Saturday, 31 August 2013

Table alias scope in informix SQL

Table alias scope in informix SQL

In the following example SQL
select * from (
select col
from myTable mt
inner join anotherMyTable amt on mt.id = amt.id
) as t
where
exists (select amt.colX from anotherMyTable amt where amt.id = 42)
The 'amt' alias is defined in two places. Is it correct to declare the
second table alias with the same name as the first or I should use another
name (amt2) ?
In this example I assume that both aliases are located in different scopes
so it's okay to use the same name. I use Informix DBMS.
p.s. it's an example SQL, the question is only about table alias scope.

Mysql subquery sum of votes

Mysql subquery sum of votes

I've got a table of votes, alongside a table of 'ideas' (entries)
Basically, I want to retrieve an object that can be read as:
id,
name,
title,
votes : {
up : x,
down : y
}
So it's simple enough until I get to the subquery and need to do two sets
of SUMs on the positive and negative values of votes.
SELECT id,name,title FROM ideas
LEFT JOIN votes ON ideas.id = votes.idea_id
My (simplified) votes table looks something like:
id
idea_id
value
Where value can be either a positive or negative int.
How would I go about getting the above object in a single query?
Bonus point: How would I also get an aggregate field, where positive and
negative votes are added together?

Multiple drop down windows that auto-close when opening another

Multiple drop down windows that auto-close when opening another

I have an example of what I'm working on here at JSFiddle
http://jsfiddle.net/OfSilence/zFuUp/. I'm trying to find a way to make the
drop-down that's opened auto close when opening another. All the solutions
I find either keep anything from opening or opening & closing everything
at the same time. Keep in mind on the final page their will be around 30
of these drop-downs. Any help would be greatly appreciated! JSFiddle

This jQuery code won't work. Beginner Here.

This jQuery code won't work. Beginner Here.

Just started practicing with jQuery, but I can't seem to get any of the
functions to work. This code below is an exercise I've been trying to run,
but it won't output the desired result. Does anyone know why? Thanks.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html lang="EN" dir="ltr" xmlns="http://www/w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type"
content="text/xml; charset=utf-8" />
<title>change2.html</title>
<script type = "text/javascript"
src = "jquery-1.4.2.min.js">
</script>
<script type = "text/javascript">
//<![CDATA[
$(document).ready(changeMe);
function changeMe(){
$("#output").html("I've changed");
}
//]]>
</script>
</head>
<body>
<h1>Using the document.ready mechanism</h1>
<div id = "output">
Did this change?
</div>
</body>
</html>

How to use terminal color palette with curses

How to use terminal color palette with curses

I can't get the terminal color palette to work with curses.
import curses
def main(stdscr):
curses.use_default_colors()
for i in range(0,7):
stdscr.addstr("Hello", curses.color_pair(i))
stdscr.getch()
curses.wrapper(main)
This python script yields the following screen:

However, I do have more colors in my gnome-terminal palette. How can I
access them within curses?

Why will the following simple grand central dispatch program not work correctly?

Why will the following simple grand central dispatch program not work
correctly?

So I was expecting the following program to print two lines. However it
doesn't print anything. Any ideas on what needs to be fixed?
#import <Foundation/Foundation.h>
#import <dispatch/dispatch.h>
int main(int argc, char **argv)
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0),
^{
printf("Done outer async\n");
dispatch_async(dispatch_get_main_queue(),^{
printf("Done inner sync");
});
});
return 0;
}
Thanks

how do i resize tinymce after changin font-size?

how do i resize tinymce after changin font-size?

Issue : when i have changed the font-size like 38pt, the text goes out of
the editor.
I am using tinymce 4.0.
This is my script to load tinymce
<script type="text/javascript">
tinymce.init({
selector: "div#textareasDiv",
theme: "modern",
inline: true,
plugins: [ "textcolor,table"],
toolbar1: " bold italic underline | alignleft aligncenter
alignright alignjustify | forecolor backcolor | fontselect |
fontsizeselect",
image_advtab: true,
menubar: false,
fixed_toolbar_container: "#toolbarCon"
});
</script>
and
<div id="textareasDiv"></div>
<div id="toolbarCon"></div>
and
<style>
#textareasDiv { padding:2px
5px;width:170px;height:80px;background:transparent;word-wrap: break-word;
}
</style>
And I am trying to get its outerHeight so that i can make change on it :
setup : function(ed)
{
ed.on('change', function(e)
{
alert($(this.getContainer()).outerHeight());
});
}
But it gives me nothing.
How can i resize tinymce editor after changing font-size?

rspec loaderrror issue during Chapter 3 of Rails Tutorial

rspec loaderrror issue during Chapter 3 of Rails Tutorial

