Thursday, 3 October 2013

How to setup MSMQ server so that it can be accessed over the Internet

How to setup MSMQ server so that it can be accessed over the Internet

We have MSMQ on a Windows 2008 R2 server, with the followings Firewall
settings: 1) Message Queuing is checked in 'Allow programs to communicate
through Windows Firewall' 2) Enable TCP port: 2103, 2105, 1801
But when a c# application (using
FormatName:DIRECT=TCP:xxx.xxx.xxx.xxx\Private$\q1) attempts to receive the
private queue message, it encountered the following error:
System.Messaging.MessageQueueException: Remote computer is not available.
at System.Messaging.MessageQueue.MQCacheableInfo.get_ReadHandle()
Is something amiss from the above setup? Please help.........
Thanks, Ben

Wednesday, 2 October 2013

IOS guided access - can app know it is in guided access mode?

IOS guided access - can app know it is in guided access mode?

I am developing an IOS app for a class room environment - conducting a
test. I have a requirement that the app should not come out during the
test. Guided access is a perfect solution for me, since I can force users
(students) to turn the device to guided access mode.
What I want is like this: Only after the device is set into guided access
mode, the app will proceed from a particular screen. Is it possible for
the app to know (programmatically) whether the device is in guided access
mode at any point in time? Any documentation available on this?
Thanks in advance for your help

xcb: how to launch an and show it into a window

xcb: how to launch an and show it into a window

I'm trying to implement a basic window manager using xcb library.
I managed to connect with X server, and grab some events, but i cannot
figure how to launch an application and show it inside the current X
session.
I'm trying to follow the xcb tutorial: http://xcb.freedesktop.org/tutorial/
Basically i thought (and probaly i'm wrong) that once the session is
started, with my "windowmanager", if i want to launch an application i
just have to fork it, and launch the application, so for example:
int child = fork();
if(child==0) {
printf("Child");
execve("/usr/bin/xterm", NULL, NULL);
}
But it seems that didn't work.
I have no much code to show, since i'm trying just to modify che code in
the tutorial pasted above (i added an infinite loop, and few other thing).
So how to launch an x application like xterm, pcmanfm and show it on the
current x session?

Implement Shapes in android

Implement Shapes in android

I need to implement paint functionalities in android.Shapes,Tools,Color
etc.How i do in android.Plz help me. Thanks in advance.

Tuesday, 1 October 2013

Simple multiple choice Java code

Simple multiple choice Java code

I'm looking for an example of Java code for multiple choice questions
that's as simple as possible. I have the Eclipse IDE but most codes I find
online don't work because they don't have the System.out.println function.

Matching specific Apache VirtualHost with regex

Matching specific Apache VirtualHost with regex

I am currently attempting to match a single Apache VirtualHost entry
within an apache config file by the ServerName of the VirtualHost. I am
doing this with python, using the re module.
Here's an example of the type of file that I am working with:
<VirtualHost *:8000>
DocumentRoot "/path/to/dir1"
ServerName eg1.dev
</VirtualHost>
<VirtualHost *:80>
DocumentRoot "/path/to/docroot"
ServerName desired.dev
</VirtualHost>
<VirtualHost *:8080>
DocumentRoot "/path/to/dir3"
ServerName eg2.dev
</VirtualHost>


I want to match the VirtualHost with a ServerName of desired.dev. So the
match I am aiming for is:
<VirtualHost *:80>
DocumentRoot "/path/to/docroot"
ServerName desired.dev
</VirtualHost>


I assumed this would be fairly simple with a regex but I can't figure out
how to do it. I currently have:
<VirtualHost \*:[0-9]*>.*?ServerName +desired.dev.*?</VirtualHost>
But the issue with this being that it matches the very first
<VirtualHost..., matches the ServerName and stops matching at the end of
the closing tag of the desired VirtualHost.
I'm aware that there are probably python modules for parsing Apache config
files but I do not wish to use anything from outside of the standard
library. If attempting this with regex is a terrible idea, are there any
alternatives?

Hint to prove that $\phi^n + \phi'^n$ is an integer. – math.stackexchange.com

Hint to prove that $\phi^n + \phi'^n$ is an integer. – math.stackexchange.com

I was solving some induction exercises but I found this that I could not
solve. Let $n \in \mathbb{N}$, prove that $\phi^n + \phi'^n$ is an integer
where $\phi=\frac{1+\sqrt{5}}{2}$ and ...

How can I calculate sum of multichoose multiplied by its argument?

How can I calculate sum of multichoose multiplied by its argument?

I need to calculate sum like this:
$\sum\limits_{k=1}^n k\textstyle\left(\!\!{n\choose k}\!\!\right)$
WolframAlpha is giving nice answer: $n{2n \choose n+1}$ But I don't know
how to prove this result.
Analogous expression for simple binomial coefficients:
$\sum\limits_{k=1}^n k{n\choose k} = n \cdot 2^{n-1}$
can be easily proved by taking derivative of $(1+x)^n$ and setting $x$ to
$1$ after that. But for multichoose I'm dealing with infinite series
$(1-x)^{-n} = \sum\limits_{k=0}^\infty {n-1+k\choose k} x^k$
and solution with setting $x$ to something won't work, I believe.

Monday, 30 September 2013

Jordan type representation for sequences with bounded variation

Jordan type representation for sequences with bounded variation

We say that a sequence $(x_n)$ of real numbers is of bounded variation iff
$ \sum_{n=1}^\infty |x_{n}-x_{n-1}|<\infty$ (where $x_0:=0$).
Let $(x_n)$ be convergent to zero.
Do there exist monotonic convergent to zero sequences $(a_n)$, $(b_n)$
such that $x_n=a_n-b_n$ ?
Thanks

How can I find out the very first time linux machine start up=?iso-8859-1?Q?=3F_=96_serverfault.com?=

How can I find out the very first time linux machine start up? –
serverfault.com

When we use uptime, it only shown us the up-time of ours machine since it
started from the last time it turning on/shutdown/reboot. But, what if I
want to get the time when our machine started from …

CSS Text overflow not working because word-break

CSS Text overflow not working because word-break

If a write this sentence in a width 90px and height 20px with text
overflow property:
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
will display:
aaaaaaaaaaaaaa...
the text-overflow property will work, but if the sentence is:
T H I S I S A S E N T E N C E
it will display:
T H I S I S A
S E N T E N C
E
the line will break and the text-overflow property won't work.
How can I get this to work correctly?

android facebook logout issues

android facebook logout issues

I have implemeted code for facebook connection to post message on wall ,
refere from this link https://github.com/facebook/facebook-android-sdk ...
every thing is working fine...
Now my issues is when I do logout() it is showing me logout successfully ...
private void clearCredentials() {
try {
facebookConnector.getFacebook().logout(getApplicationContext());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
but when next time open an app ... it is not logged out.... Thanks in
advance...

Sunday, 29 September 2013

Is Python list.extend() Order Presserving?

Is Python list.extend() Order Presserving?

I'm wondering whether the extend function preserves the order in the two
list.
>> list = [1, 2, 3]
>> list.extend([4, 5])
>> list
[1, 2, 3, 4, 5]
Is extend always working like that way?

Carousel effect for Joomla 3.1.5

Carousel effect for Joomla 3.1.5

Sorry for my ignorance but I am new in Joomla and I would need to add a
similar effect to this example
http://www.2joomla.net/joomla-extensions/2j-carousel/2j-carousel-demo-case2
For it, Could anybody help me with that?

Installation problems with Debian and ubuntu

Installation problems with Debian and ubuntu

I'm trying to install Debian 7.1 on my PC, but keep getting the following
error "This program doesn't support windows 6.2.9200 SP0 yet". I've tried
version 7.0 too, but got the same error.
My attempts to install ubuntu have been similarly unsuccessful. I
downloaded ubuntu 13.04 and when I attempt to install it, while it says it
is downloading I have been getting "An error ocurred: Permission denied.
For more information, please see the log file
c:\users...\appdata\local\temp\wubi-13.04-rev279.log" but when I look for
this file, it doesn't seem to exist.
My PC came with Windows 8 preinstalled. I'm not sure if there's any other
information I should provide, but if there is please let me know. I've
been stumbling around clumsily for the past two days, and really don't
have any idea how I should proceed.

I am facing database error in cpanel, what i can do?

I am facing database error in cpanel, what i can do?

My CodeIgniter database setting is:
$db['default']['hostname'] = 'localhost';
$db['default']['username'] = 'empyreal_username';
$db['default']['password'] = 'password';
$db['default']['database'] = 'empyreal_dbname';
$db['default']['dbdriver'] = 'mysql';
$db['default']['dbprefix'] = '';
$db['default']['pconnect'] = TRUE;
$db['default']['db_debug'] = TRUE;
$db['default']['cache_on'] = FALSE;
$db['default']['cachedir'] = '';
$db['default']['char_set'] = 'utf8';
$db['default']['dbcollat'] = 'utf8_general_ci';
$db['default']['swap_pre'] = '';
$db['default']['autoinit'] = TRUE;
$db['default']['stricton'] = FALSE;
but it shows the following error:
A Database Error Occurred
Unable to connect to your database server using the provided settings.
Filename: core/Loader.php
Line Number: 346
What can i do? please suggest me

Saturday, 28 September 2013

How to display the current live wallpaper inside an application?

How to display the current live wallpaper inside an application?

How do you display the user's live wallpaper inside your application?
Since live wallpapers are more than just videos, I am unsure as to where
to start on this one, but I do know that it is possible.

Project on How To Design a Web Browser?

Project on How To Design a Web Browser?

I Was Interested in working on making a sample web browser
i know c++,html and java script
can any one tell me how to procedd on building it..
thank you..

What's wrong with my if-else statement? (Java)

What's wrong with my if-else statement? (Java)

I made this simple GUI program that counts the vowels and consonants of a
particular sequence of characters. The counter is okay, but I'm having a
problem with the if-else statement where I had to display a message when
that character is neither a vowel nor consonant... Here's the code:
//I initialized these variables:
public static int vowels = 0, consonants = 0, charac = 0;
public static String outputStr;
public static String conso = "bcdfghjklmnpqrstvwxyz";
public static String vow = "aeiou";
//Here's the code for my "count" button
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String userInput = jTextField1.getText();
userInput = userInput.toUpperCase();
conso = conso.toUpperCase();
vow = vow.toUpperCase();
String wordInput[] = userInput.split("");
vowels = 0;
consonants = 0;
charac = 0;
for(int i=0; i<wordInput.length; i++) {
for(int j=0; j<5; j++) {
char v = vow.charAt(j);
String VL = Character.toString(v);
if(VL.equals(wordInput[i])) {
vowels ++;
charac = 0;}
else {
charac += 1; }
}
for(int h=0; h<21; h++) {
char c = conso.charAt(h);
String CL = Character.toString(c);
if(CL.equals(wordInput[i])) {
consonants ++;
charac = 0; }
else {
charac += 1; }
}
}
String totalVow = Integer.toString(vowels);
String totalCons = Integer.toString(consonants);
jLabel5.setText(totalVow);
jLabel6.setText(totalCons);
//here's the if-else statement:
if (charac == 0) {
jLabel7.setText(" ");
}
else if (charac >= 1) {
jLabel7.setText("The sequence contains invalid characters.");
}
if (userInput.isEmpty()) {
jLabel7.setText("No input.");
}
}
Here's what it looks like:

I entered a "sequence" of characters that does not have any special
characters or digits. But it still displays the message wherein it has
other characters other than the vowels and consonants. Is there something
wrong with the if-else statement? Thanks for the help :)

Convert Integer value to ip address in C

Convert Integer value to ip address in C

How to convert Integer value to IPaddress? i am having int value=570534080
and want to convert as 192.168.1.34

Friday, 27 September 2013

Too many data on database - "replication" decision needed

Too many data on database - "replication" decision needed

Now I have a problem with a MySQL application. Actually I'm worried about
a problem I might have in a few months.
Here's the scenario: I'm developing a web application that will have a lot
of clients using it. It's a application that has a unique core and several
adaptations (running on the same core), so the database is the same for
all adaptations. Each adaptation has one or more clients using it.
So, my database has more than 200 tables and some tables may have more
than 500 rows per day per client. I'm worried that when the database get
too big the selects may be really expensive.
I was thinking about create several databases (identical schema) and the
application should decide what database to use based on what client is
logged. But I'll have really problems to update the schemas (I'll have to
update each database). My application can choose the database, it's not a
problem.
Do you think that the MySQL can really stop if it has a lot of data?
Is there a way to easily update several identical-schema-databases?
Master/slave approach solves my problem?
I think it's important you to know that in all tables I have a collumn
that tells me to what client that row belongs to and always use it in all
the select queries as a WHERE clause.
So what I need help is to decide what to do. Can you help me with these
questions? Do you have any other smarter solution?
I don't know if it's important but I'm using PHP.
Thank you all!