I'm working through Michael Hartl's Rails Tutorial book and I'm on Chapter
3, trying to get the rspec test to fail as it says in the book. The only
issue is I keep getting a load error every time I run: $ bundle exec rspec
spec/requests/static_pages_spec.rb
It returns this:
atlas:sample_app Leopard$ bundle exec rspec
spec/requests/static_pages_spec.rb
/usr/local/rvm/gems/ruby-2.0.0-p247@railstutorial_rails_4_0/gems/selenium-webdriver-
2.0.0/lib/selenium/webdriver/common/zipper.rb:1:in `require': cannot
load such file -- zip/zip (LoadError)
from
/usr/local/rvm/gems/ruby-2.0.0-p247@railstutorial_rails_4_0/gems/selenium-webdriver-2.0.0/lib/selenium/webdriver/common/zipper.rb:1:in
`<top (required)>'
from
/usr/local/rvm/gems/ruby-2.0.0-p247@railstutorial_rails_4_0/gems/selenium-webdriver-2.0.0/lib/selenium/webdriver/common.rb:9:in
`require'
from
/usr/local/rvm/gems/ruby-2.0.0-p247@railstutorial_rails_4_0/gems/selenium-webdriver-2.0.0/lib/selenium/webdriver/common.rb:9:in
`<top (required)>'
from
/usr/local/rvm/gems/ruby-2.0.0-p247@railstutorial_rails_4_0/gems/selenium-webdriver-2.0.0/lib/selenium/webdriver.rb:29:in
`require'
from
/usr/local/rvm/gems/ruby-2.0.0-p247@railstutorial_rails_4_0/gems/selenium-webdriver-2.0.0/lib/selenium/webdriver.rb:29:in
`<top (required)>'
from
/usr/local/rvm/gems/ruby-2.0.0-p247@railstutorial_rails_4_0/gems/selenium-webdriver-2.0.0/lib/selenium-webdriver.rb:1:in
`require'
from
/usr/local/rvm/gems/ruby-2.0.0-p247@railstutorial_rails_4_0/gems/selenium-webdriver-2.0.0/lib/selenium-webdriver.rb:1:in
`<top (required)>'
from
/usr/local/rvm/gems/ruby-2.0.0-p247@global/gems/bundler-1.3.5/lib/bundler/runtime.rb:72:in
`require'
from
/usr/local/rvm/gems/ruby-2.0.0-p247@global/gems/bundler-1.3.5/lib/bundler/runtime.rb:72:in
`block (2 levels) in require'
from
/usr/local/rvm/gems/ruby-2.0.0-p247@global/gems/bundler-1.3.5/lib/bundler/runtime.rb:70:in
`each'
from
/usr/local/rvm/gems/ruby-2.0.0-p247@global/gems/bundler-1.3.5/lib/bundler/runtime.rb:70:in
`block in require'
from
/usr/local/rvm/gems/ruby-2.0.0-p247@global/gems/bundler-1.3.5/lib/bundler/runtime.rb:59:in
`each'
from
/usr/local/rvm/gems/ruby-2.0.0-p247@global/gems/bundler-1.3.5/lib/bundler/runtime.rb:59:in
`require'
from
/usr/local/rvm/gems/ruby-2.0.0-p247@global/gems/bundler-1.3.5/lib/bundler.rb:132:in
`require'
from /Users/Leopard/Autodidactism/Rails
Tutorial/sample_app/config/application.rb:12:in `<top (required)>'
from /Users/Leopard/Autodidactism/Rails
Tutorial/sample_app/config/environment.rb:2:in `require'
from /Users/Leopard/Autodidactism/Rails
Tutorial/sample_app/config/environment.rb:2:in `<top (required)>'
from /Users/Leopard/Autodidactism/Rails
Tutorial/sample_app/spec/spec_helper.rb:3:in `require'
from /Users/Leopard/Autodidactism/Rails
Tutorial/sample_app/spec/spec_helper.rb:3:in `<top (required)>'
from /Users/Leopard/Autodidactism/Rails
Tutorial/sample_app/spec/requests/static_pages_spec.rb:1:in `require'
from /Users/Leopard/Autodidactism/Rails
Tutorial/sample_app/spec/requests/static_pages_spec.rb:1:in `<top
(required)>'
from
/usr/local/rvm/gems/ruby-2.0.0-p247@railstutorial_rails_4_0/gems/rspec-core-2.13.1/lib/rspec/core/configuration.rb:819:in
`load'
from
/usr/local/rvm/gems/ruby-2.0.0-p247@railstutorial_rails_4_0/gems/rspec-core-2.13.1/lib/rspec/core/configuration.rb:819:in
`block in load_spec_files'
from
/usr/local/rvm/gems/ruby-2.0.0-p247@railstutorial_rails_4_0/gems/rspec-core-2.13.1/lib/rspec/core/configuration.rb:819:in
`each'
from
/usr/local/rvm/gems/ruby-2.0.0-p247@railstutorial_rails_4_0/gems/rspec-core-2.13.1/lib/rspec/core/configuration.rb:819:in
`load_spec_files'
from
/usr/local/rvm/gems/ruby-2.0.0-p247@railstutorial_rails_4_0/gems/rspec-core-2.13.1/lib/rspec/core/command_line.rb:22:in
`run'
from
/usr/local/rvm/gems/ruby-2.0.0-p247@railstutorial_rails_4_0/gems/rspec-core-2.13.1/lib/rspec/core/runner.rb:80:in
`run'
from
/usr/local/rvm/gems/ruby-2.0.0-p247@railstutorial_rails_4_0/gems/rspec-core-2.13.1/lib/rspec/core/runner.rb:17:in
`block in autorun'
I've also already scoured all of the questions with this issue but none of
the given answers in those seem to work for me. I've been stuck for about
4 hours on this.
I've also reinstalled rspec, made sure my Gemfile was saved and properly
updated and installed and still seem to get nowhere.
Here is my current Gemfile:
source 'https://rubygems.org'
ruby '2.0.0'
#ruby-gemset=railstutorial_rails_4_0
gem 'rails', '4.0.0'
gem 'bootstrap-sass', '2.3.2.0'
gem 'bcrypt-ruby', '3.0.1'
gem 'faker', '1.1.2'
gem 'will_paginate', '3.0.4'
gem 'bootstrap-will_paginate', '0.0.9'
group :development, :test do
gem 'sqlite3', '1.3.7'
gem 'rspec', '2.13.0'
gem 'rspec-rails', '2.13.1'
# The following optional lines are part of the advanced setup.
# gem 'guard-rspec', '2.5.0'
# gem 'spork-rails', github: 'sporkrb/spork-rails'
# gem 'guard-spork', '1.5.0'
# gem 'childprocess', '0.3.6'
end
group :test do
gem 'selenium-webdriver', '2.0.0'
gem 'rspec-rails', '2.13.1'
gem 'capybara', '2.1.0'
gem 'factory_girl_rails', '4.2.0'
gem 'cucumber-rails', '1.4.0', :require => false
gem 'database_cleaner', github: 'bmabey/database_cleaner'
# Uncomment this line on OS X.
# gem 'growl', '1.0.3'
# Uncomment these lines on Linux.
# gem 'libnotify', '0.8.0'
# Uncomment these lines on Windows.
# gem 'rb-notifu', '0.0.4'
# gem 'win32console', '1.3.2'
end
gem 'sass-rails', '4.0.0'
gem 'uglifier', '2.1.1'
gem 'coffee-rails', '4.0.0'
gem 'jquery-rails', '2.2.1'
gem 'turbolinks', '1.1.1'
gem 'jbuilder', '1.0.2'
group :doc do
gem 'sdoc', '0.3.20', require: false
end
group :production do
gem 'pg', '0.15.1'
gem 'rails_12factor', '0.0.2'
end
Thanks in advance for your help!

Friday, 30 August 2013

What is wrong with this TCP interaction?

What is wrong with this TCP interaction?

I have TCPServer.java:
import java.util.*;
import java.net.*;
import java.io.*;
public class TCPServer {
public static void main(String[] args) throws IOException {
ServerSocket tcp = new ServerSocket(1387);
while (true) {
Socket request = tcp.accept();
Scanner sc = new Scanner(request.getInputStream());
DataOutputStream out = new
DataOutputStream(request.getOutputStream());
System.out.println("Request count: " + sc.nextLine());
out.writeBytes("send another request please");
}
}
}
and pythonClient.py:
#!/usr/bin/python
import socket, time, sys
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((sys.argv[1], 1387))
count = 0
while True:
count += 1
sock.sendall(str(count) + "\n")
time.sleep(1)
data = sock.recv(1024)
print "received:\n", str(data)
I am running both on the same host and was expecting to receive "Request
count: x" every second with an incremented x value in the console of the
TCPServer and
received:
send another request please
every second in the terminal that is running pythonClient.py. However, all
I get is "Request count: 1" in java console and nothing else. In the
terminal, I get:
received:
s
received:
end another request please
Why is this not working as expected? Why is it all locked up after one
iteration and why did the first response from the server get accepted as
two different messages?

Thursday, 29 August 2013

WCF service fails to call another WCF service on same machine

WCF service fails to call another WCF service on same machine

I have a website hosted in IIS7 in server A. The website calls a web
service that is also hosted in server A, but the call returns an error
401. I tried referencing to the web service by IP address, host
(A.domain.com), and fully qualified dsn. None worked.
After some research, I found out about the loopback check, and the
BackConnectionHostNames.
Refer to this article
Disabling the loopback check fixes the problem, but is not a desirable
solution.
For the BackConnectionHostNames, I tried adding:
A
A.domain.com
A.full.domain.com
But it didn't work.
I played some with IIS http bindings for the website, I tried adding
A.domain.com to the host name, and I also tried setting the IP, but still
got the same error.
Am I missing something? (I clearly am...) Where else should I be looking at?
Any help appreciated. Thanks

CSS3 opacity animation no longer works on Firefox?

CSS3 opacity animation no longer works on Firefox?

I've made my backgrounds fade in with CSS3 here:
http://www.cphrecmedia.dk/musikdk/stage/artistchannel.php
It works fine, but not in Firefox (newest beta).
The funny thing though is that my small pulse animation works fine:
http://www.cphrecmedia.dk/musikdk/stage/chat.php
So it seems its the opacity-animation which wont work.
This is my code:
.fadeIn{
animation: fadein 1s;
-moz-animation: fadein 1s; /* Firefox */
-webkit-animation: fadein 1s; /* Safari and Chrome */
}
@keyframes fadein {
from {
opacity:0;
}
to {
opacity:1;
}
}
@-moz-keyframes fadein { /* Firefox */
from {
opacity:0;
}
to {
opacity:1;
}
}
@-webkit-keyframes fadein { /* Safari and Chrome */
from {
opacity:0;
}
to {
opacity:1;
}
}
Anyone who knows whats wrong?

Javascript: Object context overwritten?

Javascript: Object context overwritten?

I understand there is some sort of context mix up in the following
Javascript code I have.
Could someone explain my why I have this problem and how to solve the issue?
I have a class called Model which seems to work just fine. In this class
is a method called update(). This will perform an AJAX call to the backend
and parse the returned JSON. That's where things get tricky. The correct
query is sent to the backend and the correct JSON is sent back. However,
during parsing, there is some kind of collision or context issue between
both models.
I call the update function through another object called View. This View
object has a list of models (instances of Model). The view will then call
each update function of each view. This works great until the returned
data is parsed.
In the following code, everything is good until the line where there's the
comment "/!\ HERE /!\".
this.update = function(dbi) {
console.log('Updating model ' + this.name + '.');
var modelObj = this; // This is used to have a reference to 'this' Model
while in other contexts.
if (this.columns.length == 0) {
/* Let's build all the columns */
$("[id^='" + this.ref + "']").each(function() {
var colName = $(this).attr('id').split('-')[1];
if (modelObj.columns.indexOf(colName) == -1) {
modelObj.columns.push(colName);
}
});
}
/* Let's build the bindings. */
var allBindings = {};
for (placeholder in this.bindings) {
allBindings[placeholder] = this.bindings[placeholder].val();
}
$.post(path + 'inc/fetch.php', {
dbi : dbi,
table : this.table,
columns : btoa(this.columns),
limit : this.limit,
offset : this.offset,
distinct : this.distinct,
where : btoa(this.where),
bindings : btoa(JSON.stringify(allBindings))
}, function(data) {
if (!data.valid) {
$("#userError>p>span.userMessage").html(data.msg);
$("#userError").dialog({
width : 500,
buttons : {
'Dismiss' : function() {
$(this).dialog("close");
}
}
});
} else {
/* The data returned by the backend is simply JSON data with the
key-value pair. There is one key per row returned. */
var numRows = 0; // /!\ HERE /!\ Starting here, displaying the data
variable will always display the first of two objects.
for ( var rowID in data) {
if (rowID == 'valid')
continue;
numRows++;
for (column in data[rowID]) {
console.log('[' + modelObj.str() + '] setting #' + modelObj.ref +
'-' + column + ' to [' + data[rowID][column] + ']');
var el = $('#' + modelObj.ref + '-' + column);
var val = data[rowID][column];
switch (el[0].nodeName) {
case "SELECT":
el.html('<option val="' + val + "'>" + val + "</option>");
break;
case "TD":
el.text(val);
break;
case "INPUT":
el.val(val);
break;
default:
console.log('Dont know how to display "' + val + '"!');
}
}
}
if (numRows < modelObj.columns.length) {
for ( var cNo in modelObj.columns) {
var column = modelObj.columns[cNo];
console.log("col = " + column);
console.log('data');
console.log(data);
console.log('columns');
console.log(modelObj.columns);
console.log('[0] of ' + '#' + modelObj.ref)
var par = $('#' + modelObj.ref).nodeName;
var el = $('#' + modelObj.ref + '-' + column);
var val = data[0][column];
switch (par) {
case "SELECT":
el.html('<option val="' + val + "'>" + val + "</option>");
break;
case "TABLE":
var limit = $('#' + modelObj.ref + ">tr").length - 1; // The
first line (tr) is the header.
for ( var missingRow in limit) {
if (data.hasOwnProperty(missingRow) == 0 ||
data[missingRow].hasOwnProperty(column) == 0) {
console.log('[' + modelObj.str() + '] setting #' +
modelObj.ref + '-' + column + ' to [N/A]')
$('#' + modelObj.ref + '-' + column + '-' +
missingRow).text('N/A');
}
}
break;
case "INPUT":
el.val(val);
break;
default:
console.log('Dont know how to display "' + val + '"!');
}
}
}
}
}, "json");
};
Any thought is helpful. Thanks in advance.

Wednesday, 28 August 2013

Making scrollbars work with the WeifenLuo Dock Panel Suite

Making scrollbars work with the WeifenLuo Dock Panel Suite

I have the following code, which is basically a ToolStrip menu item:
private void addRoomToolStripMenuItem_Click( object sender,
System.EventArgs e )
{
frmRoom newRoom = new frmRoom();
dockPanel.Scroll += dockPanel_Scroll;
dockPanel.VerticalScroll.Visible = true;
dockPanel.VerticalScroll.Enabled = true;
dockPanel.VerticalScroll.Maximum = newRoom.Height;
dockPanel.VerticalScroll.SmallChange =
dockPanel.VerticalScroll.Maximum / 8;
dockPanel.VerticalScroll.LargeChange =
dockPanel.VerticalScroll.Maximum / 4;
newRoom.Show( dockPanel, DockState.Document );
}
void dockPanel_Scroll( object sender, ScrollEventArgs e )
{
dockPanel.VerticalScroll.Value = e.NewValue;
}
For some reason I cannot get the vertical scrollbar to work properly with
the Dock Panel Suite. The scrollbar always goes to the top and the dock
panel does not scroll up as expected.
As there is no documentation on the web for this control I am hoping that
somebody can point me in the right direction.
Thanks.

Paging a changable collection

Paging a changable collection

Paging using LINQ can be easily done using the Skip() and Take() extensions.
I have been scratching my head for quite some time now, trying to find a
good way to perform paging of a dynamic collection of entities - i.e. a
collection that can change between two sequential queries.
Assume a query that without paging will return 20 objects of type MyEntity.
The following two lines will trigger two DB hits that will populate
results1 and results2 with all of the objects in the dataset.
List<MyEntity> results1 = query.Take(10).ToList();
List<MyEntity> results2 = query.Skip(10).Take(10).ToList();
Now let's assume the data is dynamic, and that a new MyEntity is inserted
into the DB between the two queries, in such a way that the original query
will place the new entity in the first page.
In that case, results2 list will contain an entity that also exists in
results1,
causing duplication of results being sent to the consumer of the query.
Assuming a record from the first page was deleted, it will result missing
a record that should have originally appear on results2.
I thought about adding a Where() clause to the query that verify that the
records where not retrieved on a previous page, but it seems like the
wrong way to go, and it won't help with the second scenario.
I thought about keeping a record of query executions' timestamps,
attaching a LastUpdatedTimestamp to each entity and filtering entities
that were changed after the previous page request. That direction will
fail on the third page afterwards...
How is this normally done?
Is there a way to run a query against an old snapshot of the DB?

How to explode a Dictionary List as headers in a format-table

How to explode a Dictionary List as headers in a format-table

Sorry for the title, not sure how to label this question. I want to
express a list of Dictionary objects with Key as Header/Property and Value
as the header/property value.
For example take the following PoSH code
$obj1 = new-object object | select Data; $obj1.Data =
@{"header1"="Value1";"header2"="Value2";}
$obj2 = new-object object | select Data; $obj2.Data =
@{"header1"="ValueA";"header2"="ValueB";}
$tmp = @($obj1,$obj2)
$tmp then looks like the following:
Data
----
{header2, header1}
{header2, header1}
$tmp | select -Expand Data gets the following useful information
Name Value
---- -----
header2 Value2
header1 Value1
header2 ValueB
header1 ValueA
Anyway I can pivot the data and turn the Names into Properties (or
headers) and express them with values i.e.
header1 header2
---- -----
Value1 ValueB
ValueA Value2

How to I trick Java RMI/JMX to be accesible from outside localhost without hardcoding the IP?

How to I trick Java RMI/JMX to be accesible from outside localhost without
hardcoding the IP?

How to I trick Java RMI to be accesible from outside localhost without
hardcoding the IP ?

split text with delimiters + int between 0-9

split text with delimiters + int between 0-9

I have to write a function that display string typed by the user , with
color in a textview.
Exemple : ^1Hi ^2 everyone:
"Hi" = red color because because there is "^1" before
"Everyone" = green color beacause there is "^2" before.
So I think I have to use split function like this :
String txt = myEditText.getText().toString();
String[] splits = txt.split("\\^(\\d+)");
But I don't know how to get number typed after "^".
And then I want tout assign a color with the number types.
And I think I can use :
MyTextView.setText(HTML.fromHtml(myTextModifiedWithColor);
So if you have any idea, it would be very appreciated.

Tuesday, 27 August 2013

Rails 4: prevent 'to_json' from adding a root node?

Rails 4: prevent 'to_json' from adding a root node?

This feels like it should be simple, but after Googling for an hour I
can't figure this out.
I'm POSTing an Amazon S3 'policy document' as JSON to my server. I need to
encode the JSON as is, but Rails is adding stuff to 'params' which is
cluttering the JSON I need to encode.
Here is what I have:
class Api::Amazons3Controller < Api::BaseController
def sign_policy
policy_document = params.except(:action, :controller)
encoded_policy_document =
Base64.encode64(policy_document.to_json).gsub(/\n|\r/, '')
signature = Base64.encode64(
OpenSSL::HMAC.digest(
OpenSSL::Digest::Digest.new('sha1'),
ENV['AWS_SECRET_ACCESS_KEY'],
policy_document)
).gsub(/\n/, '')
response = { policy: policy_document, signature: signature }
render json: response
end
end
I'm trying to 'clean up' the params with params.except(:action,
:controller), but policy_document.to_json adds a root note called
'amazons3' (the controller name) around the JSON, which I don't want. I
just need to encode the pure json from the request.
Any help would be highly appreciated!

iOS 7 app termination issue

iOS 7 app termination issue

I am working on an iOS application which gets terminated by iOS after
hours (4-5 hrs) of inactivity in background (I have proper logs which
support that iOS terminates the app and moreover I see no crashes in the
app). I understand this is pretty usual as iOS has the right to purge the
memory of the app and terminate it under any memory pressure. Moreover iOS
7 is still in beta phase, so I am sure there are improvements waiting to
show up in the market version.
But what baffled me is it is happening more often in iOS 7 than iOS 6. I
ran tests on iOS 6 and iOS7 with the same number of apps running in
background along with my app. After a few hours I see my app getting
terminated in iOS 7 and not in iOS 6.
Now my question is there any evidence about apps being terminated more in
background in iOS 7.
Moreover do you see the new background modes introduced in iOS 7, fetch
and remote-notification, do any good to my app from being terminated.
Note: My app has the background mode set as "App communicates with an
accessory". I tested my app on iOS 7 Beta 6 version.

Regex to only let two words: either male or female

Regex to only let two words: either male or female

I need to let through into SQL query only two words: either male or female
I use PHP function that returns:
return preg_replace( "/([male|female])/i", '', $data );
At the moment it removes these words but how do I delete absolutely
everything and let only
either male or female?
What am I missing here?

Mozilla Firefox caching even though cach is set to 0 MB?

Mozilla Firefox caching even though cach is set to 0 MB?

I've stumbled upon a strange phenomenon with Mozilla Firefox. When I'm
loading a page with a single checkbox on it and I check the checkbox
without saving this state to the database (and getting it again), I
normally would expect that the checkbox is not checked then when I reload
the page.
But when I clicked on "reload page" (or used F5) it displayed a checked
checkbox. Only when I used either opened the page in a new window, OR
clicked into the url input and used enter to reload the page (or used
ctrl-F5) the page was shown with an unchecked checkbox.
First thought was "caching", but when I set caching memory to 0 MB (and
cleared the cache) the phenomenon was still the same.
So my question is 3 fold there: a.) Is that phenomenon still caching? b.)
Is there any option under firefox that can I overlooked that could stop
this strange behaviour? c.) Is the only option to stop this behaviour by
using: "Cache-Control: no-cache, no-store"?
Tnx
Tnx.

ListViewItem.ForeColor Change Doesn't Display

ListViewItem.ForeColor Change Doesn't Display

I'm using the following code to change the ForeColor of items for which a
selected action has already been performed.
internal static void grayOut(ref ListView myLV)
{
//change each selected item to gray text
//currently, multiselect is turned off, so this will only be one
item at a time
foreach (ListViewItem item in myLV.SelectedItems)
{
item.UseItemStyleForSubItems = false;
item.ForeColor = Color.Gray;
item.Font = new Font("MS Sans Serif", 10, FontStyle.Italic);
item.Selected = false;
}
myLV.Refresh();
}
I have two problems.
The property changes, but that change does not display. In other words, I
know that the ForeColor is changed to gray, because later I check to see
if it is gray when the user tries to perform a certain action. However, it
doesn't appear gray or italicized.
I'm also using the following to try and cancel a MouseDown event to keep
the item from being selected again, but it still ends up being selected:
private void lvUsers_MouseDown(object sender, MouseEventArgs e)
{
// Make sure it was a single left click, like the normal Click event
if (e.Button == MouseButtons.Left)
{
ListViewHitTestInfo htInfo = lvUsers.HitTest(e.X, e.Y);
if (htInfo.Item.ForeColor == Color.Gray)
{
return;
}
}
}
I haven't found any other method for cancelling a MouseDown event, so I'm
not sure what else to try.

Is there a difference between Zoƫ and Zoe in SEO

Is there a difference between Zoë and Zoe in SEO

I'm finishing of a website for a Blues band called Zoë Schwarz Blue
Commotion, her name is Zoë
In terms of SEO do the search engines see any difference between Zoë and
Zoe. I think the vast majority of people when searching will type Zoe as
most people won't know where the ë is.
It would be nice to use her name Zoë but would this affect our SEO efforts?
Roy

cURL with HTML content

cURL with HTML content

I need to post to a URL and I am doing this with curl. But the problem is
with the HTML content I am posting. I am using this page which I am
requesting to send an html email. So it will have inline styles. When I
urlencode() or rawurlenocde() these style attribute is stripped. So the
mail will not look correct. How can I avoid this and post the HTML as it
is ?

Monday, 26 August 2013

Which one is indicating the exact memory use for java application

Which one is indicating the exact memory use for java application

I have a java application. The issue now I take a heap using the jmap and
I also got this codes running in my application.Both are giving me
different values. The runtime is showing out of 256mb which is what I have
assigned as initial and maximum memory? I want to detect is there any
memory leakage but the runtime is fluctuating and whereas the one from
heap is keep increasing in small amount? Any help on this?
long memory = runtime.totalMemory() - runtime.freeMemory();
System.out.println("\n\nUsed memory is bytes: " +
memory);
//Print the jvm heap size.
long heapSize = runtime.totalMemory();
System.out.println("\n\nHeap Size = " + heapSize);
int mb = 1024*1024;
System.out.println("##### Heap utilization
statistics [MB] #####");
//Print used memory
System.out.println("Used Memory:"
+ (runtime.totalMemory() -
runtime.freeMemory()) / mb);
//Print free memory
System.out.println("Free Memory:"
+ runtime.freeMemory() / mb);
//Print total available memory
System.out.println("Total Memory:" +
runtime.totalMemory() / mb);
//Print Maximum available memory
System.out.println("Max Memory:" +
runtime.maxMemory() / mb);

How to use dynamic key name in object during object construction?

How to use dynamic key name in object during object construction?

I want to use a dynamic key name during the creation of the object.
var myKey = 'text';
var myObj = {
[myKey]: 'Hello' // not working
};
alert(myObj.text);
I know you can do it on the next line after the object is created
myObj[key] = 'someValue', but I was curious about doing it when you're
creating the object.
There's a plethora of similar questions about it, but they all do it after
the object has been created using the [] notation.

Android App beta/alpha test apk not installing

Android App beta/alpha test apk not installing

My company has an app published in the google play store/android
marketplace. One of the issues that we're fixing in the next version of
the app is adding back xlargeScreen = true (it was somehow set to false in
the previous version, so now the app isn't showing up on larger tablets).
We're trying to get the alpha/beta testing setup so we can make sure we
have all our problems fixed before we push the apk to live.
I've uploaded an apk to alpha and published it. I made a google+
community, added it to the accepted testers and sent out the link for the
app. But, when we go out to the link and get set as testers nothing
happens. If I go to the google play store, it shows the date for the
newest upload to the account but the 'install' button attempts to install
the previous live version (which is incompatible with the test device,
yay!). Also someone else used their device and all the install did was
install the old version to their device.
I've considered the "wait up to 24 hours for the publish to go through"
being the problem, but the first alpha was uploaded Friday at lunch and
would not work at lunch today, on Monday. I moved the old apk to beta and
put a new one in alpha (more bug fixes yay) at lunch today. I checked all
the settings and everything looks correct, but I can't see how I'm suppose
to actually download the beta or the alpha at this point. And if I'm
suppose to download the production version 1) How am I suppose to do that
on the device that's incompatible with the production version and 2) how
do I choose between the beta and the alpha version?

How can I get my Macs to see my SAMBA file sharing server?

How can I get my Macs to see my SAMBA file sharing server?

I have recently set up a SAMBA file share. After going through a series of
steps, I have finally been able to have most of my computers see this
server. The primary requirements were: 1) it had to be password protected,
2) have multiple users, 3) each user can own a file, but all users can
write to each others' files.
I am in an office with 5 Macs, 1 Linux Server (Ubuntu 13.04), 1 Windows
Server (Windows 2008 R2), and three Windows XP Pro desktops. All computers
can access the share properly, except the Macs.
Oddly enough, ONE Mac is able to view the share and login. All the other
Macs fail to login after putting in the username and password.
Here are the contents of my smb.conf file:
[global]
workgroup = workgroup
server string = %h server (Samba, Ubuntu)
dns proxy = no
log file = /var/log/samba/log.%m
max log size = 1000
syslog = 0
panic action = /usr/share/samba/panic-action %d
security = user
encrypt passwords = yes
obey pam restrictions = yes
unix password sync = yes
passwd program = /usr/bin/passwd %u
passwd chat = *Enter\snew\s*\spassword:* %n\n
*Retype\snew\s*\spassword:* %n\n *password\supdated\ssuccessfully* .
pam password change = yes
map to guest = bad user
usershare allow guests = yes
username map = /etc/samba/smbusers
guest ok = no
guest account = nobody
comment = Home Directories
browseable = no
read only = no
create mask = 0775
directory mask = 0775
[printers]
comment = All Printers
browseable = no
path = /var/spool/samba
printable = yes
; guest ok = no
; read only = yes
create mask = 0700
[print$]
comment = Printer Drivers
path = /var/lib/samba/printers
[interactive]
path = /home/shok07a/interactive
writeable = yes
browseable = yes
comment = interactive
create mask = 0777
directory mask = 2777
force directory mode = 2777
guest ok = no
force group = sambashare

Can't combine alias with fastcgi_cache in Nginx

Can't combine alias with fastcgi_cache in Nginx

This works:
location ~ ^/special/(.+\.php)$ {
alias /var/special/$1;
try_files "" =404;
include fastcgi_params;
fastcgi_pass 127.0.0.1:9000; # php-fpm socket
}
But this doesn't:
location ~ ^/special/(.+\.php)$ {
alias /var/special/$1;
try_files "" =404;
include fastcgi_params;
fastcgi_pass 127.0.0.1:9000; # php-fpm socket
fastcgi_cache mycache;
}
If I try to go to the URL "/special/index.php" I get a "File not found."
text in the browser, which I assume comes from php-fpm or PHP. And I get
this error in the Nginx log:
FastCGI sent in stderr: "Primary script unknown", client: 202.179.27.65,
server: myserver.org, request: "GET /special/index.php HTTP/1.1", host:
"myserver.org"
Any idea why adding fastcgi_cache breaks this?
Note that fastcgi_cache works fine when I use a location that doesn't use
an alias.

Does string.IsNullOrEmpty have performance issues?

Does string.IsNullOrEmpty have performance issues?

Is there any difference between this two ways of checking the string?
if(!string.IsNullOrEmpty(myString))
{
//Do something
}
and
if(!myString != null && !myString != "")
{
//Do something
}
So far I though no, but someone is saying so. And he's saying that the
second one is better as the first one requires a method call.
I'm a little confused.

WEB AUDIO API - How to get audio data after filtering in WEB AUDIO API?

WEB AUDIO API - How to get audio data after filtering in WEB AUDIO API?

I have two problems in WEB AUDIO API.
First, i opened mp3 file and did audio processing with Javascript. After
that, it passed to filter as biquadfilter. at this moment, i wanna get
processed audio buffer array data and analysis it but i couldn't get audio
buffer array. How can i get audio buffer array that passed the filter
section ?
Second, i'd like to open two files and after that, i wanna do some
calculation between two files. how can i do that ? in detail, i'd like to
minus second file from first file. for to do, i should know audio buffer
array data of them.

Amazon EC2 inbound filter for private IP

Amazon EC2 inbound filter for private IP

I have two ec2 instaces created in Amazon cloud, one with public
IP(Elastic IP), and another with only private IP 172.31.5.151. Then, set
security group to the instance with public IP to limit https inbound
access like 172.31.5.151/32
But it doesn't work. When I chanage the https inbound filter to 0.0.0.0/0,
then everything works fine. The question is: how to set inbound filter for
a private IP?
Thanks.

Sunday, 25 August 2013

Custom accessoryView image and accessoryButtonTappedForRowWithIndexPath

Custom accessoryView image and accessoryButtonTappedForRowWithIndexPath

I am trying to get a custom image working with the
accessoryButtonTappedForRowWithIndexPath function. From what I understand
in order to do this, you have to use a UIBUtton, simply adding a
UIImageView on the UITableViewCellAccessoryDetailDisclosureButton will not
work.
My problem is how to get the touch gesture from my UITableViewCell
subclass into the parent UITableView function.
Here is the code in my TableViewCell subclass:
upVote = [UIButton buttonWithType:UIButtonTypeCustom];
UIImage *upVoteImg = [UIImage imageNamed:@"vote.png"];
upVote.frame = CGRectMake(self.frame.size.width-upVoteImg.size.width, 0,
upVoteImg.size.width , upVoteImg.size.height);
[upVote setBackgroundImage:upVoteImg forState:UIControlStateNormal];
[self.contentView addSubview:upVote];
[upVote addTarget:self action:@selector(checkButtonTapped:event:)
forControlEvents:UIControlEventTouchUpInside];
The calling function (also inside the subclass of the TableViewCell
- (void)checkButtonTapped:(id)sender event:(id)event
{
UITableView *tableView = (UITableView *)self.superview;
[tableView.delegate tableView:tableView
accessoryButtonTappedForRowWithIndexPath:[tableView
indexPathForCell:self]];
}
It crashes at the final line of the above function with this:
* Terminating app due to uncaught exception 'NSInvalidArgumentException',
reason: '-[UITableViewWrapperView delegate]: unrecognized selector sent to
instance 0x16f48160'

Trouble after Skype installation: libqtgui4:i386,libtiff4:i386,libqt4-declarative:i386,libqtwebkit4:i386,

Trouble after Skype installation:
libqtgui4:i386,libtiff4:i386,libqt4-declarative:i386,libqtwebkit4:i386,

I am using the Ubuntu Precise.
Trouble in configuration after Skype (downloaded from the site of Skype)
installation.
The results shown below as consequence of the commands:
sudo apt-get update
sudo apt-get -f install
sudo dpkg --configure -a
(the language of the system was configured for Portuguese)



sudo apt-get update
sudo apt-get -f install
Desempacotando libtiff4:i386 (de .../libtiff4_3.9.5-2ubuntu1.5_i386.deb) ...
dpkg: erro processando
/var/cache/apt/archives/libtiff4_3.9.5-2ubuntu1.5_i386.deb (--unpack):
'./usr/share/lintian/overrides/libtiff4' is different from the same file
on the system
Erros foram encontrados durante o processamento de:
/var/cache/apt/archives/libtiff4_3.9.5-2ubuntu1.5_i386.deb E: Sub-process
/usr/bin/dpkg returned an error code (1)
sudo dpkg --configure -a
dpkg: problemas de dependência impedem a configuração de libqtgui4:i386:
libqtgui4:i386 depende de libtiff4; porém: Pacote libtiff4:i386 não está
instalado.
dpkg: erro processando libqtgui4:i386 (--configure): problemas de
dependência - deixando desconfigurado
dpkg: problemas de dependência impedem a configuração de
libqt4-declarative:i386: libqt4-declarative:i386 depende de libqtgui4 (=
4:4.8.1-0ubuntu4.4); porém: Pacote libqtgui4:i386 não está configurado
ainda.
dpkg: erro processando libqt4-declarative:i386 (--configure): problemas de
dependência - deixando desconfigurado
dpkg: problemas de dependência impedem a configuração de
libqtwebkit4:i386: libqtwebkit4:i386 depende de libqtgui4 (>= 4:4.8.0);
porém: Pacote libqtgui4:i386 não está configurado ainda.
dpkg: erro processando libqtwebkit4:i386 (--configure): problemas de
dependência - deixando desconfigurado
dpkg: problemas de dependência impedem a configuração de skype:i386:
skype:i386 depende de libqtgui4 (>= 4:4.8.0); porém: Pacote libqtgui4:i386
não está configurado ainda.
skype:i386 depende de libqtwebkit4 (>= 2.2~2011week36); porém: Pacote
libqtwebkit4:i386 não está configurado ainda.
dpkg: erro processando skype:i386 (--configure): problemas de dependência
- deixando desconfigurado
Erros foram encontrados durante o processamento de:
libqtgui4:i386
libqt4-declarative:i386
libqtwebkit4:i386
skype:i386



Although there is these troubles, the Skype is working.
However, I tried to change the language of the system for English and it
wasnt possible.
Regards,
Juracy

Getting data object in button's (located in ListView row) listener

Getting data object in button's (located in ListView row) listener

Okay, title is propably unclear, here is what i want to do: I have
ListView and inside each row there is some text and a button. I'm setting
listener to each button (in my custom list Adapter) like that:
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater li;
li = LayoutInflater.from(context);
convertView = li.inflate(R.layout.list_item, null);
}
Item elem = elems.get(position);
TextView mainText = (TextView) convertView.findViewById(R.id.main_text);
TextView sideText = (TextView) convertView.findViewById(R.id.side_text);
mainText.setText(elem.desc);
sideText.setText(timestampToString(elem.date));
Button againButton = (Button) convertView
.findViewById(R.id.itemAgainButton);
againButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// onClick actions
}
});
Now inside onClick method i need to acces Item object from which current
row was created. I'm not sure if it's clear what i want to do. Here i'm
setting listener on ListView elements in my Activity class
lista.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Item item = (Item) parent.getItemAtPosition(position);
Intent i = new Intent(getApplicationContext(),
DidItItemActivity.class);
i.putExtra("id", item.id);
startActivity(i);
}
});
and I can use parent.getItemAtPosition(position) which gives me exactly
what i need. How can i do the same in Adapter class?

Inversion of return value

Inversion of return value

I have a flag that I want to pass to a function which returns true or
false based on a value in a map:
// userList is a List<String> and is stored as the value field in a map
// user is a String
if(flag)
{
if (userList == null)
return false;
else if(userList.size() == 0)
return true;
return userList.contains(user);
}
else
{
if (userList == null)
return true;
else if(userList.size() == 0)
return false;
return !userList.contains(user);
}
My question is this: is there anyway to tidy this code up, there is a lot
of replication (the if and else block are identical, except their return
values are the opposite of each other).
I'm not a very experienced code, and I'd really appreciate some guidance!

show hidden div below current row of divs in responsive layout with jquery

show hidden div below current row of divs in responsive layout with jquery

I have a responsive layout for an image gallery that will show 3, 2 or 1
images per row based on user's screen width. here is the part of the CSS
that will decide how many images to show per row:
@media only screen and (max-width : 480px) {
/* Smartphones: 1 image per row */
.box {
width: 100%;
padding-bottom: 100%;
}
}
@media only screen and (max-width : 650px) and (min-width : 481px) {
/* Tablets: 2 images per row */
.box {
width: 50%;
padding-bottom: 50%;
}
}
@media only screen and (min-width : 651px) {
/* large screens: 3 images per row */
.box {
width: 33.3%;
padding-bottom: 33.3%;
}
}
for each ".box" div, there is another (initially hidden) div that should
be displayed below the current row of images when tapping a button.
on a desktop browser showing three images per row, it would look like this
<div class="box">
<div class="boxInner">
<img src="../img/img1.jpg">
<div class="infoBox">
<button class="detailLink" name="det1">Show Details</button>
</div>
</div>
</div>
<div class="box">
<div class="boxInner">
<img src="../img/img2.jpg">
<div class="infoBox">
<button class="detailLink" name="det2">Show Details</button>
</div>
</div>
</div>
<div class="box">
<div class="boxInner">
<img src="../img/im3.jpg">
<div class="infoBox">
<button class="detailLink" name="det3">Show Details</button>
</div>
</div>
</div>
<div class="detailWrapper" id="det1">
<div class="detail">Details for img1</div>
</div>
<div class="detailWrapper" id="det2">
<div class="detail">Details for img2</div>
</div>
<div class="detailWrapper" id="det3">
<div class="detail">Details for img3</div>
</div>
This is the script that will toggle the divs with details:
<script>
$(".detailLink").click(function () {
var id = $(this).attr("name");
$("#"+id).slideToggle("slow");
});
</script>
But if I resize the browser window so that only one or two images per row
are displayed, obviously the initially hidden div for the first and second
image will not be displayed below the first row anymore, but below the
second row.
I have no idea how to rewrite this code so it will display the initially
hidden div always in the row below the actual image, no matter if 1, 2 or
3 images are displayed per row. I could create three separate pages and
redirect browsers to them based on screen width, but that seems somewhat
redundant and there must be a better solution.
My first question on Stackoverflow - hope I did it right.

Saturday, 24 August 2013

Automatic check-in in visual studio 2012

Automatic check-in in visual studio 2012

Every time I hit save in my visual studio 2012 It tries to check-in and
most of the times it fails.!!! I'm using Microsoft TFS server itself.
Now my question is How can I make it stop from auto checking-in?
I tried to disable it from option->source control-> environment but there
is not option to disable the auto checking-in on saving in Saving drop
down.
I want to save my project locally and check-in when ever I want and not
automatically.

Ubuntu suspend problem

Ubuntu suspend problem

Ubuntu cannot be suspended. While using Ubuntu I sometimes need to suspend
the OS for multiple reasons. In my case when I either suspend using the
command or by the option above shutdown or just put down the screen the
laptop gets suspended but while opening up gets to a blinking screen with
extremely thin colour stripes blinking for a fraction of a second.

Dynamically calculate table heading widths using javascript - how to? (PHP -> javascript variable assignment)

Dynamically calculate table heading widths using javascript - how to? (PHP
-> javascript variable assignment)

I'm currently attempting to write a dynamic table where the heading width
is split in equal widths equally across the required number of columns
(PHP variable "$numberofcolumns").
Firstly, could someone please give me a hand popping some more code in
that would make it easy for me to calculate the table heading widths
dynamically? So far I have only got as far as turning the php variable
into a JavaScript variable $noofcolumns -> var columnno as shown below -
I'm now completely lost!
My total table width remaining to use is 80% (20% already used for a fixed
width column).
i.e.
if columnno = 3 -> table heading width = 80% / 3
if columnno = 4 -> table heading width = 80% / 4
etc...
I have tried using the calc() CSS3 function previously, but this doesn't
display correctly in a fair amount of browsers! (hence the requirement for
javaScript!) Due to this issue, it would be easier if the outcome of the
JavaScript code gave a value in pixels!
<script type="text/javascript">
var columnno = <?php echo $numberofcolumns; ?>;
</script>
Secondly, am I correct in thinking that I can retrieve the calculated
JavaScript variable (as javaScript is client side...) by using a PHP
function such as: $_REQUEST['javascript_variable_name_here']?

Multiple results from an SQL query

Multiple results from an SQL query

I am not 100% sure how to phrase this question. I searched through the
archives as much as I could but could not find what I was looking for.
I have three database tables.
tblSeason(Id,Season)
tblPlayers(ID,FirstName,LastName,DisplayName,Handicap,Current)
tblMatch(ID,MatchDate,Season,Player1,Player2,Player1Score,Player2Score,Winner)
I have been trying to work out how to return something like the following.
Player1
Player2 -- 2 Games Against
Player3 -- 1 Game Against
Player2
Player1 -- 2 Games Against
Player3 -- 3 Games Against
Thanks

Changing path to folder on server

Changing path to folder on server

Is it possible to change this script to direct it's path to a folder?
<script>
$('#container').waterfall({
itemCls: 'item',
colWidth: 222,
gutterWidth: 15,
gutterHeight: 15,
checkImagesLoaded: false,
path: function(page) {
return 'data/data1.json?page=' + page;
}
});
</script>
I already have a PHP script works in finding the server folder.
<?php
$dirname = "photos/home/";
$images = scandir($dirname);
shuffle($images);
$ignore = Array(".", "..");
foreach($images as $curimg){
if(!in_array($curimg, $ignore)) {
echo "<img src='img.php?src=".$dirname.$curimg." ' />\n";
}
}
?>
Is it possible to combine both scripts together either in PHP our jquery?
Thank you.
Erik

How to wait till the response comes from the $http request, in angularjs?

How to wait till the response comes from the $http request, in angularjs?

I am using some data which is from a RESTful service in multiple pages. So
I am using angular factories for that. So, I required to get the data once
from the server, and everytime I am getting the data with that defined
service. Just like a global variables. Here is the sample:
var myApp = angular.module('myservices', []);
myApp.factory('myService', function($http) {
$http({method:"GET", url:"/my/url"}).success(function(result){
return result;
});
});
In my controller I am using this service as:
function myFunction($scope, myService) {
$scope.data = myService;
console.log("data.name"+$scope.data.name);
}
Its working fine for me as per my requirements. But the problem here is,
when I reloaded in my webpage the service will gets called again and
requests for server. If in between some other function executes which is
dependent on the "defined service", It's giving the error like "something"
is undefined. So I want to wait in my script till the service is loaded.
How can I do that? Is there anyway do that in angularjs?

Probability in toin coss

Probability in toin coss

Suppose that you have a fair coin. You start with $\$0$. You win $\$1$
each time you get a head and loose $\$1$ each time you get tails.
Calculate the probability of getting $\$2$ without getting below $\$0$ at
any time.

Can't set focus() on any input element which is opened with fancybox

Can't set focus() on any input element which is opened with fancybox

I made a login form opened with fancybox, and I'd like to set the first
input as autofocus after the form is opened up. But I tried every way
possible found on internet to make that happen, still with no luck.
Can anyone help me plz?

Moving ruby and rubygems into a custom path

Moving ruby and rubygems into a custom path

I have a local ruby interpreter created a third party which is installed
under /usr/lib/projectA/ruby/bin/ruby
Now, I want to copy the whole folder strcuture into another folder with
the same structure: /usr/lib/projectB/ruby/bin/ruby
After I copied the files, and call the copied ruby, e.g.
# /usr/lib/projectB/ruby/bin/ruby -v
ruby 1.9.x
Seems to be working, however, when I run
# /usr/lib/projectB/ruby/bin/ruby -e 'puts 1'
<internal:gem_prelude>:1:in `require': cannot load such file --
rubygems.rb (LoadError)
from <internal:gem_prelude>:1:in `<compiled>'
Seems it can't find the rubygems, so I add the path
# /usr/lib/projectB/ruby/bin/ruby -e 'puts 1' -I
'/usr/lib/projectB/ruby/lib/'
/usr/lib/projectB/ruby/lib/ruby/1.9.1/rubygems.rb:31:in `require': cannot
load such file -- rbconfig (LoadError)
Now, another files cannot be loaded, so I assume more to come..
So
What is the correct method to set the new rubygems base path for my new ruby?
Why even calling puts 1 will invoke the rubygems?
p.s. I can't use rvm or similar approach as we need to deploy the whole
zip package with the ruby to our user.

Friday, 23 August 2013

Editing one column of a table in a BD

Editing one column of a table in a BD

I have a _mybb database and i want to edit on column of the mybb_users
table The column is the displaygroup column Iv looked all over the net and
can't figure out/find the sql query to use to do this! Can anyone help?

Test a server using MTR through TCP

Test a server using MTR through TCP

Is it possible to use MTR over TCP? If not is there an alternative? I have
done some research and I am not finding any way to do such a thing, so I'm
wondering if anyone has had any experience with doing such a thing. If
there really is no such thing what is the best way to do an extended test
with very rapid ICMP requests to a MySQL server from a network perspective
so we can troubleshoot a very quick packet loss issue through the network.

@Autowired entityManagerFactory is null

@Autowired entityManagerFactory is null

My app can't autowire entityManagerFactory.
My applicationContext.xml:
<bean id="persistenceUnitManager"
class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager">
<property name="persistenceXmlLocation">
<value>classpath:jpa-persistence.xml</value>
</property>
</bean>
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitManager" ref="persistenceUnitManager" />
</bean>
<bean id="transactionManager"
class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
My java class:
public class Engine {
@Autowired
@Qualifier("entityManagerFactory")
private EntityManagerFactory entityManagerFactory;
......
}
Question:
Why entityManagerFactory is null?