SSRS 2005 Return the parameters that do not return a matching record

SSRS 2005 Return the parameters that do not return a matching record

I am using SSRS 2005. I have a report that has a single parameter
"@Serial". Our support technicians enter computer serial numbers into the
parameter field and generate a report returning the matching records from
the database table. The count of serial numbers is not hard set and ranges
from 1 to 100++.
My ultimate goal is to list the serial numbers that do not return a
matching record.
In SSRS I have tried using the =JOIN(Parameters!Serial.Value,",") to list
all of the parameter values (serial numbers) into a text field. This works
fine to list ALL of the parameters passed but I do not know the correct
expression to convert the list so it only contains only the un-matched
serial numbers.
It was suggested that I use a Left Join in the SQL query, however, I don't
know how to get the parameters entered by the technician into a temp table
in SQL so that I can Join the two tables.
Any help on either method is appreciated, and alternatives to these two
methods are welcome.

Trac issue/bug tracking software - is there a way to use git AND svn on the same trac installation

Trac issue/bug tracking software - is there a way to use git AND svn on
the same trac installation

I've successfully installed Trac bug tracking software which has the
ability to use SVN and GIT - however I am having problems setting up both
types of repositories for the same trac installation. The config seems to
imply that there should be only one 'type' of repository for a trac
install but this seems to fly in the face of the interface which implies
that more than one type of repo can be added to the interface.
Anyone have this same issue? I have been to google already and cannot find
the search terms needed to address this specific issue.
Any help is appreciated. Thank you!

Editing block elements in classes and nested classes

Editing block elements in classes and nested classes

I am trying to edit my drop-box using cascading style sheets. Normally its
possible but in my code. i am using a Jquery click based slide-down
window. In this i am unable to select the element. How to i add style to
my drop-down box? I am posting the code .
<div class="dropdownwrap">
<class="select" select name="district">
<option>Select District</option>
<option>abcd</option>
<option>acbd</option>

monogame c# - loading sound file

monogame c# - loading sound file

I'm trying to load sound into my game. I downloaded an .mp3 sound (a
second long) and tried to load it both as Song and as SoundEffect, but it
didn't work, so I tried loading the same sound but as .wav and I was able
to load it as a SoundEffect. The problem is that the sound that is coming
out sounds like static noise. I looked a bit into this and found out I
need to load sounds as .xnb files, so I downloaded 'XNAContentCompiler'
project and tried to compile the sounds causing a 'PInvokeStackImbalance'
error.
So I found this thread:
http://xboxforums.create.msdn.com/forums/p/65519/65519.aspx
Saying I can ignore this and continue.
The xnb file fails to be created when I try to convert the .wav files,
saying it is 24-bit audio and I may only use 8 to 16 bit. So I tried to
compile the .mp3 file and it succeed, creating a 1k file that I still
cannot load not as a Song and not as SoundEffect.
I'm now completely lost on this and can no longer understand what I need
to try to load and what is a different problem completely, and I would
love some explanations... Thank you.

Got linking error after 'Enable Modules' in iOS 7

Got linking error after 'Enable Modules' in iOS 7

The error happened when I was transferring my app from iOS6 to iOS7 when
applying one of the new objective-c features--- Modules. Here is the
situation: 1. I turned "Enable Modules(C and Objective-C)" to YES in the
project settings. 2. Since Auto Linking is enabled for system frameworks,
I deleted the reference of all the system frameworks under "Build Phases
---> Link Binary With Libraries"(Note that I also delete the reference
under the Project Navigator--->Frameworks directory). 3. Then I built my
app and got the linking errors. 4. Finally after several try, I figured
out that I still need to import MobileCoreServices.framework and
SystemConfiguration.framework(both of them are system frameworks, I think)
because I am using AFNetworking library in my project. Anyone has idea why
I have to refer them though others don't need to be(such as UIKit or
Foundation, both of them are also used in AFNetworking library...)? Thanks
in advance.

Thursday, 26 September 2013

C - index applied to pointer to pointer

C - index applied to pointer to pointer

I want to ask what does C do when it sees a index on a pointer to pointer;
for example:
struct X {
int a;
int b;
};
struct X ** ptr;
What will happen if a statement contains :
ptr[i] // where i is an unsigned int
Thanks.

Wednesday, 25 September 2013

JoinMulticastGroup thrown invalid argument exception in vb.net

JoinMulticastGroup thrown invalid argument exception in vb.net

I am using following code to which sends udp multicast packets,
Private Const _POLL_COMMAND As String = "PJMReader"
Private Const _PORT As Integer = 8023
Private Const _MULTICAST_ADDRESS As String = "224.0.0.1"
Shared GroupIP As IPAddress
Shared GroupEP As IPEndPoint
Shared ListenUdp As UdpClient
Public Shared Sub Main()
Dim GroupEP As IPEndPoint
Dim SendUdp As New UdpClient()
Dim GroupIP As IPAddress
GroupIP = IPAddress.Parse(_MULTICAST_ADDRESS)
GroupEP = New IPEndPoint(GroupIP, _PORT)
SendUdp.JoinMulticastGroup(GroupIP, 12)
Dim bteSendDate() As Byte
Try
bteSendDate = Encoding.UTF8.GetBytes(_POLL_COMMAND)
SendUdp.Send(bteSendDate, bteSendDate.Length, GroupEP)
Dim tBytes() As Byte = SendUdp.Receive(GroupEP)
MessageBox.Show(Encoding.UTF8.GetString(tBytes))
' System.Console.WriteLine(Encoding.UTF8.GetString(tBytes))
' System.Console.ReadLine()
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
End Sub
But the Strange thing is that this code is working perfectly on windows
7,2008 server, i am facing this error only on Windows XP Machines
Thanks in Advance

Thursday, 19 September 2013

Variable inside class (whose value is derived from another class) isn't available to methods

Variable inside class (whose value is derived from another class) isn't
available to methods

I'm new to OOP so there's probably something fundamental I'm missing here.
In the Foo class, the $this->user_group variable is not available to the
bar() method. Why is that? And is there a less messy way to get these
classes to all talk to each other than including the $DB (and others)
every instantiation (this gets hairier with my actual code, which has many
more classes). Here's an example:
class Foo {
private $Auth, $user_group;
function __construct($DB) {
$this->Auth = new Auth($DB);
$this->user_group = $this->Auth->get_user_permissions_group();
// ("echo $this->user_group;" here will output the correct value)
}
public function bar() {
// ("echo $this->user_group;" here will output nothing)
return ($this->user_group > 1 ? 'cool!' : 'not cool!');
}
}
class Auth {
private $DB;
function __construct($DB) {
$this->DB = $DB;
}
public function get_user_permissions_group() {
$result = $this->DB->query('return user permissions level from DB');
return $result; // int, 1-3
}
}
$DB = new Database();
$Foo = new Foo($DB);
echo $Foo->bar();

Removing an element from group but keeping "odd/even" state accurate

Removing an element from group but keeping "odd/even" state accurate

What are I am trying to achieve is fairly easy (I think) but unfortunately
I can't get a hold of the solution.
Consider the following HTML syntax:
<div id="wrapper">
<div class="box">
<a href="#" class="close">close</a>
</div>
<div class="box">
<a href="#" class="close">close</a>
</div>
<div class="box">
<a href="#" class="close">close</a>
</div>
<div class="box">
<a href="#" class="close">close</a>
</div>
<div class="box">
<a href="#" class="close">close</a>
</div>
</div>
Basically all boxes are floating left and that makes room for 2 per line.
The first box has a margin-right of 25px so that the 2nd box is pushed to
the edge of its container.
When I click the ".close" link I want the element to "hide();" and if the
element I clicked is ":even" then the one that will come into place (the
odd one) is to become "even" so the margin is applied and vice versa.
Basically it's a dynamic ":nth-child(2n)"... Every 2nd element has to have
no margin, and then first one has to have a margin-right of 25px, even if
I remove one element from that group.
Hope that makes sense! Thank you very much

Cannot append list to a list?

Cannot append list to a list?