Code review for Xcode Projects

Code review for Xcode Projects

The best application or platform for code review in iOS ? Please propose
an application or platform good for code reviews for team iOS.

sudo: source: command not found when executing tcl as sudo

sudo: source: command not found when executing tcl as sudo

I have a test.tcl (has all permissions) which contains the following-
#!/usr/bin/tclsh
puts "hello, world"
This is how I'm executing my tcl script-
sudo source /opt/test.tcl
I got the output-
sudo: source: command not found
But I checked the availability of source and sudo using whereis command
and they were available-
$ whereis sudo
sudo: /usr/bin/sudo /usr/share/man/man8/sudo.8.gz
$ whereis source
source: /usr/share/man/man1/source.1.gz
However, when I attempt to execute tcl as-
sudo tclsh /opt/test.tcl
I get the expected output-
hello, world
Am I missing something here?

Thursday, 22 August 2013

converting apple-tab-space into

converting apple-tab-space into

is there a library that convert apple-tab-space into &nbsp; character ?
if there is none, can you please suggest an efficient way in doing so?
Im having some trouble with my code editor using contenteditble div
(nevermind)

create new object? or reuse existing one?

create new object? or reuse existing one?

What is good practice in JavaScript when you need to wipe out data and put
new data?
I use Dojo's Memory and dGrid to display my data. the data gets retrieved
every time user clicks 'refresh' button.
the refresh button won't be called many times during the lifetime of the
application. I have the following code for the grid
store = new Memory();
grid = new OnDemandGrid({
selectionMode: 'single',
store: store
});
and the code above is currently run in the method that initialises the
application.
and I have another method called 'showGrid' which will decide the layout
of the grid.
and the store is updated when the application receives message with new data.
My concern is, Memory does not have method for wiping out its data. so I
have to loop through the store and put the new data. Whereas if I don't
reuse the store and just create new one, it would be easier or faster.
Then why wouldn't I just create store in the 'showGrid' method and let it
creates store every time user clicks refresh? Speed or memory is not a big
concern in the application since data is not that big.
But I want to achieve this in terms of "the correct way" because I learnt
creating new objects when it is reusable is important back in my uni days
(although it was Java Class not JavaScript).
Thanks in advance :)

1080p raspberry pi on debian/raspbian/xbmc

1080p raspberry pi on debian/raspbian/xbmc

I am getting started on my HTPC raspberry pi build. I was wondering if I
use xbmc I absolutely need to buy the codec to play all videos (if it is
not hardware accelerated would it play if I overclocked it?)
also if i use raspbian with Omxplayer, do I still need to buy the licence?
Thanks

How do I write php code to send JSON data from MySQL database to my AngularJS application

How do I write php code to send JSON data from MySQL database to my
AngularJS application

I'm trying to wire up my angularjs application to get JSON data from a
database (mySQL), using PHP as the server-side language (a language I
taught myself this summer, and am most comfortable with).
Having looked at these links: (Angular JS: Full example of
GET/POST/DELETE/PUT client for a REST/CRUD backend?) (How to access the
services from RESTful API in my angularjs page), I feel very confident in
how the AngularJS code should look, but I don't know what the URL is doing
in these $resource examples.
I've never implemented a RESTful API in any language, and I'm having a lot
of trouble understanding what the code should be inside the tags.
Explanations on the web are often too technical for my skill level. I've
tried asking my professors, but I haven't found one who has implemented
REST before.
I appreciate any time and any help, Andrew

Random subsampling in R

Random subsampling in R

I am new in R, therefore my question might be really simple. I have a 40
sites with abundances of zooplankton. My data looks like this (columns are
species abundances and rows are sites)
0 0 0 0 0 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 85 0 0 0 0 0 0 45 5 57 0
0 0 0 0 0 13 0 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 7 0 0 3 0 0 12 8 0 57 0
0 0 0 0 0 0 0 1 0 0 0 0 0 0 59 0 0 0 0 0 0 0 4 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 105 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 100 0 0
35 0 55 0 0 0 0 0 1 4 0 0 0 0 0 0 0 0 0 0 0 0 34 21 0 0 0 0 0 0 0 9 17 0 0
0 54 0 0 0 27 5 0 0 0 1 0 0 0 1 0 0 0 0 17 0 0 0 54 3 0 0
What I d like to is take a random subsample from each site without
replacement (e.g. 50 individuals) several times (bootstrap) in order to
calculate diversity indexes to the new standardized abundances afterwards.
I tried several commands with no success.
Every bit of help will be widely appreciated
Cheers
Paris