I can't find this question elsewhere on StackOverflow, or maybe my
researching skills are not advanced enough, so I am asking now:
So I was playing around with Python today after not having touched it in a
while and I found that the following snippet of code does not work:
>>> list1 = [1,2,3]
>>> list2 = [4,5,6]
>>> list3 = list1.append(list2)
>>> list3
Why does the last line not produce any results?
Also, I'm using Python 2.7.3, if that makes any difference

c# return value of dictionary from stored procedure

c# return value of dictionary from stored procedure

I have a function that grabs the output from a stored procedure. However,
I bit of JSON and all it's outputs being displayed are 'true'. I'm not
sure if I'm returning or placing the values correctly into my dictionary.
Here is my function
public static Dictionary<string,int> GetGhCsStatus()
{
using (Entities db = new Entities())
{
System.Data.Objects.ObjectParameter CsOut = new
System.Data.Objects.ObjectParameter("CsStatus", typeof(int));
System.Data.Objects.ObjectParameter GhOut = new
System.Data.Objects.ObjectParameter("GhStatus", typeof(int));
System.Data.Objects.ObjectParameter CsRunValue = new
System.Data.Objects.ObjectParameter("CSRunningValue",
typeof(int));
System.Data.Objects.ObjectParameter GhRunValue = new
System.Data.Objects.ObjectParameter("GHRunningValue",
typeof(int));
int r = db.proc_GhCsStatus(CsOut, GhOut, CsRunValue, GhRunValue);
Dictionary<string, int> Status = new Dictionary<string, int>();
Status.Add("CsStatus", (int)CsOut.Value);
Status.Add("GhStatus", (int)GhOut.Value);
Status.Add("CheckIfCsIsRunning", (int)CsRunValue.Value);
Status.Add("CheckIfGhIsRunning", (int)GhRunValue.Value);
return Status;
}
}
my stored procedure:
USE [DATABASE]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[proc_GhCsStatus]
-- Add the parameters for the stored procedure here
-- @TimeLimit Int, Do not need this paramter as it is grabbed from
Messenger_Settings table
@CsStatus Int OUTPUT,
@GhStatus Int OUTPUT,
@CSRunningValue Int OUTPUT,
@GHRunningValue Int OUTPUT
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Declare variables.
DECLARE @CsLastUpdate Int;
DECLARE @GhLastUpdate Int;
DECLARE @CsTimeout Int; -- Used to set Timeout
DECLARE @GhTimeout Int; -- Used to set Timeout
DECLARE @CheckGHRunningValue varchar(10);
DECLARE @CheckCSRunningValue varchar(10);
-- Calculate the LastUpdate.
SELECT @CsLastUpdate = DATEDIFF(second, Timestamp, CURRENT_TIMESTAMP)
FROM Heartbeat
WHERE Id=1
-- Calculate the LastUpdate.
SELECT @GhLastUpdate = DATEDIFF(second, Timestamp, CURRENT_TIMESTAMP)
FROM Heartbeat
WHERE Id=2
-- Grab CSTimeout from Messenger_Settings table
SELECT @CsTimeout = SettingValue
FROM Messenger_Settings
WHERE SettingName = 'CSTimeout'
-- Grab GHTimeout from Messenger_Settings table
SELECT @GhTimeout = SettingValue
FROM Messenger_Settings
WHERE SettingName = 'GHTimeout'
-- Get CS flag.
SELECT @CheckCSRunningValue = SettingValue
FROM Messenger_Settings
WHERE SettingName = 'CheckIfCSIsRunning'
-- Get GH flag.
SELECT @CheckGHRunningValue = SettingValue
FROM Messenger_Settings
WHERE SettingName = 'CheckIfGHIsRunning'
-- Compare it to the TimeLimit.
IF @CsLastUpdate > @CsTimeout SELECT @CsStatus = 0;
ELSE SELECT @CsStatus = 1;
-- Compare it to the TimeLimit.
IF @GhLastUpdate > @GhTimeout SELECT @GhStatus = 0;
ELSE SELECT @GhStatus = 1;
-- Convert true and false to 1 and 0
IF @CheckCSRunningValue = 'false' AND @CheckGHRunningValue = 'false'
SELECT @GHRunningValue = 0, @CSRunningValue = 0
ELSE IF @CheckCSRunningValue = 'false' AND @CheckGHRunningValue =
'true'
SELECT @GHRunningValue = 0, @CSRunningValue = 1
ELSE IF @CheckCSRunningValue = 'true' AND @CheckGHRunningValue =
'false'
SELECT @GHRunningValue = 1, @CSRunningValue = 0
ELSE IF @CheckCSRunningValue = 'true' AND @CheckGHRunningValue =
'true'
SELECT @GHRunningValue = 1, @CSRunningValue = 1
END
GO

Syncing Core Data with iCloud

Syncing Core Data with iCloud

How do I sync the contents of my sql file (created with core data) to
iCloud so that multiple devices can access the content?
Are there any good tutorials? Thank you.

How to know the minimum jQuery requirement for a script?

How to know the minimum jQuery requirement for a script?

I was curious how I would find out what the minimum jQuery requirement for
a plugin would be.
I'm developping a jQuery plugin for customers, and today I had the
question what jQuery requirements it has. This customer is still running
on jQuery 1.4.4, which is pretty damn old (and adviced him to update).
Still I would like to know how I can find out what the minimum jQuery
version would be to run my plugin.
Are there any methods or tools for this, or do I have to find out myself
some way?

Is it good practice to rely on domain constraints for validation

Is it good practice to rely on domain constraints for validation

Is it good practice to validate user input using the domain constraints
such as email(unique:true) then rely on a message.properties input such as
className.email.unique=Email address already in use to create an error
message. Or is it better practice to have some client side validation or
some check being carried in a web service before trying to persist to the
domain?

Wednesday, 18 September 2013

How can I add two list fragments one below the other?

How can I add two list fragments one below the other?

I want to add two listfragments (listfragment1 and listfragment2) whose
list are populated dynamically from webservice call. The listfragment2 is
suppose to be just below the listfragment1 such that if more content is
fetched in listfragment1 then listfragment2 should move/slide down.

MS Access - Details form returns same first record

MS Access - Details form returns same first record

I have eigtheen image controls in a form for browsing images in a multiple
column and rows arrangements which I am adopting from [Roggers website].1
It was challenging for me to understand fully how I could modify it for my
purpose but one person here helped me up to the stage where I could open a
details form upon clicking any one of the unbound image controls in the
form.
The problem I have now is that although the form opens it returns the same
data for the first record in the database regardless of which control I
click.
I know how to make a simple criteria for a single control like "[ItemID]
=" & Me.lstItems, but in this case the image controls are multiple and
arranged in a column and rows pattern. I think that the image controls are
populated with the this code, were "Im_" can be one of the eighteen image
controls:
Me("Im_" & Format(Cnt, "00")).Picture = Nz(rst.Fields("ImageFile"), "")
I need to know how I can add a criteria to the event or function so that
the form opens with related data in it.
This is the function for the click event:
Function OpenMyForm(strFormName As String)
DoCmd.OpenForm strFormName
End Function
This is the click event itself included in the code below under Private
Sub P_SetValues(Cnt As Long):
Me("Im_" & Format(Cnt, "00")).OnClick = "=OpenMyForm('F_Details')"
And the whole code behind the main form:
Private Sub P_FillControls()
On Error GoTo ErrTrap
Dim Cnt As Long
Cnt = 1
Do Until (Cnt > BlockSize Or rst.EOF)
P_SetValues Cnt
Cnt = Cnt + 1
rst.MoveNext
Loop
If Cnt <= BlockSize Then
For Cnt = Cnt To BlockSize
P_SetNulls Cnt
Next
End If
ExitPoint:
On Error GoTo 0
Exit Sub
ErrTrap:
MsgBox Err.Number & " - " & Err.Description
Resume ExitPoint
End Sub
Private Sub P_SetValues(Cnt As Long)
On Error GoTo ErrTrap
If RecCount > 0 Then
Me("Rn_" & Format(Cnt, "00")).Caption = (rst.AbsolutePosition + 1)
Else
Me("Rn_" & Format(Cnt, "00")).Caption = ""
End If
Me("Lb_" & Format(Cnt, "00")).Caption = Nz(rst.Fields("ImageName"), "")
Me("Im_" & Format(Cnt, "00")).Picture = Nz(rst.Fields("ImageFile"), "")
Me("ID_" & Format(Cnt, "00")) = rst.Fields("ImageFile")
' Note - For no caption, dot is used in lieu of
' zero length string, so as to prevent the
' label from disappearing
Me("Im_" & Format(Cnt, "00")).OnClick = "=OpenMyForm('F_Details')"
ExitPoint:
On Error GoTo 0
Exit Sub
ErrTrap:
MsgBox Err.Number & " - " & Err.Description
Resume ExitPoint
End Sub
Private Sub P_SetNulls(Cnt As Long)
On Error GoTo ErrTrap
Me("Rn_" & Format(Cnt, "00")).Caption = "."
Me("Lb_" & Format(Cnt, "00")).Caption = "."
Me("Im_" & Format(Cnt, "00")).Picture = "."
Me("ID_" & Format(Cnt, "00")) = Null
' Note - For no caption, dot is used in lieu of
' zero length string, so as to prevent the
' label from disappearing
ExitPoint:
On Error GoTo 0
Exit Sub
ErrTrap:
MsgBox Err.Number & " - " & Err.Description
Resume ExitPoint
End Sub
Public Sub P_Initialize()
On Error Resume Next
RecCount = 0 ' Default
Me.LbNoImage.Visible = False
' Remove any existing instance of the recordset
If Not rst Is Nothing Then
rst.Close
Set rst = Nothing
End If
' This recordset will finally get closed in form's
' close event.
Set rst = CurrentDb.OpenRecordset("Q_ImageNormalSort")
' Set rst = CurrentDb.OpenRecordset("Q_Dynamic_Query")
If rst.EOF And rst.BOF Then
' There are no records
P_FillControls
Me.LbNoImage.Visible = True
P_SetStatusNavBtns
Me.CmdAdd.SetFocus
Exit Sub
End If
rst.MoveLast
RecCount = rst.RecordCount
LastID = rst.Fields("ImageFile")
rst.MoveFirst
FirstID = rst.Fields("ImageFile")
' First Load (signified by step size argument = 0)
P_Next 0
Me.LbRecMsg.Caption = "Of " & RecCount
On Error GoTo 0
End Sub
Function OpenMyForm(strFormName As String)
DoCmd.OpenForm strFormName
End Function
I will appreciate.
Joseph

How to read matrix elements one by one from file, C++