Optimal LinqToSql GroupBy query, in 1:m relationship

Optimal LinqToSql GroupBy query, in 1:m relationship

I have two database tables (connected with relation 1:m):

Location (locId, locName)
1, USA
2, Germany
3, Spain
Sublocations (subLocId, subLocName, locId)
1, Denver, 1
2, Detroit, 1
3, New York, 1
4, Hamburg, 2
5, Berlin, 2
6, Munich, 2
7, Madrid, 3
8, Barcelona, 3
9, Valencia, 3
With using Linq to Sql, I need to fill the LocationDto, like this:
LocationDto (locId, subLocId, name)
1, null, USA
1, 1, Denver
1, 2, Detroit
1, 3, New York
2,null, Germany
2, 4, Hamburg
2, 5, Berlin
2, 6, Munich
3,null, Spain
3, 7, Madrid
3, 8, Barcelona
3, 9, Valencia

winapi analog of java's synchronized/wait()

winapi analog of java's synchronized/wait()

java's synchronized block is like windows critical section or mutex: only
one thread may enter it at a time.
But there's a difference: when you call wait() inside the synchronized
block, other threads gain the ability to enter the block. Not sure how to
do the same in winapi.

Wednesday, 21 August 2013

Javascript code for time, date, and changing greeting depending on time

Javascript code for time, date, and changing greeting depending on time