How to read matrix elements one by one from file, C++

This might be an elementary question. I'm new to C++ and I want to
implement a huge random matrix which might not fit in the memory. So I
think maybe I should write it into a file and read in element by element
in a stream.
What I want to check is, if the element is smaller than a threshold. If
yes, push the index of the element (i,j) in a stl vector for storage, if
no, go to the next element.
Basically I need a couple of lines that write a matrix AJM into
matrix.txt, and then read its element as:
for(int i = 0; i < ROWS; i++){ for(int j = 0; j < COLS; j++){
currentElement = "read AJM[i][j] from file"; } }
So "read AJM[i][j] from file" is not clear to me, I guess it's done by
iterate the file pointer to some certain position given by i and j, and
specify how many bytes to read, right?
Could you show me the C++ code to write matrix.txt and read in element one
by one knowing its index, so that I avoid storing the whole matrix in the
memory?
Thank you so much!

Redirecting a site using Parallels Plesk Panel 9.3.0

Redirecting a site using Parallels Plesk Panel 9.3.0

I am using Parallels PLesk for the first time, and am a little lost.
I am trying to redirect my entire site / domain to a different domain and
cannot find a section in the control panel to do this.
I have tried in web hosting settings for the domain, and also in all other
sections, and cannot seem to find where this is done?
any guidance in the right direction would be greatly appreciated :) thank you

Looping over cursor not same count as cursor count on android

Looping over cursor not same count as cursor count on android

In my app I´m using a SimpleCursorAdapter to display contacts.
Each view has it´s own checkbox. in order to check all, I´m going through
the cursor, putting each ID to a Set, which is progressed by the getView()
method to trigger checkboxes.
The problem is here:
int counter = 0;
if (cursor.moveToFirst())
while (cursor.moveToNext()) {
contact_ids_to_skip.add(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID)));
counter++;
}
The first list entry is always triggered, because counter is 157, and
cursor.getCount() is 158.
I do not know what is happening here. I thought cursor.moveToFirst() is
putting the cursor into its right position, but thats not the case.
How can I solve this?

Fake Call Implementation using phonegap

Fake Call Implementation using phonegap

I'm working on one app which has Fake Call feature. It does not need it to
be an actual call. It will be just a screen that looks like it is calling,
with a ringtone and display. Once the user touches the screen it should
not have any functionality.
Can anyone suggest if it is possible using phonegap? If yes, what will be
the steps of implementation.
Thanks in advance.
Best regards, Vinay

How to convert wordpress from english to japanese?

How to convert wordpress from english to japanese?

I have a wordpress site it is now in English, But i have to convert it
completely in wordpress.
All posts, links,terms,taxonomy also db entries everything to japanese.
Can anyone suggest me how to do this, i dont want to use any plugin.
Thanks

Tuesday, 17 September 2013

Get Webcam status (turn on/off) without turning it on

Get Webcam status (turn on/off) without turning it on

I m trying to write an application by c++ that check if the webcam is
turned on or off.
The only way I found is Using COM component. but it just run the Webcam,
if failed it return IN-USE, otherwise turn the webcam on.
The problem : My need is webcam doesn't turn on!
Is there any solution could help me find "Is webcam turn on or off"?

Parse error: syntax error, unexpected ')', expecting :: (T_PAAMAYIM_NEKUDOTAYIM)

Parse error: syntax error, unexpected ')', expecting ::
(T_PAAMAYIM_NEKUDOTAYIM)

I have the following code
define("SCRIPT_URL", "");
function ifScriptFolder() {
if(isset(SCRIPT_URL) && !empty(SCRIPT_URL)) {
echo "/".SCRIPT_URL."/";
} else {
echo "/";
}
}
but it's giving me the following error:
Parse error: syntax error, unexpected ')', expecting ::
(T_PAAMAYIM_NEKUDOTAYIM) in *(path)* on line 3
Can anyone see what's going wrong here or how to fix it?

Highstock - insert HTML link inside flag tooltip

Highstock - insert HTML link inside flag tooltip

I create a flag data point in the following manner
eventData = []
event = {
x : Date.UTC(2011, 3, 25),
title : 'A',
text : "<a href='http://google.com'>Google</a>"
}
series.push({
type:"flags",
data:eventData
});
Now I get the text "google" but I can't click on it. What's the best way
to achieve this?
Also, if this is possible (I'm pretty sure it's possible, because I swear
I've seen it before!) is there also a way to open the link in a new tab
window?

wrong value when converting String date to date Object

wrong value when converting String date to date Object

When I convert String date like "18/09/13,02:01:51" Using this method:
public static Date stringToDateFormat(String dateString) {
Date date = null;
try {
date = new SimpleDateFormat("dd/MM/yy,hh:mm:ss").parse(dateString);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
When I save this convert this date object to SQL Date and store it in
PostgreSQL Database, I lose the time 2013-09-18 00:00:00
Is it coding problem or DB configuration?
Thanks.

read csv with initial white space in pandas

read csv with initial white space in pandas

I have a problem in pandas with a csv file that has initial whitespace in
some columns, for example:
pd.read_csv(StringIO("""1 2\n 3 4\n5 6"""), delim_whitespace=True,
names=["a", "b"], skipinitialspace=True)
a b
0 1 2
1 NaN 3
2 5 6
I tried using instead \s+ regular expression as separator and it works as
I expect:
pd.read_csv(StringIO("""1 2\n 3 4\n5 6"""), sep="\s+", names=["a", "b"])
a b
0 1 2
1 3 4
2 5 6
However, I would like to understand why skipinitialspace is not solving
the issue in the first case.

java swing button can change panel into a text area of same size?

java swing button can change panel into a text area of same size?

Like if we have an gui interface like
name:
occupation:
can we direct the input with a button to the same space of panel with a
jtextarea like the panel was in frame of 200,200 now after entering the
details and submitting it using a button can we have the output on the
same place with 200,200 JTextArea,

Sunday, 15 September 2013

Rails: How to test dynamically define methods that are based on other model

Rails: How to test dynamically define methods that are based on other model

I have a model called DeviceState which contains states like
"active","offline","online".
I have another model called Device which belongs_to to DeviceState.
Now, to have methods such as @device.active? and @device.offline? on the
device model I've defined a dynamic method like so:
DeviceState.all.each do |method|
define_method((method.name + "?").to_sym) do
self.device_state.name == method.name
end
end
My problem is that when I try to create tests on the Device model, the
dynamic method are not created because the DeviceState model hasn't been
populated on the database while the test environment started up. So by the
time I create the DeviceState data with factory girl it would be too late.
One solution I tried is to seed the DeviceState in spec_helper, however
while this worked for the first test I didn't work for all the rest as the
database cleaner removed the data.
So what would be the best way to overcome those dynamically defined methods?
Thanks.

UIButton change title on press using a counter

UIButton change title on press using a counter

I get an error with the code below.. I'm banging my head against the wall
because I can't figure out why I can't seem to have the message updated
with the number of button presses (a counter) each time you press the
button...
- (IBAction)countButtonTapped:(id)sender {
self.pressCount+=1;
//int count = (int)self.pressCount;
//[self.tapCountButton setTitle:@"I've been tapped %i time(s)!"
forState:UIControlStateNormal];
//[self.tapCountButton setTitle:@"I've hit the main button!"
forState:UIControlStateNormal];
//NSLog(@"I've been tapped %lu time(s)!", (unsigned
long)self.pressCount);
[(UIButton *)sender setTitle:@"I've been tapped %@
time(s)!",self.pressCount forState:UIControlStateNormal];

.htaccess in Subfolder not working

.htaccess in Subfolder not working

I have a url Like
http://localhost/coupon/stores.php?store_slug=url
I want to change it like this
http://localhost/coupon/url
I tried with this code
RewriteEngine on
RewriteBase /coupon/
RewriteCond %{REQUEST_FILENAME} ! -f
RewriteCond %{REQUEST_FILENAME} ! -d
RewriteRule (.*) stores.php?store_slug=$1
but its not working with the above mentioned .htaccess code am getting 500
internal server error. I am using this .htaccess file in sub folder ie
coupon
can anybody check where am doing wrong ?

CSS/Javascript code to provide image border for many sizes of HTML div

CSS/Javascript code to provide image border for many sizes of HTML div

I'm intending to write a HTML5/Javascript game to run in modern browsers.
It will need dialog boxes (i.e. modal popups) whose borders would be made
of images (e.g. one for the vertical, one for the horizontal, one for each
corner). The popups, and therefore border, should contain and size to a
div (containing text or whatever). There will be lots of different size
popups.
I hope that my requirements are clear enough. Can I do this with just CSS?
Are there some sample CSS 'libraries' to do this? Or do I need to use
Javascript (or a combination of CSS and Javascript) and, again, if so
there any example or libraries I can use?

Passing cli parameters to casperjs through grunt task and npm test

Passing cli parameters to casperjs through grunt task and npm test

I'm running tests with npm test - that actually runs a grunt task grunt
casperjs:
casperjs:{
options:{},
files:
['./test_index.js',
'./test_map_regression.js',
'./test_index_get_gush.js'] /
},
using the grunt-casperjs-plugin in order to automate testing with slimerjs
along with phantomjs, both running under casperjs in Travis-ci.
In order to do that, I need to pass the engine as a variable from the
command line. something like:
casperjs --engine=slimerjs test_suite.js
Question: I can't find a way to pass the options from grunt cli (and I
assume npm command line options would delegate to grunt. correctly?) to
the files array.
I tried to add:
var engine = grunt.option('engine') || 'phantomjs';
engine = '--engine='+engine;
and then in the file array do:
files:['./test_index.js '+engine,
'./test_map_regression.js '+enging,
'./test_index_get_gush.js '+engine]
but seems that file array has to get real file names without the added args.
I'll be glad for any ideas on how to solve this through.

Ruby-on-Rails update_attributes strong pramaters rails 4

Ruby-on-Rails update_attributes strong pramaters rails 4

I'm attempting to follow
http://railscasts.com/episodes/165-edit-multiple-revised for updating
multiple records simultaneously. However I need to make some changes to
accommodate rails 4.
The controller:
def update_multiple
@products = Product.find(params[:product_ids])
@products.reject! do |product|
product.update_attributes(params[:product].reject { |k,v| v.blank? })
end
end
def product_params
params.require(:product).permit(:id, :x, :y, :z)
end
This throws an error on the update_attributes I understabd rails 4
requires strong paramaters so I have tried:
product.update_attributes(product_params.reject { |k,v| v.blank? })
and
product.update_attributes(product_params[:product].reject { |k,v| v.blank? })
again both throw errors.