I'm sorry to bother y'all but I have been working on this assignment and
cannot get it to work. I am learning JavaScript and need all the help I
can get. Thank you in advance for any tips. I entered the following code
step-by-step as specified by the textbook "JavaScript" by Don Gosselin
(Chapter 6, Exercise 6-3, pp. 368-369.)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Welcome</title>
<body>
<h1>Welcome to My Web Page</h1>
<script type="text/javascript">
/* <![CDATA[ */
var dateObject = new Date();
var greeting = "";
var curTime = "";
var minuteValue = dateObject.getMinutes();
var hourValue = dateObject.getHours();
if (minuteValue <10){
minuteValue="0"+minuteValue;
}
if(hourValue<12) {
greeting="<p>Good Morning!</p>"
curTime=hourValue+":"+minuteValue + " AM";
}
else if(hourValue==12) {
greeting = "<p>Good Afternoon!</p>";
curTime=(hourValue + ":" +minuteValue+" PM");
}
else if(hourValue<17){
greeting="<p>Good afternoon!</p>";
curTime=(hourValue-12) + ":" + minuteValue+ " PM";
}
else {
greeting="<p>Good evening!</p>";
curTime+(hourValue-12) + ":" +minuteValue+" PM";
}
var dayArray=new
Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday");
var monthArray=new Array
("January","February","March","April","May","June","July","August","September","October","November","December");
var day=dateObject.getDay();
var month=dateObject.getMonth();
document.write("<p>"+greeting+ "It is"+curTime+"on" +
dayArray[day]+","+monthArray[month]+""
dateObject.getDate()+","+dateObject.getFullYear()+".</p>");
/* ]]> */
</script>
</body>
</html>

Load Image on specific coordinates on FORM

Load Image on specific coordinates on FORM

Here is my code:
Form1.Picture = LoadPicture("C:\Users\User\Desktop\1xxx-LOGO-brand-.jpg",
, , 913, 486)
I used this code to load a picture successfully. However, the X and Y
coordinates did not work. IT load at default coordinates(0,0).a
How should I set the location of a picture to be loaded inside a form?
Thanks

How to center drop down menu?

How to center drop down menu?

thank you for your time today to help me solve this CSS issue.
Test Page here
I'm got the navigation menu set up (top nav = main-nav) as I'd like it but
I can't for the life of me figure out a way to center align the drop down
(second level of navigation) to its parent navigation item, without
effecting the current layout or functionality.
The navigation list was tricky to set up with the menu in the middle and
to still be dynamic via Wordpress. I used a combination of display:table
and display:table-cell to do this. The top level of the navigation looks
great but the drop down secondary levels are off aligned.
Any advice would be greatly appreciated. Thanks in advance! Cheers,

How do I add man-page to man for a new tool I created?

How do I add man-page to man for a new tool I created?

I've created a new tool for Linux and I'd like to create the help page for
man. How can it be done?

Which data type for HTML?

Which data type for HTML?

I would like to store html in my database, what field type would you
recommend?
VarChar
Blob
Text
The html will vary in length depending on the row.
Thanks

Is it advisible to add new table in Joomla?

Is it advisible to add new table in Joomla?

I need to know if it is advisible to add new table in default database of
Joomla. Will it be preserved if I update my Joomla.
If yes, then can anybody describe the steps?

Tuesday, 20 August 2013

Specifying relative path to shockwave flash object

Specifying relative path to shockwave flash object

While playing the .SWF file in windows forms as below, I noticed that it
doesn't takes any relative paths.
What is done below is that each time the PlayVideo Form Dialog opens it
loads a new video which I was tracking using a global variable:
GlobalVariablesTracking.videoTrack and incremented it after successfully
loading a video.
private void PlayVideo_Load(object sender, EventArgs e)
{
CurrentVideoKey = GlobalVariablesTracking.videoTrack;
currentVideoName =
ConfigurationManager.AppSettings[CurrentVideoKey.ToString()];
if (!String.IsNullOrEmpty(currentVideoName))
{
GlobalVariablesTracking.videoTrack =
GlobalVariablesTracking.videoTrack + 1;
axShockwaveFlash1.Movie = "\\Videos\\" + currentVideoName;
axShockwaveFlash1.Play();
}
}
Below are the Keys I read from App.Config
<add key="1" value="a.swf"/>
<add key="2" value="b.swf"/>
.....
The issue I encountered in the line:
axShockwaveFlash1.Movie = "\\Videos\\" + currentVideoName;
It doesn't takes relative path. If a complete absolute path is specified
as below, it works perfectly.
axShockwaveFlash1.Movie = "C:\\Videos\\" + currentVideoName;
How to get this ShockWave flash object to work with a Relative URL ?

Best way to set Wordpress plugin max version for update?

Best way to set Wordpress plugin max version for update?

Is there a way to set a max update-able version of Wordpress plugins,
until they are fully tested in our environment? For example, this could
make sure no users update to NextGen 2.x which is broken in various ways,
until it is verified to not cause conflicts.
I tried the plugins_api filter, which works for searching plugins, but it
only changes the displayed version in "add new" plugins page.
Do you have to mirror the WP repository with older versions with some
complicated hacks, or is there a simple switch/hook to set the preferred
version?

How is data divided into packets?

How is data divided into packets?

Hi sorry if this is a stupid question (I just started learning network
programming), but I've been looking all over google about how files/data
are divided into packets. I've read everywhere that somehow files are
broken up into packets have headers/footers applied as they go through the
OSI model and are sent through the wire where the recipient basically does
the reverse and removes the headers.
My question is how exactly are files/data broken up into packets and how
are they reassembled at the other end?
How does whatever doing the reassembling know when the last packet of the
data has arrived and etc?
Is it possible to reassemble packets captured from another machine? And if
so how?
(Also if it means anything I'm mostly interested in how this work for TCP
type packets)
Any pointers towards resources is much appreciated, thank you!

printer hp laserjet p1102 on ubuntu 13.04

printer hp laserjet p1102 on ubuntu 13.04

I buy a printer I have a hp laser jet p1102 printer. How can i install it
on ubuntu 13.04. Please help me to install it with command or .deb Please
help me.

mysqli/PDO information: from mysqli to pdo-> how to handle error

mysqli/PDO information: from mysqli to pdo-> how to handle error