Custon SeekBar (vertical)

Custon SeekBar (vertical)

I need to implement my own Vertical SeekBar. I wrote class and define in XML.
Java class:
package com.example.Radio_KPI.utils;
import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.widget.SeekBar;
public class VerticalSeekBar extends SeekBar {
public VerticalSeekBar(Context context) {
super(context);
}
public VerticalSeekBar(Context context, AttributeSet attrs, int
defStyle) {
super(context, attrs, defStyle);
}
public VerticalSeekBar(Context context, AttributeSet attrs) {
super(context, attrs);
}
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(h, w, oldh, oldw);
}
@Override
protected synchronized void onMeasure(int widthMeasureSpec, int
heightMeasureSpec) {
super.onMeasure(heightMeasureSpec, widthMeasureSpec);
setMeasuredDimension(getMeasuredHeight(), getMeasuredWidth());
}
protected void onDraw(Canvas c) {
c.rotate(-90);
c.translate(-getHeight(), 0);
super.onDraw(c);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (!isEnabled()) {
return false;
}
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_MOVE:
case MotionEvent.ACTION_UP:
int i = 0;
i = getMax() - (int) (getMax() * event.getY() / getHeight());
setProgress(i);
Log.i("Progress", getProgress() + "");
onSizeChanged(getWidth(), getHeight(), 0, 0);
break;
case MotionEvent.ACTION_CANCEL:
break;
}
return true;
}
}
XML code:
<com.example.Radio_KPI.utils.VerticalSeekBar
android:id="@+id/volume_bar"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:progress="0"
android:max="100"
android:progressDrawable="@drawable/progressbar"
android:secondaryProgress="0" />
Error:

Saturday, 14 September 2013

python find substrings based on a delimiter

python find substrings based on a delimiter

I am new to python , so I might be missing some thing simple.
I am given a example
string = "The , world , is , a , happy , place "
I have to create substrings separated by , and print them and process
instances separately . i.e. in this example i should be able to print
The
world
is
a
happy
place
What approach can i take . I was trying to use string find functionality ,
but
Str[0: Str.find(",") ]
does not helps in finding 2nd , 3rd instances .

Maximum gigabit ethernet speed

Maximum gigabit ethernet speed

Might be a simple question but I'm not too sure how this works so just
look for some clarification.
I've read that gigabit switches can transfer at speeds up to 1gbit but I'm
just wondering if this means that a 1gbit NIC would not be able to send at
speeds of more than 500mbit while receiving data at speeds of 500mbit.

Why is my definition of a function that chooses an element from a finite set inconsistent?

Why is my definition of a function that chooses an element from a finite
set inconsistent?

I would like to reason about functions that choose one element from a
finite set.
I tried to define a predicate that tells me whether some given function is
such a gchooserh function:
definition chooser :: "('a set Ë 'a) Ë bool"
where "chooser f &#10231; (Í A . finite A &#10230; f A ¸ A)"
Actually those finite sets from which I'd like to choose elements are of a
concrete type, but putting a concrete type in 'a's place causes the same
trouble.
I have also tried to omit finite A, but the sets I'm dealing with are
finite, and I don't even want to think about the axiom of choice here.
Now this definition seems to be inconsistent:
lemma assumes "chooser f" shows "False" using assms chooser_def by force
How can I define chooser in a reasonable way? I would like to use it as
follows:
assume "finite A"
moreover assume "chooser f"
moreover assume "choice = f A"
ultimately have "choice ¸ A" by ???
Most of the time it merely matters that a member of the set is chosen, not
how it is chosen.



Background: I'd like to formalise tie-breakers in auctions (section 4 of
this paper). Suppose there are two highest bids for the item being
auctioned, we need to arbitrarily choose the one bidder who should win the
auction.



Here is, BTW, a really minimal example (which is a bit harder to understand):
lemma "(Í A . finite A &#10230; f A ¸ A) &#10233; False" by force

Wrong date format displayed

Wrong date format displayed

I am trying to display date in this format dd/MM/yyyy
Model addnotations
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode
= true)]
instead I am getting date in format dd-MM-yyyy I have also tried
dd.MM.yyyy which works fine.Anything works fine except desired result...

How to write a minimal example of secure downloads with lighttpd?

How to write a minimal example of secure downloads with lighttpd?

There is quite a good wiki on how to use Lighttpd to do secure downloads
with django. The idea is to do this (in your view?) and use the
mod_secdownloads module:
def gen_sec_link(rel_path):
import time, hashlib
secret = 'verysecret'
uri_prefix = '/dl/'
hextime = "%08x" % time.time()
token = hashlib.md5(secret + rel_path + hextime).hexdigest()
return '%s%s/%s%s' % (uri_prefix, token, hextime, rel_path)
The only problem is the implementation. I have an app in which a number of
models have a field that determines whether they are public.
public = models.BooleanField(default = False)
Now if that field is True I want to file to be easily downloadable using a
standard /media/file.txt link. If that field is False I want that file to
be only accesible for secure downloads both frontend and in the admin. I
do not want to rewrite every single view that has a link to a file.
How can I implement this? Should this be in models.py? Can anyone give me
a minimal example?

How to create custom controller and form for login and registration in YII

How to create custom controller and form for login and registration in YII

Please tell me how to I create my custom login and registration in YII
without generating the crud/controller.

Converting TableView Storyboards from iPhone to iPad

Converting TableView Storyboards from iPhone to iPad

I have read the responses to this question. They are good, but I don't
think they answer how to convert table view based storyboards. For
example, iPad tables are usually built on a UISplitView.
I know too, that I can copy various scenes. But that doesn't create all
the seques, and with a fair number of scenes (i.e. >20), organizing and
debugging can create a bit of havoc.
What then, have people found as the best practices (least work, easiest to
debug), to manage TableView conversions?
Many thanks

Friday, 13 September 2013

Phonegap application Database Issue

Phonegap application Database Issue

I am developing iOS application using phonegap(Cordova 2.2) and Kendo ui
mobile . My applications is working well. I am using pre populated
database to my application and i copied pre populated database to app
Library/Webkit/LocalStorage folder. Its working fine too. But problem is
when app runs first time , it not take correct database path.
When i open database in first time, it take Database from Library/Caches
folder. But i run app second time its work properly and app take database
path from Library/Webkit/LocalStorage folder.
Correct path is Library/Webkit/LocalStorage
Wrong path is Library/Caches
What is the reason for it? Please help me. Thank you.

Query all items and ignore if condition

Query all items and ignore if condition

I current have two functions which perform queries on my database; the
first one performs a query on all my entries and the second has a
specification (for version control).
Database
id | version_id
---------------
1 | 1
2 | 2
3 | 1
4 | 1
Code
public function post($postid)
{
global $db;
$query = "SELECT * FROM news WHERE id='$postid'";
return $db->select($query);
}
public function version_count()
{
global $db;
$query = "SELECT * FROM news WHERE post_id='1' ORDER BY version_id
DESC LIMIT 1";
return $db->select($query);
}
To display my entries, I've tried the following, which does as expected,
giving me all entries:
$posts_array = $query->post($post);
foreach ( $counted_versions as $post )
{
echo $post->id . "-";
}
However, I only want to echo rows 2 and 4, since 2 is unique and 4 is the
most recent.
At first, I thought this logic would work :
$posts_array = $query->post($post);
$counted_versions = $query->version_count();
foreach ( $counted_versions as $counted )
{
foreach ( $posts_array as $post )
{
echo $post->id . "-";
}
}
But rather, I get 1-2-3-4- and if I switch my foreach loops around, I get
4-4-4-4-, whereas I would expect 2-4 or at the very least 1-4 (or 4-2 or
4-1).
Anybody have a way to get a similar result?

SharePoint 2013 TaxonomyFieldType in custom list has IsTermSetValid = False

SharePoint 2013 TaxonomyFieldType in custom list has IsTermSetValid = False

I'm using Visual Studio 2012 to create a custom Site Column of type
TaxonomyFieldType, a custom content type that uses it, and a custom list
that uses the content type.
Everything appears to deploy fine. If I look at my custom site column it
appears to reference the proper termset correctly. I can create a new list
in the web UI that uses my custom content type just fine. However, my
custom list created using the Visual Studio 2012 List template always
shows my taxonomy field as disabled on the new form. Here are the other
things I've witnessed about it:
In the web UI of SharePoint, if I go to the list properties and drill into
my taxonomy site column I notice it shows that it isn't mapped to a
termset. Keep in mind that if I do the same thing in Site Settings for my
content type it appears correct. I can do the same thing for the web UI
created custom list and everything is fine (editable in the new form and
the field has the termset defined).
If I use powershell to dump out the info for the site column itself it has
a valid termset.
If I use powershell to dump out the info for the field in the VS2012
created list it shows emtpy guid for the SspId, TermSetId, and TextField.
It also shows IsTermSetValid = False.
If I use powershell to dump out the info for the field in the SharePoint
web UI created list it shows the correct guid for the SspId, TermSetId,
and TextField. It also shows IsTermSetValid = True.
Does anyone know why I seem to be having this behavior for the VS 2012
create custom list? Any help is appreciated.

How to create transparent slider in javafx

How to create transparent slider in javafx

I am trying to create a slider whose thumb is transparent. Idea here is, i
want a slider with some labels and icon behind it. When my slider (thumb)
comes on top of label/icons, the labels/icons are visible through the
thumb of slider.
May be i have to use css or some other way ? I am not sure how to actually
achieve it. I am attaching an image of what i want to achieve.

Please help.

What's the used for new dll "sunec.dll" file along with JAVA7

What's the used for new dll "sunec.dll" file along with JAVA7

I just noticed there is one new dll file named sunec.dll since JAVA7.
I did a lot of google time to get understand what is used for?
Can anyone prvovide one instroduciton about this new file??
Thansk a lot

Thursday, 12 September 2013

Pointer manipulation in java

Pointer manipulation in java

I have an question in my mind,
What are the reasons for restricting Java not to support Pointer
Manipulations?
If anyone knows that then, please clarify it .?

Need Help Exception at Public Game1() in MonoGame on OSX

Need Help Exception at Public Game1() in MonoGame on OSX

So i'm trying to create this program that works perfect in Visual Studio
2012 at School. But when i'm at home it's giving me this Thrown Exception
error at Public Game1(). Hopefully someone can help me out with this so
that way i can actually run my program and finish it.
The Call Stack is:
System.NullReferenceException: Object reference not set to an instance of
an object at Microsoft.Xna.Framework.OpenTKGameWindow.Initialize ()
[0x00000] in :0 at Microsoft.Xna.Framework.OpenTKGameWindow..ctor ()
[0x00000] in :0 at Microsoft.Xna.Framework.OpenTKGamePlatform..ctor
(Microsoft.Xna.Framework.Game game) [0x00000] in :0 at
Microsoft.Xna.Framework.GamePlatform.Create (Microsoft.Xna.Framework.Game
game) [0x00000] in :0 at Microsoft.Xna.Framework.Game..ctor () [0x00000]
in :0 at MonoGameTest.Game1..ctor () [0x00023] in
/Users/sebnabt/Projects/MonoGameTest/MonoGameTest/Game1.cs:38 at
MonoGameTest.Program.Main () [0x00001] in
/Users/sebnabt/Projects/MonoGameTest/MonoGameTest/Program.cs:19
And my code:
`
region Using Statements
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Storage;
using Microsoft.Xna.Framework.Input;
endregion
namespace MonoGameTest
{
/// <summary>
/// This is the main type for your game
/// </summary>
public class Game1 : Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
// Maps user keys to display colors
Dictionary<Keys, Color> key_to_color = new Dictionary<Keys, Color>();
// these are the colors guessed by the user, so far.
List<Color>[] player_colors = new List<Color>[10];
// these are the keys that correspond to a dot color
List<Keys> color_letters = new List<Keys>();
Texture2D dot_picture;
KeyboardState old_keyboard_state;
int row;
public Game1() : base()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
base.Initialize ();
}
/// <summary>
/// Allows the game to perform any initialization it needs to before
starting to run.
/// This is where it can query for any required services and load any
non-graphic
/// related content. Calling base.Initialize will enumerate through any
components
/// and initialize them as well.
/// </summary>
///
/// // screen constants
const int SCREEN_WIDTH = 640;
const int SCREEN_HEIGHT = 480;
protected override void Initialize()
{
row = 0;
// back buffer
graphics.PreferredBackBufferHeight = SCREEN_HEIGHT;
graphics.PreferredBackBufferWidth = SCREEN_WIDTH;
graphics.PreferMultiSampling = false;
graphics.ApplyChanges();
base.Initialize();
// initialize the color dictionary
key_to_color.Add(Keys.R, Color.Red);
key_to_color.Add(Keys.G, Color.Green);
key_to_color.Add(Keys.B, Color.Blue);
key_to_color.Add(Keys.Y, Color.Yellow);
color_letters = new List<Keys>();
foreach (Keys letter in key_to_color.Keys)
{
color_letters.Add(letter);
}
}
/// <summary>
/// LoadContent will be called once per game and is the place to load
/// all of your content.
/// </summary>
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
// load our textures
dot_picture = Content.Load<Texture2D>(@"media\ball");
}
/// <summary>
/// Allows the game to run logic such as updating the world,
/// checking for collisions, gathering input, and playing audio.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Update(GameTime gameTime)
{
// get keyboard state once per frame
KeyboardState keyState = Keyboard.GetState();
// exit the game?
if (keyState.IsKeyDown(Keys.Escape))
{
this.Exit();
}
// erase list of player colors?
else if (keyState.IsKeyDown(Keys.Space))
{
player_colors[this.row].Clear();
}
// player pressed a color key?
else {
foreach (Keys letter in color_letters)
{
if (key_was_released(letter, keyState))
{
add_color(letter);
}
if (this.player_colors [row].Count () >= 4) {
this.row = this.row + 1;
}
}
}
old_keyboard_state = keyState;
base.Update(gameTime);
}
protected override void UnloadContent() {
}
bool key_was_released(Keys key, KeyboardState new_state)
{
return old_keyboard_state.IsKeyDown(key) &&
new_state. IsKeyUp (key);
}
void add_color(Keys key)
{
Color color = key_to_color[key];
if (player_colors[this.row].Count() < 4)
{
player_colors[this.row].Add(color);
}
}
/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
graphics.GraphicsDevice.Clear (Color.CornflowerBlue);
// draw typical sprites
spriteBatch.Begin ();
draw_player_colors (spriteBatch);
spriteBatch.End ();
base.Draw (gameTime);
}
protected void draw_player_colors(SpriteBatch batch)
{
for (int current_row = 0; current_row < 10; current_row++) {
for (int column = 0; column < player_colors[current_row].Count();
column++) {
int x = 100 + column * 70;
int y = 100 + column * 70;
Vector2 loc = new Vector2 (x, y);
Color c = player_colors[current_row].ElementAt (column);
batch.Draw (dot_picture, loc, c);
}
}
}
}
}
`

do I have to declare the $http service when requiring other services?

do I have to declare the $http service when requiring other services?