I have finished the main functions of my code, but I have got tons of
"useless" code that I'm trying to remove.
This is an example:
else if(isset($_POST['act']) && $_SESSION['status']<3 &&
$_POST['act']=='delete_ticket'){
$encid=preg_replace('/\s+/','',$_POST['enc']);
$encid=($encid!='' && strlen($encid)==87) ? $encid:exit();
$mysqli = new mysqli($Hostname, $Username, $Password, $DatabaseName);
$stmt = $mysqli->stmt_init();
if($stmt){
$query = "UPDATE ".$SupportTicketsTable." a
INNER JOIN ".$SupportUserTable." b
ON b.id=a.operator_id
SET b.assigned_tickets= CASE WHEN
b.assigned_tickets!='0' THEN (b.assigned_tickets-1)
ELSE b.assigned_tickets END
WHERE a.enc_id=?";
if($prepared = $stmt->prepare($query)){
if($stmt->bind_param('s', $encid)){
if($stmt->execute()){
$query = "DELETE FROM ".$SupportMessagesTable." WHERE
`ticket_id`=(SELECT `id` FROM ".$SupportTicketsTable."
WHERE `enc_id`=?) ";
if($prepared = $stmt->prepare($query)){
if($stmt->bind_param('s', $encid)){
if($stmt->execute()){
$query = "SELECT enc FROM
".$SupportUploadTable." WHERE
`ticket_id`=?";
if($prepared = $stmt->prepare($query)){
if($stmt->bind_param('s', $encid)){
if($stmt->execute()){
$stmt->store_result();
$result =
$stmt->bind_result($mustang);
if($stmt->num_rows>0){
$path='../upload/';
while
(mysqli_stmt_fetch($stmt))
{
if(file_exists($path.$mustang)){
file_put_contents($path.$mustang,'');
unlink($path.$mustang);
}
}
}
$query = "DELETE FROM
".$SupportUploadTable." WHERE
`ticket_id`=?";
if($prepared =
$stmt->prepare($query)){
if($stmt->bind_param('s',
$encid)){
if($stmt->execute()){
$query = "DELETE
FROM
".$SupportFlagTable."
WHERE `enc_id`=?";
if($prepared =
$stmt->prepare($query)){
if($stmt->bind_param('s',
$encid)){
if($stmt->execute()){
$query
=
"DELETE
FROM
".$SupportTicketsTable."
WHERE
`enc_id`=?";
if($prepared
=
$stmt->prepare($query)){
if($stmt->bind_param('s',
$encid)){
if($stmt->execute()){
echo
json_encode(array(0=>'Deleted'));
}
else
echo
json_encode(array(0=>mysqli_stmt_error($stmt)));
}
else
echo
json_encode(array(0=>mysqli_stmt_error($stmt)));
}
else
echo
json_encode(array(0=>mysqli_stmt_error($stmt)));
}
else
echo
json_encode(array(0=>mysqli_stmt_error($stmt)));
}
else
echo
json_encode(array(0=>mysqli_stmt_error($stmt)));
}
else
echo
json_encode(array(0=>mysqli_stmt_error($stmt)));
}
else
echo
json_encode(array(0=>mysqli_stmt_error($stmt)));
}
else
echo
json_encode(array(0=>mysqli_stmt_error($stmt)));
}
else
echo
json_encode(array(0=>mysqli_stmt_error($stmt)));
}
else
echo
json_encode(array(0=>mysqli_stmt_error($stmt)));
}
else
echo
json_encode(array(0=>mysqli_stmt_error($stmt)));
}
else
echo
json_encode(array(0=>mysqli_stmt_error($stmt)));
}
else
echo
json_encode(array(0=>mysqli_stmt_error($stmt)));
}
else
echo
json_encode(array(0=>mysqli_stmt_error($stmt)));
}
else
echo json_encode(array(0=>mysqli_stmt_error($stmt)));
}
else
echo json_encode(array(0=>mysqli_stmt_error($stmt)));
}
else
echo json_encode(array(0=>mysqli_stmt_error($stmt)));
}
else
echo json_encode(array(0=>mysqli_stmt_error($stmt)));
}
else
echo json_encode(array(0=>mysqli_stmt_error($stmt)));
exit();
}
As you can see there are too many if statement for the mysqli connection:
this is the part I want to remove, is there a way remove them? I have
tried to wrap it between try and catch but the code returns anyway the
success echo (it's an AJAX call).
I have read that mysqli have got some problems with try and catch function
so I have took a look at PDO, but I'm not an expert and I don't understan
if I can get the same result of the code that I have posted with it, I
have also read that I have to change the error mode to
PDO::ERRMODE_EXCEPTION, but I haven't understood very well the point.
Basically: is there someone who can explain me how PDO handle the errors?

Can I get an event if i click outside some div?

Can I get an event if i click outside some div?

I have a drop down list I did not use the HTML select element, I build it
with UL. It is working fine now but I have one problem if I click the drop
down it will slide down and when I select an element it will slide up.
What I want to slide the list up if I click out the div of the list
(without choosing any element). I wonder if I can do it using some JQuery
but I do not know how to link this situation with JQuery event listener ??
can anybody help me please? This is my js file:
$('.final_dates_list li').live('click',function(){
id = $(this).attr("id");
if(id == 'current')
{
$("#dates_list").find("li").each(function(){
//alert($(this).attr("id"));
$(this).show();
$(this).slideDown('slow');
});
}
else
{
this_id = $(this).attr("id");
$("#dates_list").find("li").each(function(){
//alert($(this).attr("id"));
$(this).hide();
$(this).slideUp('slow');
});
$("#dates_list").find("#current").show();
}
});
css:
div.final_dates_container ul.final_dates_list
{
float:right;
margin:0px;
padding:0px;
width:100px;
line-height: 21px;
overflow: hidden;
border: 1px solid #27292c;
border-radius: 4px;
background: url('bg.png') no-repeat right #494849;
box-shadow:inset 0 0 1px #393939;
-moz-box-shadow:inset 0 0 1px #393939;
-webkit-box-shadow:inset 0 01px #393939;
list-style-type:none;
color:#fff;
font-size:0.8em;
text-align:center;
font-weight:bold;
position:relative;
z-index:9999;
}
div.final_dates_container ul.final_dates_list li:hover
{
text-decoration:underline;
cursor:pointer;
}
div.final_dates_container ul.final_dates_list li
{
border-top:1px solid #eee;
}
html:
<div class="final_dates_container">
<table border="1">
<tr>
<td>
<ul id="dates_list" class="final_dates_list">
<li id='current'>0</li>
<li id='-6' style='display:none'>-6</li>
<li id='-5' style='display:none'>-5</li>
<li id='-4' style='display:none'>-4</li>
<li id='-3' style='display:none'>-3</li>
<li id='-2' style='display:none'>-2</li>
<li id='-1' style='display:none'>-1</li>
<li id='0' style='display:none'>0</li>
<li id='1' style='display:none'>1</li>
<li id='2' style='display:none'>2</li>
<li id='3' style='display:none'>3</li>
<li id='4' style='display:none'>4</li>
<li id='5' style='display:none'>5</li>
<li id='6' style='display:none'>6</li>
</ul>
</td>
</tr>
</table>
</div>

Why do I need to use these nasty comments in C# / .Net code?

Why do I need to use these nasty comments in C# / .Net code?

I'm building application and one of requirements is to use a comments like
this one:
/// <summary>
/// Creates new client.
/// </summary>
/// <param name="uri">The URI.</param>
/// <param name="param">The param.</param>
/// <returns></returns>
I understand that it's easy for various kind of tools to generate the docs
based on these xmls. But it significantly decreases code readability, and
that's exactly what we, humans, trying to achieve.
Could this approach be replaced by any other technique in .Net? And what's
the better way to improve code readability and cleanness?

Monday, 19 August 2013

C99999 format in java to be used in sql

C99999 format in java to be used in sql

i have a number with format "C99999"
i need import it to sql
i try this
while (rs.next()){
int s=rs.getInt("Number");
s++;
String n = String.format("%05d",s);
view.txtcustomernumber.setText(n);
how to add "C" into this format and the data type in mysql is int

PHP Session Variables In Common Code Sheets and Functions

PHP Session Variables In Common Code Sheets and Functions

In my quest to conquer Php sessions, I'm faced with my (lack of)
understanding with Php sessions, and setting \ accessing session
variables.
I wish to place common session variable setting and accessing within a
common php sheet, and execute a function that would set, or reset a
session and its' variables. For example;
common.php (Code sheet)
class SessionSetEnum {const NOT_SET = 0; const CREATED = 1; const
RECREATED = 2;}
function SessionSet($timeOut = 900) {
$ss = SessionSetEnum::NOT_SET;
if(!isset($_SESSION['CREATED'])) {
$_SESSION['CREATED'] = time();
$ss = SessionSetEnum::CREATED;
}
elseif((time() - $_SESSION['CREATED']) > $timeOut) {
session_destroy();
session_unset();
session_regenerate_id(true);
$_SESSION['CREATED'] = time();
$ss = SessionSetEnum::RECREATED;
}
return($ss);
}
For all other sheets on the website, I'll have the following;
index.php (Code sheet)
session_start();
include('common.php');
if (SessionSet() === SessionSetEnum::RECREATED)
{
unset($country_cd);
$country_cd = getCountryCode();
}
another-page.php (Code sheet)
session_start();
include('common.php');
if (SessionSet() === SessionSetEnum::RECREATED)
{
unset($country_cd);
$country_cd = getCountryCode();
}
All examples I've searched, always place session variable setting and
access, directly beneath session_start(), on every code page. I would like
to know if there is anything about php session variables such that, they
should not be coded in a common code sheet?
Please note that I saw on another website or two, the sure way of
destroying a session in php is they way I've expressed it. It does look
like an overkill. Also, the example is not real life, just an example
demonstrating php usage.
Very much appreciate your time and consideration.
Thanks and regards, BotRot

Reading multiple user input strings inside a loop

Reading multiple user input strings inside a loop


I am currently trying to solve a problem from CodeChef but I am having
troubles with using fgets() inside a loop.

The first input (T) is going to be a positive integer containing the
number of user inputs.
Then delimited by newline characters, the user is going to input a string
below the length of 10 under any circumstances.

So, I've tried this:

#include <stdio.h>
#include <stdlib.h>
#define SIZE 10
int main()
{
int T;
int diffX, diffY;
char s[SIZE];
scanf("%d", &T);
while (T--){
fgets(s, SIZE, stdin);
printf("%s\n", s);
}
return 0;
}
However, when I attempted to test the code with the following inputs:
3
Hello
Hi
What

I was only able to input until "Hi" then the program exited successfully
(returning 0).

Why is this the case and how can I fix it?
Thank you in advance,
kpark.

$.get callback function doesn't work

$.get callback function doesn't work

Im trying to execute a jquery.get() request but callback and error
function are not working. This is my code:
$.get(serviceURL, {idioma:idioma}, function(links) {
links.forEach(function(link) {
link.source = nodes[link.source] || (nodes[link.source] = {name:
link.source});
link.target = nodes[link.target] || (nodes[link.target] = {name:
link.target});
});
d3.values(nodes).forEach(function(node) {
var serviceURL = "url //http://localhost:8080/..." +
node.name;
$.get(serviceURL, function(data) {
$.each(data, function(index, datos){
console.log(datos);
});
});
$(document).ajaxError(function(event, request, settings) {
console.log("event: " + event + " request:" + request);
alert("Error accessing the server");
});
});
});
There are two $.get() methods, and second is nested in first. First
$.get() is working, but second is the one is not working. Debugging with
Firebug, I see that running 2nd $.get() HTTP GET request is OK (HTTP code
200 and I see JSON object in console), but instead of execute
function(data), then it goes to the line
$(document).ajaxError(function(event, request, settings) but neither
executes error function (not showing alert or console output).
The problem is that I'm not able to see which is $.get real response, I'm
testing 2nd $.get function, outside forEach(node) and $.get links
function, passing node parameters directly to serviceURL and it works.
Could you help me, please? regards

Backbone.js - how to make sub models from Json data using collection parse

Backbone.js - how to make sub models from Json data using collection parse

When i fetching the data from server, i am getting raw json for my
navigation. my navigation has the main link and sublinks (drop down ) - in
this case how can i make a main model and nest the sub model within
that..? or how can i make 2 different models for main and sub - links and
connect each other..
Here is the json i am getting from server:
[
{
"label": "General",
"link": "#/general",
"subLinks": [
{
"label": "Dashboard",
"link": "#/dashboard"
},
{
"label": "My Task",
"link": "#/mytask"
},
{
"label": "My Documents",
"link": "#/mydocuments"
},
{
"label": "My Templates",
"link": "#/mytemplates"
},
{
"label": "Search",
"link": "#/search"
}
]
},
{
"label": "Repositories",
"link": "#/reposotories",
"subLinks": []
},
{
"label": "SavedSearches",
"link": "#/savedSearches",
"subLinks": []
},
{
"label": "Favourites",
"link": "#/favourites",
"subLinks": []
},
{
"label": "Reports",
"link": "#/reports",
"subLinks": []
},
{
"label": "Preferences",
"link": "#/preferences",
"subLinks": []
}
]
after i receive my json i use the parse method to manipulate the models:
define(["backbone","models/model","collection/baseCollection"], function
(Backbone,model,baseCollection) {
var mainLinkModel = model.extend({
defaults:{
label:"mainLink",
link:"#",
subLinks:{ // is this correct way to make..?
label:"mainLink",
link:"#",
}
}
})
var headerCollection = baseCollection.extend({
url:function(){
return this.path + "edms/navigationLinksTest"
},
model:model,
initialize:function(){
},
parse:function(response){
var mainNavi = [];
_.each(response.navList, function(m){
// i am making new models.. but how to handle
the sublinks?
mainNavi.push(new mainLinkModel(m));
})
}
});
return new headerCollection;
})
But what i doing the way is not giving the proper result. how to handle
this kind of models.. any one help me in this please..?