angular.module("ABC.services").service("configService", [
'loggerService', function(logger, $http) {
debugger;
return this.get = function(onError, onSuccess) {
return $http.get("/api/config/").success(function(config) {
logger.debug('loaded config');
return onSuccess(config);
}).error(onError);
};
}
]);
(I have a logger that's more complex than $log)
I find that at the debugger line $http is undefined unless I include
'$http' in the list of dependencies. The docs don't discuss this use case.
Their example of native service injection looks like:
angular.module('myModule', [], function($provide) {
Would I be required to declare $provide as a dependency if I was also
using one of my own services? I'm just really confused about when I can
rely on the automatic injection of $ services and when I have to
explicitly declare them.

Seleceted Value from a ListBox WPF .NET 3.5

Seleceted Value from a ListBox WPF .NET 3.5

I have a listbox in my WPF app. The definition is given below:
<ListBox Margin="17.493,33.32,22.491,26.656" Name="lstData"
PreviewMouseLeftButtonDown="ListBox_MouseDown"
IsTextSearchEnabled="False" />
In the code behind, I bind the ListBox to a List. When the value is
selected from the List Box, in my code behind, I want to be able to
retrieve that value. How do I do it? Sample C# code will be helpful.
Thanks.

preg_grep returning whole string instead of part

preg_grep returning whole string instead of part

the following code is run
$mysqlquery = "SELECT `description` FROM `table`";
$sqlresourceid = mysql_query($mysqlquery);
$subject = mysql_fetch_row($sqlresourceid);
$regexisbn = '/(97(8|9))?\d{9}(\d|X)/i';
$pattern = '/.*/i';
$matches = preg_grep ($regexisbn, $subject);
var_dump($matches);
however this returns the following
ISBN10: 0470945176 by Paul D. Kimmel Publisher: John Wiley & Sons
Copyright year: © 2011
I just wanted it to return the ISBN 0470945176 , how come this is happening?

Django: Request Times Out When Resizing 10,000 Pictures

Django: Request Times Out When Resizing 10,000 Pictures

I'm trying to resize pictures stored on my Amazon S3 service by
downloading them on to my EC2 Django Server w/Gunicorn, modifying them and
then sending it back to S3. I'm downloading the pictures via the url
stored in my database, here is my code below to give you a better
understanding:
import urllib
import Image
import os
from boto.s3.connection import S3Connection
from boto.s3.key import Key
def resize(request):
queryset = Pictures.objects.all()
for picture in queryset:
s3_url = picture.url
filename = s3_url.split('/')[-1].split('.')[0]
print filename
download_photo = urllib.urlretrieve(s3_url,
"/home/ubuntu/Desktop/Resized_Images/%s.jpg" % (filename))
downloaded_photo =
Image.open("/home/ubuntu/Desktop/Resized_Images/%s.jpg" %
(filename))
resize_small = downloaded_photo.resize((100, 100), Image.ANTIALIAS)
small_filename = filename + "_small"
print small_filename
resize_small.save("/home/ubuntu/Desktop/Resized_Images/%s.jpg" %
(small_filename))
resize_medium = downloaded_photo.resize((300, 300), Image.ANTIALIAS)
med_filename = filename + "_medium"
print med_filename
resize_medium.save("/home/ubuntu/Desktop/Resized_Images/%s.jpg" %
(med_filename))
os.remove("/home/ubuntu/Desktop/Resized_Images/%s.jpg" % (filename))
bucket_name = settings.BUCKET_NAME
# connect to the bucket
conn = S3Connection(settings.AWS_ACCESS_KEY_ID,
settings.AWS_SECRET_ACCESS_KEY)
bucket = conn.get_bucket(bucket_name)
k = Key(bucket)
k.key = '%s/%s.jpg' % (username, small_filename)
k.set_contents_from_filename("/home/ubuntu/Desktop/Resized_Images/%s.jpg"
% (small_filename))
k.make_public()
os.remove("/home/ubuntu/Desktop/Resized_Images/%s.jpg" %
(small_filename))
j = Key(bucket)
j.key = '%s/%s.jpg' % (username, med_filename)
j.set_contents_from_filename("/home/ubuntu/Desktop/Resized_Images/%s.jpg"
% (med_filename))
j.make_public()
os.remove("/home/ubuntu/Desktop/Resized_Images/%s.jpg" %
(med_filename))
print 'Photos have been resized and sent to the FoodShot S3 Bucket'
return HttpResponse("Success")
When I tried this in development, it worked. On my development server, I
had about 50-60 urls. But on my production server, I have about 10,000
urls of images that I need to download and resize. However the request
keeps timing out, what should I do?

Awk merging of two files on id

Awk merging of two files on id

I would like to obtain the match the IDs of the first file to the IDs of
the second file, so i get, for example, Thijs Al,NED19800616,39. I know
this should be possible with AWK, but I'm not really good at it.
file1 (few entries)
NED19800616,Thijs Al
BEL19951212,Nicolas Cleppe
BEL19950419,Ben Boes
FRA19900221,Arnaud Jouffroy
...
file2 (many entries)
38,FRA19920611
39,NED19800616
40,BEL19931210
41,NED19751211
...

python: calling a method with a string and input()

python: calling a method with a string and input()

I'm brushing up on my Python and I'm a little confused about something,
the following code does not work as intended:
def a():
print "called a"
def b():
print "called b"
dispatch = {'go':a, 'stop':b}
dispatch[input()]()
When I type the word go into the console, I get "NameError: name 'go' is
not defined", but when I type 'go' (with the quotes) it works fine. Is
input() not returning a string? And if not, then shouldn't using str()
convert the input to a string?
When I change the code to:
dispatch[(str(input())]()
I still get the same behaviour.
note: I'm using Python2.7 if it makes a difference.
Sorry if this is obvious, it's been a few years since I've used Python!

Wednesday, 11 September 2013

jQuery show/hide drop-down options based on another drop-down option

jQuery show/hide drop-down options based on another drop-down option

I am trying to create a drop-down select menu that will consist of three
select boxes, where the 3rd box will show/hide specific option based on an
option selected in the 1st select box.
I was wondering if anyone here is be able to suggest a solution to this.
Here is a simplified version of the 3 select boxes I have:
<select class="product" id="select_1" name="product">
<option selected="selected" value=""> Choose Category </option>
<option value="Mens Suits"> Mens Suits </option>
<option value="Womens Suit"> Womens Suits </option>
<option value="Children Suit"> Children Suits </option>
</select>
<select class="color" id="select_2" name="color">
<option selected="selected" value=""> Choose Color </option>
<option value="Blue">Blue</option>
<option value="Red">Red</option>
<option value="Green">Green</option>
</select>
<select class="size" id="select_3" name="size">
<option selected="selected" value=""> Choose Size </option>
<!-- Mens Sizes Below -->
<option value="36">36</option>
<option value="38">38</option>
<option value="40">40</option>
<!-- Womens Sizes Below -->
<option value="30">30</option>
<option value="29">29</option>
<option value="28">28</option>
<!-- Children Sizes Below -->
<option value="12">12</option>
<option value="11">11</option>
<option value="10">10</option>
</select>
With the example above, I would like to be able to view the first 3
options from the 3rd select box (36, 38, and 40) when the option Mens
Suits from the 1st select box is chosen. Similarly, when the Womens Suits
is selectedfrom the 1st box, the options 30, 29, and 28 should be visible
in the 3rd box. The same with the Children Suits.
I hope this makes sense. Thank you.

Best way to pass data objects to Grand Central Dispatch Task

Best way to pass data objects to Grand Central Dispatch Task

Question: What is the preferred/best/accepted practice for passing data
(beyond primitives) to a background task using Grand Central Dispatch
(GCD)?
What concerns me with objective C blocks is this: Variables accessed by
the block are copied to the block data structure on the heap so that the
block can access them later. Copied pointer references could mean multiple
threads are accessing the same object.
I'm still fairly new to objective C and iOS but I'm not new threads (C++,
Java, C, C#).
Code set #1 (Primitive Copy from scope)
//Primitive int
int taskIdBlock = self->taskNumber;
//declare a block that takes in an ID and sleep time.
void (^runTask)(int taskId, int sleepTime);
//Create and assign the block
runTask = ^void(int taskId, int sleepTime)
{
NSLog(@"Running Task: %d", taskId);
// wait for x seconds before completing this method
[NSThread sleepForTimeInterval:sleepTime];
//update the main UI
//tell the main thread we are finished with this task.
dispatch_async(dispatch_get_main_queue(), ^
{
NSLog(@"Completed Task %d",taskId);
});
};
//Get the global concurrent dispatch queue and launch a few tasks
dispatch_queue_t globalConcurrentQueue =
dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//TASK #1
//increment the task number and log
NSLog(@"Create Task Number %d", ++taskIdBlock);
//dispatch the task to the global queue.
dispatch_async(globalConcurrentQueue, ^{
runTask(taskIdBlock,5);
});
//TASK #2
//increment the task number and log
NSLog(@"Create Task Number %d", ++taskIdBlock);
//dispatch the task to the global queue.
dispatch_async(globalConcurrentQueue, ^{
runTask(taskIdBlock,3);
});
Output:
Create Task Number 1
Create Task Number 2
Running Task: 1
Running Task: 2
Completed Task 2
Completed Task 1
Code set #2 (Object Reference Copy from scope)
//Integer Object
NSInteger *taskIdBlock = &(self->taskNumber);
//declare a block that takes in an ID and sleep time.
void (^runTask)(int taskId, int sleepTime);
//Create and assign the block
runTask = ^void(int taskId, int sleepTime)
{
NSLog(@"Running Task: %d", taskId);
// wait for x seconds before completing this method
[NSThread sleepForTimeInterval:sleepTime];
//update the main UI
//tell the main thread we are finished with this task.
dispatch_async(dispatch_get_main_queue(), ^
{
NSLog(@"Completed Task %d",taskId);
});
};
//Get the global concurrent dispatch queue and launch a few tasks
dispatch_queue_t globalConcurrentQueue =
dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//TASK #1
//increment the task number and log
NSLog(@"Create Task Number %d", ++(*taskIdBlock));
//dispatch the task to the global queue.
dispatch_async(globalConcurrentQueue, ^{
runTask(*taskIdBlock,5);
});
//TASK #2
//increment the task number and log
NSLog(@"Create Task Number %d", ++(*taskIdBlock));
//dispatch the task to the global queue.
dispatch_async(globalConcurrentQueue, ^{
runTask(*taskIdBlock,3);
});
Output:
Create Task Number 1
Running Task: 2
Create Task Number 2
Running Task: 2
Completed Task 2
Completed Task 2
Notice the 1st line in each piece of code. Primitive int to Object
NSinteger. I would have like to seen something like this:
dispatch_async(globalConcurrentQueue,runTask(*taskIdBlock,3));
However this does not compile. I can only see this getting more difficult
in the future so best to get a solid example down first. Thanks in
advance.

Rails ActiveRecord object not saving

Rails ActiveRecord object not saving

I have this table that stores serialized objects:
class CachedObject < ActiveRecord::Base
attr_accessible :key, :data
validates_uniqueness_of :key
end
The data column stores a serialized object indexed by key. Pretty simple.
I'm running this code to test:
key = "test"
obj = {"test" => "test"}
row = CachedObject.find_or_create_by_key key
row.data = obj.to_json
row.save
The object is getting created, but it's not saving back to the database.
No error messages. What am I doing wrong here?

Meteor integration with external services

Meteor integration with external services

This may seem like a very basic question. I need my small Meteor app to
integrate with an external service. Specifically ZeroRPC -
http://zerorpc.dotcloud.com/
Here's some example ZeroRPC client code.
Are there any potential issues with this and Is there a preferred way to
do this?
var zerorpc = require("zerorpc");
var client = new zerorpc.Client();
client.connect("tcp://127.0.0.1:4242");
client.invoke("hello", "RPC", function(error, res, more) {
console.log(res);
});

Case within Case statement

Case within Case statement

I have to get an instructor approval date from a table called section. If
that table doesn't have the date (null), then I have to get a date from
offering table, and even if that table doesn't have what I am looking for,
then from Term table.
How do I create a case statement to handle that?
so far here's what I have:
SELECT @dInstructApprDate = case when a.InstructorApprovalDate is null
then
select @dInstructApprDate = instructorapprovaldate from
SSS_OfferingAcademicPeriods where
SSS_OfferingRegPeriods.SSS_OfferingsID = @lSSS_OfferingsID
I am not sure why it doesn't like me using select statement within "THEN"
Any help would be appreciated.

Invalid attempt to read data when no data is present

Invalid attempt to read data when no data is present

I have a Sql Dbase in C#[built before i got to my present job,creator is
gone], and it was fine until last week. On the first page
clerk_search.aspx it searches SQL for people and posts back to a datagrid
thats fine. There is a ASP Image button thats clicked on and it goes
forward to the next page, to enter the reason the for the customers visit
with loaded fields about the customer that post back. For some persons the
next page populates, for others it does not. The SQL statement used checks
out fine in query analyzer, i dont understand. I dont think its the reader
because others are logged in fine, and the other customers are present in
the rows in SQL and can be queried just fine. All is posted below, I am
not savvy with coding, please assist.
`System.InvalidOperationException: Invalid attempt to read when no data
is present.
Line 40: SqlDataReader reader2 = cmd.ExecuteReader();
Line 41: reader2.Read();
Line 42: LblLName.Text = "" + reader2["LAST_NAME"];
Line 43: LblFName.Text = "" + reader2["FIRST_NAME"];
Source File: "....clerk_create.aspx.cs" Line: 42
[InvalidOperationException: Invalid attempt to read when no data is
present.]
System.Data.SqlClient.SqlDataReader.GetValue(Int32 i) +118
System.Data.SqlClient.SqlDataReader.get_Item(String name) +27
clerk_create.Page_Load(Object sender, EventArgs e)
in "c:......\clerk_create.aspx.cs:42
System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o,
Object t,
EventArgs e) +14
System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender,
EventArgs e)
+35
System.Web.UI.Control.OnLoad(EventArgs e) +99
System.Web.UI.Control.LoadRecursive() +50
System.Web.UI.Page.ProcessRequestMain(Boolean
includeStagesBeforeAsyncPoint, Boolean
includeStagesAfterAsyncPoint) +627
Here is the actual: ....clerk_create.aspx.cs
public partial class clerk_create : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Cookies["us"] == null)
{
Response.Write("Sorry, you do not have access to this page.
Please see
data systems.");
Response.End();
}
if (!IsPostBack)
{
using (SqlConnection connection = new SqlConnection
(WebConfigurationManager.ConnectionStrings["walkin2"].ConnectionString))
{
TextBox txtsct =
(TextBox)Page.PreviousPage.FindControl("Txtsct");
Txtsct.Text = txtsct.Text;
TextBox txt =
(TextBox)Page.PreviousPage.FindControl("Txtssn");
Txtssn.Text = "" + txt.Text;
connection.Open();
string strsql2 = "SELECT dbo.table_name.SSN,
dbo.table_name.LAST_NAME,
dbo.table_name.FIRST_NAME, dbo.table_name.MIDDLE_INITIAL,
dbo.table_name.COMPONENT_CODE, dbo.table_name.PRESENT_CODE
FROM
dbo.table_name INNER JOIN dbo.table_name ON
dbo.table_name.SSN = '" +
Txtssn.Text + "')";
SqlCommand cmd = new SqlCommand(strsql2, connection);
SqlDataReader reader2 = cmd.ExecuteReader();
reader2.Read();
LblLName.Text = "" + reader2["LAST_NAME"];
LblFName.Text = "" + reader2["FIRST_NAME"];
`

How to do an HTML select form where the selected option update a JSON value?

How to do an HTML select form where the selected option update a JSON value?

I currently have one HTML+JS webpage where I hard code the starting
condition (the West, North, East, South geographic coordinate of a
country) :
var WNES = { "W": 67.0, "N":37.5, "E": 99.0, "S": 5.0, "item":"India" };
I however just datamined data for ~180 countries, so I also have :
var WSEN_list = [
{"W":60.504050405040545;"S":29.306134923492337;"E":75.1575157515752;"N":38.47551472547255;"item":"Afghanistan"},
{"W":11.611161116111646;"S":-17.94743030603061;"E":24.068406840684105;"N":-4.453854347434742;"item":"Angola"},
{"W":19.279927992799315;"S":39.62168720072006;"E":21.00810081008106;"N":42.67814713471347;"item":"Albania"},
{...}
];
I want my end-user to pick a country using a html <select> element :
<form>
Select your country:
<select id="mySelect">
<option>Afghanistan</option>
<option>Albania</option>
<option>Angola</option>
</select>
</form>
then, to store the user's selected item value (by exemple "Angola"), and
state :
var WNES =
{"W":11.611161116111646;"S":-17.94743030603061;"E":24.068406840684105;"N":-4.453854347434742;"item":"Angola"};
How to do a such select button and system which update my WNES from the
WSEN_list ?

Can't get link_to_unless_current to work

Can't get link_to_unless_current to work

After someone pointed link_to_unless_current out to me, I would like to
apply it to my dashboard sidebar. However, I can't get it to work, so I'm
guessing I'm doing something wrong.
This is my current sidebar
.dashboard_bar
%ul
= link_to admin_dashboard_path do
%li.icon-dashboard
= link_to admin_cs_dashboard_path do
%li.icon-heart
= link_to admin_dashboard_path do
%li.icon-money
= link_to admin_dashboard_path do
%li.icon-group
= link_to admin_dashboard_path do
%li.icon-bug
= link_to admin_dashboard_path do
%li.icon-hdd
When I change link_to to link_to_unless_current, it just screws up my css
and the icons are no longer clickable.
Can someone enlighten me on how to fix it?

Tuesday, 10 September 2013

Access 2010 - How would you pass the returned result from an if statement to set field criteria that contains logical operators

Access 2010 - How would you pass the returned result from an if statement
to set field criteria that contains logical operators

Im looking to set field criteria with an if statement but the result of
the if statement will contain a logical opertor.
eg
If([Code]="PEN", "GENR", "GENR OR GENR-R")
The result is that for a given row the expression would set the criteria
to GENR if column Code = PEN and if Code <> PEN then the criteria would be
GENR OR GENR-R
Your help is greatly appreciated. thanks

Adding an signed integer beyond 0xFFFFFFFF

Adding an signed integer beyond 0xFFFFFFFF

#include <stdio.h>
void fun3(int a, int b, int c)
{
printf("%d \n", a+b+c );
}
void fun2 ( int x, int y)
{
fun3(0x33333333,0x30303030, 0x31313131);
printf("%d \n", x+y);
}
fun1 (int x)
{
fun2(0x22222222,0x20202020);
printf("%d \n", x);
}
main()
{
fun1(0x1111111);
}
I'm going through the above program for stack corruption. I am getting the
o/p for the above program with some undesired values. All I could
understand is if the added value is beyond 0xFFFFFFFF then the small
negative integer becomes the largest value say -1 becomes 0xFFFFFFFF. Any
insights on this

Is it possible to move pages from one Module to other Module

Is it possible to move pages from one Module to other Module

I have a fully developed WPF/PRISM Application. There are four modules in
it with separate regions for each of the four modules. There is a new
requirement as to move some of the pages from each of the modules to a
separate module. Now, I have created a separate module in the application.
But have not started moving the pages from one module to this new module.
Can someone tell me the challenges involved in this task? I am not sure of
this as this is my first task in PRISM Application.

Redraw jQuery Mobile button icons in iOS Safari

Redraw jQuery Mobile button icons in iOS Safari

I'm only having this problem in iOS Safari and not other webkit browsers
(such as Chrome). Occasionally, when I trigger a change on a .ui-radio or
.ui-checkbox input, the element does not get redrawn so you cannot tell
that your change has taken effect. Any other operation (scrolling,
clicking another button, or even touching the screen) will suddenly force
the redraw necessary to make the updated element appear. It seems like
jQuery mobile removes and adds these elements when changing how they look.
I've seen several explanations of what I believe is this problem as well
as possible solutions:
http://mir.aculo.us/2009/09/25/force-redraw-dom-technique-for-webkit-based-browsers/
http://mir.aculo.us/2009/01/11/little-javascript-hints-episode-3-force-redraw/
How can I force WebKit to redraw/repaint to propagate style changes?
My current solution is something like:
$(".actual-input").on("change", function () {
setTimeout(function () {
var elem = $(this).next("label").find(".ui-icon").get(0),
dsp = elem.style.display,
txt = document.createTextNode(' ');
elem.appendChild(txt);
elem.style.display = "none";
setTimeout(function () {
elem.style.display = dsp;
txt.parentNode.removeChild(txt);
}, 200);
}.bind(this), 200);
});
The initial setTimeout is because the updated element seems to get
appended after the change event completes, so I can't find another way to
capture the element I want to redraw. With the above I can visibly see the
element flicker (and if I remove display = dsp, the element will not
reappear), however there are still times where nothing appears to redraw
(even if I don't display the element again). There doesn't seem to be any
consistency about it either.

Wordpress "two contents" split up by border

Wordpress "two contents" split up by border

I'm programming a new website for a customer based on wordpress. I got 4
pages. In 2 pages I have to seperate the content by a border. Like this:
So on top I got the text by Wordpress editor in backend and on bottom I
got in this image a slideshow, but sometimes there is more text. And every
text on the website should be able to edit by the customer in wordpress so
he don't have to go to source code. But I don't have any idea how I should
go on. Have someone an idea or a hint how I can go on?
Thanks in advance
Cheers

Efficient table structure or indexing for searchable IP address ranges in SQL

Efficient table structure or indexing for searchable IP address ranges in SQL

I have raw data provided to me for a geolocation service, in the form of a
table of IP address ranges mapped to location data.
The addresses are provided as byte-packed integers (one dotted-quad per
byte), permitting easy storage and comparisons, so each row in this table
provides a range low address, a range high address, and some text location
fields. I don't have to/am not able to use CIDR.
The table is several million records.
I don't have strong SQL chops. The code I inherited simply does a sql call
like:
SELECT location FROM geodata WHERE lookup_address >= range_low AND
lookup_address =< range_high
The performance is terrible. My understanding is that this will simply do
a linear search for matching records. To get around this temporarily I
have thrown together a client cache into a tree map to bring this down to
log performance, but a) my memory usage is now hard to justify, and b)
detecting live database updates is a problem I don't really want to tackle
right now.
It seems like this problem must come up now and then in the SQL world for
addresses, telephone numbers, etc.. Is there a "standard" way to organize
and index ranges in a SQL table so that I can get at least log performance
out of a direct SQL query?

How to check host connection with internet connection

How to check host connection with internet connection

I want to full check connection to internet and a domain or host. I used a
method to check internet connection, but i can not add checking host
availability. My code is here;
public class InternetCheck{
public static boolean isInternetAvailable(Context context)
{
NetworkInfo info = (NetworkInfo) ((ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
if (info == null){
Constants.connectionProblem = "Check your internet connection";
return false;
}
else{
return true;
}
}
}
I want to add host or domain availability check inside of
isInternetAvailable() method. It must return false and set
Constant.connectionProblem = "Host is not available" . Because, i will
call that method on my main activity and if it returns false, i will show
a Toast which shows that Constants.connectionProblem .

Monday, 9 September 2013

Can't get bubble sort to work w/ comparing object properties

Can't get bubble sort to work w/ comparing object properties

For an array of books, the assignment is to get attributes of the objects
from the user, then sort based on their choice of author, title, or page
count. My bubble sort is working for the page count but not when the user
chooses author or title, so I'm guessing I'm missing something with
reference storage vs. value storage, maybe? Thanks!
import javax.swing.*;
import java.util.*;
public class LibraryBookSort {
public static void main(String[] args) {
LibraryBook[] books = new LibraryBook[5];
LibraryBook tempBook = new LibraryBook();
String enteredAuthor = "", enteredTitle = "";
String enteredPageCount;
String sortBy;
String displayString = "";
int parsedSortBy;
int parsedPageCount;
int booksLength = books.length;
// populate the array
for (int x = 0; x < booksLength; ++x)
books[x] = new LibraryBook();
// get property values from user
for (int x = 0; x < booksLength; ++x)
{
enteredTitle = JOptionPane.showInputDialog(null, "Enter book " +
(x + 1) + " of 5's title:");
books[x].setTitle(enteredTitle);
enteredAuthor = JOptionPane.showInputDialog(null, "Enter book " +
(x + 1) + " of 5's author:");
books[x].setAuthor(enteredAuthor);
enteredPageCount = JOptionPane.showInputDialog(null, "Enter book "
+ (x + 1) + " of 5's page count:");
parsedPageCount = Integer.parseInt(enteredPageCount);
books[x].setPageCount(parsedPageCount);
}
// sort by property values
sortBy = JOptionPane.showInputDialog("Choose option to sort by: (1)
title, (2) author, or (3) page count");
parsedSortBy = Integer.parseInt(sortBy);
while (parsedSortBy < 1 || parsedSortBy > 3)
{
sortBy = JOptionPane.showInputDialog("Invalid selection, please
choose option to sort by: (1) title, (2) author, or (3) page
count");
parsedSortBy = Integer.parseInt(sortBy);
}
if (parsedSortBy == 1)
{
for (int a = 0; a < booksLength - 1; ++a)
{
for (int b = 0; b < booksLength - 1; ++b)
{
if (books[b].getTitle().compareTo(books[b+1].getTitle()) > 1)
{
tempBook = books[b];
books[b] = books[b+1];
books[b+1] = tempBook;
}
}
}
}
else if (parsedSortBy == 2)
{
for (int a = 0; a < booksLength - 1; ++a)
{
for (int b = 0; b < booksLength - 1; ++b)
{
if (books[b].getAuthor().compareTo(books[b+1].getAuthor())
> 1)
{
tempBook = books[b];
books[b] = books[b+1];
books[b+1] = tempBook;
}
}
}
}
else
{
for (int a = 0; a < booksLength - 1; ++a)
{
for (int b = 0; b < booksLength - 1; ++b)
{
if (books[b].getPageCount() > books[b+1].getPageCount())
{
tempBook = books[b];
books[b] = books[b+1];
books[b+1] = tempBook;
}
}
}
}
for (int i = 0; i < booksLength; ++i)
{
displayString += (books[i].getTitle() + ", by " +
books[i].getAuthor() + ". " + books[i].getPageCount() + "
pages.\n");
}
JOptionPane.showMessageDialog(null, "Books sorted by your choice:\n\n"
+ displayString);
}
}