Thursday 3 October 2013

How to set ActionMode LayoutParams to make custom view match_parent?

How to set ActionMode LayoutParams to make custom view match_parent?

I'm trying to set a custom view into an ActionMode, but it doesn't match
ActionMode as parent. In comparison with the standard ActionBar, when you
are setting a custom view you can specifiy layout params, while is not
provided in ActionMode.
There´s any solution?
mode.setCustomView(mModeActionBarView);
getSupportActionBar().setCustomView(customActionBarView, new
ActionBar.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT));
Thanks a lot!

Wednesday 2 October 2013

Java super constructor execution sequence

Java super constructor execution sequence

I've been studying from the Java Certification Bates and Sierra book and
am stumped on chapter 2 constructor explanation:
public class Animal {
String name;
Animal(String name) {
super();
{System.out.println("Hello");} //I put this in myself
this.name = name;
}
Animal() {
this(makeRandomName());
}
static String makeRandomName() {
int x = (int) (Math.random() * 5);
String name = new String[] {"Fluffy", "Fido",
"Rover", "Spike",
"Gigi"}[x];
return name;
}
public static void main (String [] args) {
Animal a = new Animal();
System.out.println(a.name);
Animal b = new Animal("Zeus");
System.out.println(b.name);
}
}
The following is from the Bates and Sierra book:
"Notice that the makeRandomName() method is marked static! That's because
you cannot invoke an instance (in other words, nonstatic) method (or
access an instance variable) until after the super constructor has run.
And since the super constructor will be invoked from the constructor on
line 3, rather than from the one on line 7, line 8 can use only a static
method to generate the name."
I did an experiment and I inserted a super call in the overloaded
constructor and my results were:
Hello Rover Hello Zeus
Now from these results, it seems as though the overloaded constructor AND
the super constructor is executed before the static method because Hello
prints before Zeus and Rover. So, why is there a need for a static
variables?
What am I missing?
Thanks, Jane

How can I reuse a Dropdownlist in several views witn .NET MVC

How can I reuse a Dropdownlist in several views witn .NET MVC

Several views from my project have the same dropdownlist...
So, in the ViewModel from that view I have :
public IEnumerable<SelectListItem> FooDdl { get; set; }
And in the controller I have :
var MyVM = new MyVM() {
FooDdl = fooRepository.GetAll().ToSelectList(x => x.Id, x => x.Name)
}
So far so good... But I´m doing the same code in every view/controller
that have that ddl...
Is that the best way to do that?
Thanks

How to wire-up UISegmentedControl from a prototype cell?

How to wire-up UISegmentedControl from a prototype cell?

I have a UISegmentedControl defined in my storyboard within a prototype
cell. Trying to plug the control into an IBOutlet results in the Xcode
error "Couldn't compile connection". After some searching, I found this
error message is because IBOutlet can't be used with a prototype cell in
this way. Is there a way to access the UISegmentedControl* through the id
parameter of an IBAction wired up to the control?

vb.net back to back, identical lines: 1 works, 1 doesn't

vb.net back to back, identical lines: 1 works, 1 doesn't

I have these 2 lines of code:
MsgBox(tr.InnerText.Contains("Completed"))
MsgBox(tr.InnerText.Contains("removed"))
They appear right after eachother, in that order (tr is an htmlelement
defined earlier). The first line executes no problem, the second line
returns an object reference not set. What gives gais?

Tuesday 1 October 2013

Template function default parameter and type inference

Template function default parameter and type inference

C++
None of these template functions
template<typename T> void foo(T par = nullptr) {return;} //#1
template<typename T> void foo(T par = std::nullptr_t(nullptr)) {return;}
//#2
template<typename T> void foo(T par = int(0)) {return;} //#3
allow anything with the following zero-argument call to compile:
foo();
although calling foo with any value works (e.g. foo(2)).
nullptr has a specific type, which is std::nullptr_t, so I didn't think
the default parameter needed extra type qualification in #1. The type of
the default parameter is explicitly provided in #2 and #3, so I didn't
think there was any type ambiguity there.
What is wrong here? Is there a proper way to do default parameters with
template functions?

Design issue in C++

Design issue in C++

This is rather question on a design issue than a problem on c++. I'll try
to describe my thoughts in an abstract way:
I'm the "owner" of some service object A0, dynamically created by a
framework. To do my job I created dependent aggregated classes A1, A2, A3,
... to handle different specific requests.
Within A1, A2, A3... I typically use resources like a database connection,
a property tree etc..., which are available from the framework, which
calls A.
What is the best way, to make these resources "available" from A1...An ?
Typically I have setter-Methods like
a0->setFramework(myFramework);
a1->setFramework(a0->getFramework());
a2->setFramework(a0->getFramework());
a3->setFramework(a0->getFramework());
Then I use other dependent classes, to complete a specific request, e.g. a
ResponseWriterA for A, which needs also some of the mentioned services.
Therefore, I have to implement a setter
ResponseWriterInstanceA->setFramework(a1->getFramework())
and so on.
Although this works, I don't regard it as a good solution, since the same
set of resources is "propagated" through along the whole set of classes.
Moreover, I typically end up with all my subclasses depending somehow on
the whole framework, which makes it hard, to isolate classes ("each
include File is everywhere afterwards").
I would prefer a more centralized access to the set of resources, without
the need to pass data through and to keep the worker classes independent
of other nasty things. But I dont know, how to do that in a "proper"
way...
On the one hand I dont't want to use static (class) methods, but for all
other approaches, I need an object. How to get this instance, if it is not
passed as a dependent object to all of my worker-instances?
What is the typical "golden way" (maybe some kind of design pattern) to
solve such issues?
Many Thanks !

LAN not working on DELL 3360

LAN not working on DELL 3360

I have a dell Vostro 3360 and i have recently removed windows and
installed Ubuntu 12.04 I am able to use WiFi and Bluetooth but it does not
detect when any LAN cable is connected.
I tried unblocking everything using sudo rfkill unblock all but to no
avail. please help ASAP as i am a college student and i need LAN
connectivity

Monday 30 September 2013

What is the intuition behind the unit normal vector being the derivative of the unit tangent vector?

What is the intuition behind the unit normal vector being the derivative
of the unit tangent vector?

I've seen the math, but... It just doesn't make sense to me. How is the
slope going to point perpendicular to the vector that is clearly a
straight line not going in that direction?

Getting JMX working under Tomcat 7 with SSL and a self-signed cert

Getting JMX working under Tomcat 7 with SSL and a self-signed cert

I'm trying to get JMX working under Tomcat 7.0.23 with SSL. The servers
are located in AWS, which means all the hosts are NATed, and I need to use
JmxRemoteLifecycleListener to explicitly set the two ports used by JMX.
I've been doing a lot of reading on the subject but I just can't get all
the pieces working together properly.
I can get JMX working fine without SSL. I have downloaded the version of
catalina-jmx-remote.jar for my version of Tomcat and installed it in my
tomcat/lib directory. My server.xml contains:
<Listener className="org.apache.catalina.mbeans.JmxRemoteLifecycleListener"
rmiRegistryPortPlatform="1099" rmiServerPortPlatform="1098" />
When I launch Tomcat with the following settings I can connect with an
insecure session:
-Dcom.sun.management.jmxremote
-Dcom.sun.management.jmxremote.password.file=/path/to/jmxremote.password
-Dcom.sun.management.jmxremote.access.file=/path/to/jmxremote.access
-Djava.rmi.server.hostname=<public IP of server>
-Dcom.sun.management.jmxremote.ssl=false
However if I change these to the following then I'm unable to establish an
SSL connection:
-Dcom.sun.management.jmxremote
-Dcom.sun.management.jmxremote.password.file=/path/to/jmxremote.password
-Dcom.sun.management.jmxremote.access.file=/path/to/jmxremote.access
-Djava.rmi.server.hostname=<public IP of server>
-Dcom.sun.management.jmxremote.ssl=true
-Dcom.sun.management.jmxremote.ssl.need.client.auth=false
-Dcom.sun.management.jmxremote.authenticate=true
-Djavax.net.ssl.keyStore=/path/to/keystore.dat
-Djavax.net.ssl.keyStorePassword=<password>
-Djavax.net.ssl.trustStore=/path/to/truststore.dat
-Djavax.net.ssl.trustStorePassword=<password>
keystore.dat contains just a single certificate created via:
openssl x509 -outform der -in cert.pem -out cert.der
keytool -import -alias tomcat -keystore keystore.dat -file cert.der
-storepass <password>
truststore.dat contains a full copy of the java cacerts plus the CA cert
for my self-signed cert:
cp $JAVA_HOME/jre/lib/security/cacerts truststore.dat
keytool -storepasswd -storepass changeit -new <password> -keystore
truststore.dat
keytool -import -trustcacerts -file mycacert.pem -alias myalias -keystore
truststore.dat -storepass <password>
After launching Tomcat I've tried connecting via jconsole but it can't
establish a connection. I tried to verify SSL using openssl but it looks
like Tomcat isn't making use of the cert:
$ openssl s_client -connect <host>:1099
CONNECTED(00000003)
140735160957372:error:140790E5:SSL routines:SSL23_WRITE:ssl handshake
failure:s23_lib.c:177:
---
no peer certificate available
---
No client certificate CA names sent
---
SSL handshake has read 0 bytes and written 322 bytes
---
New, (NONE), Cipher is (NONE)
Secure Renegotiation IS NOT supported
Compression: NONE
Expansion: NONE
---
I've verified that my local keystore and truststore are set up properly by
exporting the keys and verifying the cert chain (combined.pem is all the
CA certs from truststore.dat and cert.pem is my cert from keystore.dat):
$ openssl verify -verbose -purpose sslserver -CAfile combined.pem cert.pem
cert.pem: OK
So now I'm at a complete loss. The cert and CA cert look correct.
Unencrypted JMX connections work. But I can't seem to get the connection
to use SSL. What am I missing here?
I don't know if this is just a red herring or not, but I don't see any way
to specify what cert in the keyStore is used by JMX. Some of what I read
implies that it just uses a cert with the alias "tomcat". Is that correct?

What does "plus colon" means in shell script expressions?

What does "plus colon" means in shell script expressions?

What does this mean:
if ${ac_cv_lib_lept_pixCreate+:} false; then :
$as_echo_n "(cached) " >&6
else
ac_check_lib_save_LIBS=$LIBS
Looks like ac_cv_lib_lept_pixCreate is some variable, so what does "+:" mean?
Where to learn complete syntax of curle brackets expressions? What is the
name of this syntax?

Merge two tables in SQL and only get row with highest number

Merge two tables in SQL and only get row with highest number

I have two user SQL tables with more or less the same data in it and I
want to merge the two tables and only take the user with the highest
MyLevel. Maybe it makes more sense if I show what I have and what I want.
Table One:
MyName, MyDescr, MyLevel, FromDB
John, "Hey 1", 100, DB1
Glen, "Hey 2, 100, DB1
Ive, "Hey 3, 90, DB1
Table Two:
MyName, MyDescr, MyLevel, FromDB
John, "Hey 4", 110, DB2
Glen, "Hey 5", 90, DB2
Ive, "Hey 6", 90, DB2
What I want to archieve (ignore the <--):
MyName, MyDescr, MyLevel, FromDB
John, "Hey 4", 110, DB2
Glen, "Hey 2, 100, DB1
Ive, "Hey 6", 90, DB2 <-- doesn't matter which one as it is the same level
Of course it is possible, but I am really in the dark regarding JOINs and
especially when needing to GROUP it or alike?

Sunday 29 September 2013

How can I turn a Regular String into a Keyword? [Python]

How can I turn a Regular String into a Keyword? [Python]

Recently, I have been programming in the language of Python. I've came
across the problem of trying to convert a string into a keyword.
Suppose I use a raw_input() phrase and turn that string into an object,
list, or dictionary.
For example, I can turn the string "Foo" into Foo and assign that name to
a python structure.
How would I do this?

Is the windows.h library in C++ complete enough for basic sound related functions?

Is the windows.h library in C++ complete enough for basic sound related
functions?

I will be working on a college project in which i need to use sound
functions. I might need to create sounds with combinations of amplitude ,
frequencies etc. Has the library got enough functions to deal with these?
Which other libraries should i consider? Please suggest those with easy
and good documentation available. :) Thanks

Generating variations of checksum functions to minimize collisions

Generating variations of checksum functions to minimize collisions

My goal is to efficiently perform an exhaustive diff of a directory tree.
Given a set of files F, I must compute the equivalence classes EQV = [F©û,
F©ü, F©ý... F&#8345;] such that f&#11388;, f&#8342; ¡ô EQV[i] iff
(f&#11388; is identical to f&#8342;) for all i, j, k.
My general approach is to start with just one big class containing all
initial files, EQV_0=[[f1,f2,...f_n]], and repeatedly split it into more
refined equivalence classes EQV©û, EQV©ü... EQV_{m-1}, based on some
heuristics, for example, file size, checksum value. After all m heuristics
have been applied (EQV_{m-1}), a pairwise diff of all the files within
each class in EQV_{m-1} must be made. Because this last step is quadratic
for each of the classes in EQV_{m-1}, ie
O(sum(n©÷ for n in map(len, EQV_{m-1})) )
and will probably be the bottleneck of my algorithm if each the m splits
are done in linear time, my goal is to make EQV_{m-1} as flat as possible.
I would like to have access to a variety of good hash functions that I can
apply to minimize collisions on EQV_{m-1}. My current idea is to use some
library provided checksum function, such as adler, and to generate
variations of it by simply applying it to different starting bytes within
the file. Another one is to first apply fast hash functions, such as
adler, and then more expensive ones such as md5 on only the classes which
are still too large.
Considering that I can compute all the hashes for a given file in just one
read of that file, how could I compute a variety of hashes that will help
me discriminate among non-identical files?
Alternatively, what is a good list of hash functions available in python
that aren't cryptographically secure?

NullPointException in Hive UDAF

NullPointException in Hive UDAF

all
I Write a hive UDAF, when add it to hive. It throws NullPointException
The code and entire task logs is pasted on github gist -->
https://gist.github.com/hellojinjie/6750572
Any idea why it throws NullPointException?
Or why it says :
stderr logs java.lang.reflect.InvocationTargetException Continuing ...
java.lang.IllegalArgumentException: Unbound variable:
GenericUDAFCdnBytesLoaded$GenericUDAFCdnBytesLoadedEvaluator0 Continuing
...
I am a beginner of hive..hehe

Saturday 28 September 2013

fgets doesn't wait for the keyboard input

fgets doesn't wait for the keyboard input

I want to read two strings from ther user's keyboard input, this is the
code I tried :
char nomFichier[50];
char emp[100];
char empEtNomFichier[150];
printf("\nDonner le nom du fichier : ");
fgets(nomFichier, sizeof nomFichier, stdin);
printf("\nDonner l'emplacement du fichier : ");
if(fgets(emp, sizeof emp, stdin)){
sprintf(empEtNomFichier, "%s/%s", emp, nomFichier);
printf(empEtNomFichier);
}else{
printf("\nLa longueur de l'emplacement est trop grande !!");
}
The problem is when I run this code, the program doesn't wait for the
keyboard input for the first fgets(), ad this is how the program looks :
Donner le nom du fichier :
Donner l'emplacement du fichier : /home/ee/Desktop
/home/ee/Desktop

IM Chat for Sellers and Buyers on ECommerce

IM Chat for Sellers and Buyers on ECommerce

I know my query can be invalid but I need to add the IM chat script to my
ecommerce website in which buyers and sellers will be able to chat with
eachother when anyone is available. Please check out the following URL and
script I found but this guy is charging for this script.
http://oxyfeatures.com/instant_messenger.php

Java Inheritance

Java Inheritance

I have a class A
public class A{
public void doWork(){
..............
.............
}
}
Now a public class B extends A
public class B extends A{
@override
public void doWork(){
............
............
}
}
Now Public class C create a object of B into it and pass it to a method of
class D
import xxx.xxx.B;
import xxx.xxx.D;
public class C{
B b= new B();
D d = new D();
d.method(b);
}
now class D takes a argument of type A into its method and operate on it.
public class D{
public void method(A a){
..........
..........
}
}
Actually It is allowed, but I cannot understand why it is allowed ?
method() in class D should take an object of type A. Please help me out ?

Finding second maximum in an array in most efficient way

Finding second maximum in an array in most efficient way

I am trying to find the second maximum in an array in the most efficient
way both in terms of space and time complexity, but I have two major
problems:
1. Time Complexity:
The naive or brute force approach will take two passes to find the
smallest element so O(n) complexity, If I sort the array then it would
take O(n2).
2. Space Complexity:
I can always use BST for O(log(n)) sorting but they will require
additional space for maintaining a tree, I can also create a heap and do
two deletes and I would get the second largest element but here also heap
is created and stored in memory.
What options do I have here?

Friday 27 September 2013

Move focus to next window conflict with eclipse on OSX

Move focus to next window conflict with eclipse on OSX

I'm trying to get eclipse (Kepler, but it shouldn't matter because all
versions I've used seem to have this problem) to play well with OSX and
the 'Move focus to next window' keybinding.
OSX has a keybinding for moving between windows within an application - by
default this is bound to CMD-`. I'd like to use this in eclipse for the
Next Editor/Previous Editor navigation to be consistent with switching
between documents in other OSX applications.
Here's the problem: If I have 'Move focus to next window' enabled in
System Preferences (System Preferences::Keyboard::Keyboard
Shortcuts::Keyboard & Text Input::Move focus to next window), then eclipse
doesn't seem to receive the key events for this - it sort of seems like
OSX is intercepting the events before eclipse gets them. If I disable
'Move focus to next window', then I can successfully bind CMD-to 'Next
Editor' in eclipse. But then none of my other OSX applications can use
CMD- which isn't really what I want.
An alternative, I thought, was to actually define a system-level keyboard
shortcut (System Preferences::Keyboard::Keyboard Shortcuts::Application
Shortcuts) for just eclipse - binding Cmd-to 'Next Editor'. That *kind of*
works, but not really. In that case I can still use Cmd- in other
applications, and I can use Cmd-` to bring up the document switch window
in Eclipse, but then like a lot of java apps, when the document switch
dialog window pops up most of the menu items in the system menu bar
disappear - including the 'Next Editor' entry. That seems to prevent OSX
from switching further down in the document stack in Eclipse. So basically
I can switch between the 2 most recent documents, but nothing else!
Can anyone think of a better solution? Maybe an edit to the eclipse source
that I can make to properly intercept Cmd-`?

Download torrents to S3 and serve as direct resumable downloads

Download torrents to S3 and serve as direct resumable downloads

Is it possible to download torrents to amazon s3 directly and then serve
them as resumable download links for a very limited verified crowd?

Generating Colors from int

Generating Colors from int

I need to create colors depending on 1 int value. For example
void setColor(int x){
red = 2*x;
blue = 5*X;
green = 1*x;
}
The problem is that i cant use random numbers because i want an id to
refer to 1 color(can be more, because i dont really need each color to be
unique)
Basicly i have an array 2d(up to 100 x 100 size), and each field has an id
numered in order from 1, and i would like to keep them a bit separated, so
i would like to make some colors depending on each field id. I dont need
an unique color for each field but i want nearest fields to be in
different colors.
any suggestions? thx
EDIT so i have array and each field has an ID
[1][2][3][4][5]..............
.............................
[1000][1001][10002]..........
and i wanted to make each cell refering to a color based on its ID, for
example ID1 = red ID2 = blue ID3= purple ID1000 = white and so on.

Databinding in C#

Databinding in C#

Can someone help me databind? I'm new to .net and c# and am following
tutorials that are only getting me half way there. The aspx is the
following:
<asp:Repeater ID="rptContent" runat="server">
<HeaderTemplate>
<table>
<thead>
<tr>
<th>T</th>
<th>L</th>
<th>S</th>
</tr>
</thead>
<tbody>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td><%# Eval("T") %></td>
<td><%# Eval("L")%></td>
<td><%# Eval("S")%></td>
</tr>
</ItemTemplate>
<FooterTemplate>
</tbody>
</table>
</FooterTemplate>
</asp:Repeater>
But on the back end I don't know how to actually bind the data. If there
is a tutorial someone can send me to follow for this part I'd appreciate
it or if you can explain that would be great.
public List<Sample> Results()
{
List<Sample> List = new List<Sample>();
myList.Add(new Sample { Title = "Title
1", Link = "/item.aspx?id=1", Summary = "summary
for Item 1" });
return List;
}
public class Content
{
public string T
{
get;
set;
}
public string L
{
get;
set;
}
public string S
{
get;
set;
}
}

Table display only 2 labels (out of 4) when use the search Bar

Table display only 2 labels (out of 4) when use the search Bar

I have a table with 4 labels which works fine. When I use the search bar,
which also works fine, the table displays only two labels:
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"airports"
ofType:@"json"];
NSString *JSONData = [[NSString alloc] initWithContentsOfFile:filePath
encoding:NSUTF8StringEncoding error:NULL];
NSArray *airports = [NSJSONSerialization JSONObjectWithData:[JSONData
dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
finalArray = [[NSArray alloc]init];
finalArray = airports;
}
-(void)filterContentForSearchText:(NSString *)searchText{
NSPredicate *resultPredicate = [NSPredicate
predicateWithFormat:@"SELF.airport_name contains[cd] %@", searchText];
self.searchResults = [finalArray
filteredArrayUsingPredicate:resultPredicate];
}
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller
shouldReloadTableForSearchString:(NSString *)searchString{
[self filterContentForSearchText:searchString];
return YES;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section
{
if (tableView == self.tableView) {
return [finalArray count];
}else{
return [searchResults count];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath: (NSIndexPath *)indexPath
{static NSString *simpleTableIdentifier = @"AirportCell";
AirportCell *cell = (AirportCell *)[tableView
dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"AirportCell"
owner:self options:nil];
cell = [nib objectAtIndex:0];
}
NSString *airportName = [[NSString alloc]init];
NSString *iataCode = [[NSString alloc]init];
NSString *icaoCode = [[NSString alloc]init];
NSString *countryAirport = [[NSString alloc]init];
if (tableView == self.tableView) {
airportName = [[finalArray objectAtIndex:indexPath.row]
objectForKey:@"airport_name"];
iataCode = [[finalArray objectAtIndex:indexPath.row]
objectForKey:@"iata_code"];
icaoCode = [[finalArray objectAtIndex:indexPath.row]
objectForKey:@"icao_code"];
countryAirport = [[finalArray objectAtIndex:indexPath.row]
objectForKey:@"country"];
cell.iataCodeLabel.text = iataCode;
cell.iataCodeLabel.font = [UIFont fontWithName:@"Verdana" size:13];
cell.icaoCodeLabel.text = icaoCode;
cell.icaoCodeLabel.font = [UIFont fontWithName:@"Verdana" size:13];
cell.airportNameLabel.text = airportName;
cell.airportNameLabel.font = [UIFont fontWithName:@"Verdana" size:13];
cell.countryLabel.text = countryAirport;
cell.countryLabel.font = [UIFont fontWithName:@"Verdana" size:13];
}else{
airportName = [[searchResults objectAtIndex:indexPath.row]
objectForKey:@"airport_name"];
iataCode = [[searchResults objectAtIndex:indexPath.row]
objectForKey:@"iata_code"];
icaoCode = [[searchResults objectAtIndex:indexPath.row]
objectForKey:@"icao_code"];
countryAirport = [[searchResults objectAtIndex:indexPath.row]
objectForKey:@"country"];
cell.iataCodeLabel.text = iataCode;
cell.iataCodeLabel.font = [UIFont fontWithName:@"Verdana" size:13];
cell.icaoCodeLabel.text = icaoCode;
cell.icaoCodeLabel.font = [UIFont fontWithName:@"Verdana" size:13];
cell.airportNameLabel.text = airportName;
cell.airportNameLabel.font = [UIFont fontWithName:@"Verdana" size:13];
cell.countryLabel.text = countryAirport;
cell.countryLabel.font = [UIFont fontWithName:@"Verdana" size:13];
}
return cell;
}

Submit record in 2 databases

Submit record in 2 databases

I have a form and I want to submit the form data in 2 databases. But the
problem is: both the databases are on different servers. I am new to mysql
so I don't know exactly how to do that. I am working in php. I am sharing
my code with you, its not working properly. so please check this out:
$con = mysql_connect('differenthost','user1','pass1');
mysql_select_db('dbname1',$con);
$path = "misc/classified/".$submiturl;
mysql_query("insert into tablename1
(title,description,status,parent_id,path) values
('$submiturl','$submiturl','active','68','$path')") or
die(mysql_error());
mysql_close($con);
mysql_connect('localhost','user2','pass2');
mysql_select_db('dbname2');
$check = mysql_query("select count(*) from tablename2 where userid
= '".$_SESSION['userid']."' and datecreated = '$datecreated'") or
die(mysql_error());
This error comes when I submit the form:
Warning: mysql_connect() [function.mysql-connect]: Unknown MySQL server
host 'differenthost' (25) in
/home/class/public_html/microworker/submiturl.php on line 11
Warning: mysql_select_db(): supplied argument is not a valid MySQL-Link
resource in /home/class/public_html/microworker/submiturl.php on line 12
Warning: mysql_query() [function.mysql-query]: Access denied for user
'user2'@'localhost' (using password: NO) in
/home/class/public_html/microworker/submiturl.php on line 16
Warning: mysql_query() [function.mysql-query]: A link to the server could
not be established in /home/class/public_html/microworker/submiturl.php on
line 16
Access denied for user 'user2'@'localhost' (using password: NO)
Please help me in that case, what is the right syntax?

Thursday 26 September 2013

Python tkinter exception handling using tkinter callwrapper

Python tkinter exception handling using tkinter callwrapper

I want to catch all the exceptions from tkinter application and dump them
in a text file. I am using tkinter callwrapper method for the same but it
doesn't seems to work.
In the belowcode NameError exception is there, but when I launch the
application by double clicking on the program, it just closes without
dumping/giving the error in tkmessagebox.
import Tkinter as tk
import tkMessageBox
class GUIExceptionHandler:
def __init__(self, func, subst, widget):
self.func = func
self.subst = subst
self.widget = widget
def __call__(self, *args):
try:
if self.subst:
args = apply(self.subst, args)
return apply(self.func, args)
except SystemExit, msg:
raise SystemExit, msg
except:
traceback.print_exc(file=open('stacktrace.log', 'w'))
tkMessageBox.showerror("TestApp", "Encountered an error.")
#root.quit()
class GUI:
def __init__(self):
self.root = None
self.__createMainWindow()
self.__GUImainloop()
def __closeApp(self):
if tkMessageBox.askyesno("Yes", "Do you really want to exit?"):
self.root.destroy()
def __createMainWindow(self):
self.root = tk.Tk()
self.root.withdraw()
tk.CallWrapper = GUIExceptionHandler
self.root.protocol("WM_DELETE_WINDOW",self.__closeApp)
errorcondition #NameSpaceError condition
def __GUImainloop(self):
self.root.mainloop()
def main():
gui = GUI()
if __name__ == '__main__':
main()
Can someone please suggest what is wrong in this code and how this can be
achieved?

Wednesday 25 September 2013

How do i input an array to a Map Reduce Job?

How do i input an array to a Map Reduce Job?

I have a service that is continuously retrieving some data .I am dumping
this data into an array, this data has to be further processed. Is it
possible to create a dynamic array that keeps getting updated by serivice,
and side by side i can execute the Map Reduce Job? Also how what class do
i use to simply take an array input(instead of a file) ? PS I'm new to
Hadoop/Map Reduce I'm coding in Java.

Thursday 19 September 2013

JOptionPane error on Eclipse

JOptionPane error on Eclipse

I am VERY new to Java (ie week 2 of AP Computer Science A). we have to use
JOptionPane to make message boxes to use with math operations. My code was
fine at school but I had to reformat it because I saved it on Facebook (no
other option). Now I get errors on all the JOptionPane lines saying
"Multiple markers at this line" and " Syntax error on tokens". How do I
fix that. here is the code (please only fix what I am asking, nothing
else, I know the code is probably weird)
import javax.swing.JOptionPane;
public class OptioPane {
public static void main(String[] args) {
}
String a = JOptionPane.showInputDialog("Enter an integer");
String b = JOptionPane.showInputDialog("Input another");
int x = Integer.parseInt(a);
int y = Integer.parseInt(b);
JOptionPane.showMessageDiaglog(null, "The numbers added together is "
+(x+y));
String c = JOptionPane.showInputDialog("Enter an integer");
String d = JOptionPane.showInputDialog("Input another");
int f = Integer.parseInt(c);
int g = Integer.parseInt(d);
JOptionPane.showMessageDialog(null, "The second number subtracted from
the first number is " +(f-g));
String s = JOptionPane.showInputDialog("Enter an integer");
String r = JOptionPane.showInputDialog("Input another");
int w = Integer.parseInt(a);
int q = Integer.parseInt(b);
JOptionPane.showMessageDialog(null, "The numbers multiplied together
is " +(w*q));
String k = JOptionPane.showInputDialog("Enter an integer");
String j = JOptionPane.showInputDialog("Input another");
int n = Integer.parseInt(a);
int m = Integer.parseInt(b);
JOptionPane.showMessageDialog(null, "The first number divided by the
second number is " +(n/m));
String fir = JOptionPane.showInputDialog("Enter an integer");
String tir = JOptionPane.showInputDialog("Input another");
int ah = Integer.parseInt(a);
int bh = Integer.parseInt(b);
JOptionPane.showMessageDialog(null, "The first number modulated by the
second number is " +(ah*bh));
}

Copy files exclude one folder

Copy files exclude one folder

Basically I want to copy everything within a folder excluding one folder,
which happens to be where logs are stored for my program. (I know I could
just store logs elsewhere, but I have my reasons). So far I have:
private void btnCopyFiles_Click(object sender, EventArgs e)
{
try
{
//Copy all the files
foreach (string newPath in Directory.GetFiles(@"\\xxx\yyy",
"*.*",
SearchOption.AllDirectories)
.Where(p => p != Logging.fullLoggingPath))
File.Copy(newPath, newPath.Replace(@"\\xxx\yyy", @"C:\bbb"));
using (StreamWriter w = File.AppendText(Logging.fullLoggingPath))
{
Logging.Log("All necessary files copied to C:\\bbb", w);
}
}
catch
{
using (StreamWriter w = File.AppendText(Logging.fullLoggingPath))
{
Logging.Log("Error copying files, make sure you have
permissions to access the drive and write to the folder.",
w);
}
}
}
How can I modify this to exclude one specific folder within \\xxx\yyy

Dependency relationship in UML

Dependency relationship in UML

in UML there is Dependency relationship,However I read the following quote:
dependency indicates a semantic relationship between two or more elements
what does semantic relationship mean in the above sentence?

Read an input file one line at a time to pass as input to grep

Read an input file one line at a time to pass as input to grep

My requirement is to read a file and then run a grep command on the read
line one at a time for all the lines in the file.
Filtering the required file which matches a pattern
find . -name *.ini -exec grep -w HTC {} \; -print | grep ini > input.files
cat input.files
./PLATFORM/android/build/integration/android/suites/android_Prefs_Devices_Comms_Suite/ini/android_0019.ini
./PLATFORM/android/build/integration/android/suites/android_Prefs_Devices_Comms_Suite/ini/android_0150.ini
./PLATFORM/android/build/integration/android/suites/android_Prefs_Devices_Comms_Suite/ini/android_0616_1.ini
./PLATFORM/android/build/integration/android/suites/android_SI_Query_Suite/ini/android_0547_4.ini
./PLATFORM/android/build/integration/android/suites/android_SI_Query_Suite/ini/android_0578.ini
./PLATFORM/android/build/integration/android/suites/android_PDL_Suite/ini/android_5203_1.ini
./PLATFORM/android/build/integration/android/suites/android_System_Maintenance_Suite/ini/android_0579_2.ini
Any idea how to read one line at a time from input.files and execute a
grep command on that ?
cat input.files -exec grep -w HTC_One {} \;

How can I center buttons inside a DIV so there's the same space right and left of the four buttons?

How can I center buttons inside a DIV so there's the same space right and
left of the four buttons?

I have the following HTML:
<div class="clearfix">
<div>
<button>a</button>
<button>a</button>
<button>a</button>
<button>a</button>
</div>
</div>
The buttons appear to the left and leave a space on the right of my outer
DIV. How can I make it so the buttons center themselves leaving a space on
the left and the right that is equal?

Making a SKScene's background transparent not working... is this a bug?

Making a SKScene's background transparent not working... is this a bug?

Is there a way to make a SKScene's background transparent and present that
scene over another one seeing thru the transparency.
The idea is to have the background of the presented scene like this:
self.backgroundColor = [SKColor colorWithRed:0.0f green:0.0f blue:0.0f
alpha:0.5f];
what would allow to see the scene behind darken. But doing this is not
working. Background is presented completely opaque.
Is there a way to do that?

how to set return type of a stored procedure according to a specific table

how to set return type of a stored procedure according to a specific table

I had made a dynamic stored procedure like this
CREATE PROCEDURE [dbo].[MyProcedure]
@pSelect nvarchar(max)
AS
BEGIN
SET NOCOUNT ON;
DECLARE @SQL nvarchar(max)
SET @SQL = 'select ' + @pSelect + ' from tabel1';
EXEC (@SQL)
END
And on updating my entitydatamodel the in context.cs the above stored
procedure is in the form of
virtual int MyProcedure(string pSelect)
{
var pSelectParameter = pSelect != null ?
new ObjectParameter("pSelect", pSelect) :
new ObjectParameter("pSelect", typeof(string));
return
((IObjectContextAdapter)this).ObjectContext.ExecuteFunction("MyProcedure",
pSelectParameter);
}
on calling the stored procedure from c# code
var result = myDataModel.MyProcedure("Select * From table1").tolist();
the above code is showing error because MyProcedure is returning a integer
return type
so how could i set the return type of the stored procedure according to
tje select query I am passing to it

HOW DO I MODIFY MY STORED PROCEDURE SO THAT ITS RETURN TYPE IS OF ANY
SPECIFIC TABLE TYPE

how to use my own form structure in agile toolkit?

how to use my own form structure in agile toolkit?

in agile toolkit we only can change the form style but is it possible to
change the form body and it's structure? I want to change HTML...
something like this:
$form->htmlsource();

Wednesday 18 September 2013

Xcode open specific view with push notifications in storyboard

Xcode open specific view with push notifications in storyboard

In my codes, I wrote it in this way
DetailView *vc = (DetailView *)[mainStoryboard
instantiateViewControllerWithIdentifier:@"DetailVC"];
self.window.rootViewController = vc;
It only show that view but I don't see the navigational bar and tab bar.
What is the right way to open a specific view (inside tabbarcontroller)
within storyboard when the app receive remote notifications automatically?

php_network_getaddresses: getaddrinfo failed

php_network_getaddresses: getaddrinfo failed

I am getting this error ( http://prntscr.com/1s51gw ) in all the functions
of Image GD library.
<?
$im = @imagecreatefromjpeg("src/bg.jpg") or die('Cannot Initialize new GD
image stream');
function copyImage1($im, $dp1_name, $x1, $y1){
$dp1 = imagecreatefromjpeg($dp1_name);
list($w1, $h1) = getimagesize($dp1_name);
imagecopy($im, $dp1, 35, 130, 0, 0, $w1, $h1);
}
function copyImage2($im, $dp2_name, $x2, $y2){
$dp2 = imagecreatefromjpeg($dp2_name);
list($w2, $h2) = getimagesize($dp2_name);
imagecopy($im, $dp2, 618, 125, 0, 0, $w2, $h2);
}
$box = imagettfbbox(30, 0, "src/font.ttf", $user_name);
imagettftext($im, 23, 0, 53, 348, imagecolorallocate($im, 73, 184, 227),
"src/font.ttf", "hello");
imagettftext($im, 23, 0, 628, 348, imagecolorallocate($im, 73, 184, 227),
"src/font.ttf", "byr");
copyImage1($im,
"http://graph.facebook.com/100001504336690/picture?width=153&height=143",
10, 10);
copyImage2($im,
"http://graph.facebook.com/100001504336690/picture?width=138&height=158",
10, 10);
$file_name = "dump/" . rand(1000, 9999) . "-id-" . rand(1000, 9999) . ".jpg";
imagejpeg($im, $file_name, 80);
imagedestroy($im);
?>
The files are available at there place,
CODE WAS WORKING FINE BUT NOW IT'S NOT WORKING. i don't know y it is not
working now..
Any help will be appreciated. please hell to solve the issue.

Printing arrays in C

Printing arrays in C

Alright I'm just now picking up c so I'm pretty terrible since I'm comin
from basic python. The question is I'm trying to print the number in an
array, I'm using a for loop but its not coming out the right way. #include
#include int main() { int array[]={0,1,2,3,4}; int i; for (i=0;i<5;i++); {
printf("%d",array[i]); } printf("\n"); }
My out put is 134513952
I have no clue why it's printing this

"Test Tools" area not showing up in VS Options

"Test Tools" area not showing up in VS Options

In Visual Studio, when I go to the "Tools" menu and select "Options..."
the window does not show an area for "Test Tools." I know it's supposed to
be there because I have been seeing other posts saying I need to change a
setting in there (references: this and this).

I'm running VS 2013 RC Ultimate. I know 2013 is beta, but it's not showing
up in my VS 2012 either.

How does this javascript callback function work?

How does this javascript callback function work?

can anyone explain line by line, I don't get how this call back and
prototype works especially the function(callback) in js file
user.getUsers(function (theUsers) {
$('#users-table-wrapper').html(user.getATable(theUsers));
});
this part in HTML
Js File
function User () {
}
User.prototype.getUsers = function (callback) {
$.ajax({
url: 'posting.php',
data: {
request:'get-users'
},
type:'post',
dataType: 'json',
success: function(users){
// callback(users);
if (callback) { callback(users); }
}
});
}
Here is my index.html
theUser is not declared but still works. when I type funcion (theUser) as
far as I know theUser is a argument or a parameter. It has to be declared
somewhere.
It seems it is neither of them.... how does this work?
<!DOCTYPE html>
<html>
<head>
<title>Users</title>
<script
src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="User.js"></script>
<script>
$(function () {
var user = new User();
user.getUsers(function (theUsers) {
$('#users-table-wrapper').html(user.getATable(theUsers));
});
});
</script>
</head>
<body>
<div class='main-wrapper'>
<h3>Users</h3>
<div id="users-table-wrapper">
</div>
</div>
</body>
</html>

REVERSE COINCHANGE:if one has 2 bills and the other has 6 bills, and the value is equal, of which values bills are these?

REVERSE COINCHANGE:if one has 2 bills and the other has 6 bills, and the
value is equal, of which values bills are these?

i am looking for an approach how to solve the following problem:
Player A has an amount of, say coins like {0,0,10,10,10,10,50,200}
Player B another amount, say {0,0,50,50,100,200}
I see how much Coins they exchange, say A gives 2 and B gives 4
The game ends even,
so both stacks have the same value
from this i can derive:
A gave | B gave
0,100 | 0,0,50,50
0,50 <--- no way !
50,50 | 0,0,50,50
100,200 | 0,50,50,200
100,200 | 0,0,100,200
and so on and so on
what are this class of algorithm is called which gives me all possible
sets for Value(A)=Value(B) or ab
my sets will contain up to 20-30 elements, so i am looking for a good
approach but my only ideas so far where brute force permutations
Thanks for any discussion/help
dj

Developing Twain ActiveX control in C++ MFC

Developing Twain ActiveX control in C++ MFC

I am developing TWAIN ActiveX control in MFC. I followed the steps that
comes in the specification of twain as follows: 1 - Load Twain 2 - Open
Data Source Manager 3 - Select Data Source 4 - Open Data Source 5 -
Negotiate capabilities with the data source 6 - Request the Acquisition of
Data from the Source 7 - Recognize that the Data Transfer is Ready
after I enable the Data Source User interface via MSG_ENABLEDS I enter a
while loop like this:
while(GetMessage(&msg, NULL, 0, 0))
{
// Forward the message to twain proc MSG_PROCESSEVENT
// then check the return message from twain
// to know if the transfer ready or not
}
I made this loop cause in MFC ActiveX control there is no Message Loop
the problem is when I close the application I got an exception
I need to know the best way to forward messages to twain via MSG_PROCESSEVENT
is it via SetWindowsHookEx , message loop, or worker thread thanks

Mod_rewrite for multiple ids and areas

Mod_rewrite for multiple ids and areas

forgive me but I'm pretty useless with mod_rewrite and could with a hand
with something.
Basically, right now I have my page reflecting the page ID in a way
similar to this:
http://www.url.com?id=X
Where X = whatever the ID is.
However, I need it to look like this:
http://www.url.com/AreaName
Where AreaName is a local area (e.g. /London).
I have about 30 areas, all with different names and of course IDs, how
would I do a rewrite that reflects all /AreaName's to their relevant IDs?
Thanks in advance!

What is Objective-C's msgSendSuper behavior?

What is Objective-C's msgSendSuper behavior?

Checking the Apple's open source message dispatching code, I notice that
the call to super uses a struct holding the instance and a class it should
find the superclass method from.
Does this mean that the compiler must explicitly change messages to super
by adding the class it is called from?
And given some class tree where C extends B extends A, and all of them
implement a method m which calls [super m], and we create D extending A at
runtime, grabbing C's implementation of m to use as D's; will [d m] in
fact call all of D, B, and A's methods m instead of just D and A's?

Tuesday 17 September 2013

Is IN and NOT IN mutually Exclusive?

Is IN and NOT IN mutually Exclusive?

I have two tables
Table 1
Column1
_______
1
2
3
4
5
6
Table 2
Column 1
________
4
NULL //This NULL value added after answering the question, to show the
real problem
5
6
7
8
9
This is an example case. When I tried,
SELECT column1 FROM Table1 WHERE column1 IN (SELECT column1 FROM Table2)
I got 4,5,6
WHEN
SELECT column1 FROM Table1 WHERE column1 NOT IN (SELECT column1 FROM Table2)
I didn't get 1,2,3 instead NULL.
In real case the column1 of table1 is nvarchar(max) and column1 of table2
is varchar(50). However, I tried casting both into varchar(50).

What are test cases in scheme and how do I use them?

What are test cases in scheme and how do I use them?

I'm a complete beginner at scheme, and want to know what test cases are,
or even do. For example, if I wanted to write a test case for the negative
root quadratic function I already coded and tested, how would I do it?
(define (quadnegative a b c)
(* (/ (+ (sqrt (-(square b) (* 4 a c))) b) 2 a) -1))
;Value: quadnegative
(quadnegative 1 3 -4)
;Value: -4
Thank you in advance.

Is it possible to stop twython streaming at certain point of time?

Is it possible to stop twython streaming at certain point of time?

I have the codes for twython streaming and it is working.
def read_cred(file): in_handle = open(file,'r')
cred = {}
for ln in in_handle:
data = ln.strip('\r\n').split('=')
if len(data) > 1:
key = data[0].strip(' ').lower()
value = data[1].strip(' ')
cred[key] = value
else:
print "error in parsing credentials file"
return cred
cred = read_cred(sys.argv[1])
class MyStreamer(TwythonStreamer): def on_success(self, data): act(data)
def on_error(self, status_code, data):
print status_code, data
stream = MyStreamer(cred['consumer_key'], cred['consumer_secret'],
cred['access_token_key'], cred['access_token_secret'])
keywords = sys.argv[2]
stream.statuses.filter(track=keywords)
However, I want to create a UI in django framework which consist of a
'start' and a 'stop' button. What should I do to stop the twython
streaming when I clicked on the button 'stop' ? Can give me some simple
examples pls?

jqGrid uses js with onSelectRow property, please how to select a row and get the asp.net page the id?

jqGrid uses js with onSelectRow property, please how to select a row and
get the asp.net page the id?

I have jqgrid that uses only js script and default.aspx page which display
the grid, IO need badly please as I'm able to view the grid but when I
click on a row on the grid it does identify the id (which I want) but I
cannot retrieve it on the back code of the page (Default.aspx.cs) using:
if (Request.QueryString["cmd"] == "select") it is detected and run the
grid but adding if (Request.QueryString["cmd"] == "delete") it is always
null, there is must be something wrong with the request. Can anybody help
please on this issue? I'll be very appreciated. Tried setting:
jQuery('#htmlTable5').jqGrid('setGridParam', { url:
'Default.aspx?cmd=select&que=1&id=' + id, mytype: 'POST', datatype:
'json'});
But it does not work (I see it inside diagnosing tool like firebug is
exist as que 1 but on page_load it is always null no matter what statement
I use.

Turn specific error into a failure in ruby Test::Unit

Turn specific error into a failure in ruby Test::Unit

I would like a way to take an error generated within a specific test
method inside a Test::Unit::TestCase and turn it into a failure with a
more friendly generic message. I keep thinking this should be possible
with some inheritance but I can't quite get my head around it.
class CalenderTest001 < Test::Unit::TestCase
def testZoneCal001
Fixture.reset
$driver = Selenium::WebDriver.for :firefox
$driver.get "http://myTestSite.com/"
$driver.find_element(:id, "IDthrowsAnError").click
end
end
The effect I would like is to have the entire thing wrapped in a begin
rescue end block with the rescue block looking something like this.
rescue Selenium::WebDriver::Error::NoSuchElementError => e
#mark this test as a failure not an error

C# .NET equivalent to JAVA Apache commons

C# .NET equivalent to JAVA Apache commons

Well, I am sure you are going to write off this question BUT all the
answers I have gotten are old and no one actually gave an answer, I am
reviving this again. is there a .Net framework equivalent to Java Apache
commons? I'll appreciate any good answer.

Sunday 15 September 2013

C# user defined struct conversion as function's default parameter

C# user defined struct conversion as function's default parameter

public struct MQL4Int
{
public int csInt;
public MQL4Int(int i)
{
csInt = i;
}
public static implicit operator MQL4Int(int value)
{
return new MQL4Int(value);
}
}
int MyFunc(MyInt i = 0)
{
return -1;
}
I want to implement a wrapper struct MyInt (simplified here) to accept int
as default value (I know this is weird and unnatural, I just need it to
comply other language format), but I meet error when I code like above,
the error is at 'int MyFunc(MyInt i = 0)' where VS2012 said
"a value of type 'int' cannot be used as a default parameter because there
are no standard conversions to Type MyInt"
As I know, int and double also defined as struct in C#. So I have tried
follows:
int MyFunc(double i = (int)0)
{
return -1;
}
it passed! Therefore I think type conversion is allowed in default parameter.
So my questions are:
Why can not use implicit type conversion for MyInt as default para?
What does the standard conversions mean in VS error message, is it diff
from implicit conversion defined in MyInt?
Thanks for all

Get All XML ChildNodes with Specific Type

Get All XML ChildNodes with Specific Type

Given the following code:
XmlDocument doc = new XmlDocument();
doc.Load(filename);
XmlElement root = doc.DocumentElement;
What is the most efficient way to get all the child nodes of root that are
of type "item". There can be more than one such item type. But most items
are of other types.
I know I can do this:
root["item"];
But that only returns a single element. How can I do the same thing but
return all elements of that type?
Thanks!

jQuery click on image does nothing

jQuery click on image does nothing

I am trying to get some jQuery code to execute when an image is clicked,
my problem is that it will only execute if I click just off the image. I
figure my problem is that I have all images being put inside a div named
photo with fixed width and heights. The images are constrained to fit
inside the div without distorting the image from its original constraints.
The image will not fill the div so when I click just outside of the image
I am clicking on the div not the image. How am I able to change my code
below so that it will only execute if an image inside the photo div is
clicked? I am new to jQuery so please forgive my question if it is a
rather simple fix.
$("body").click(function(event) {
var $target = $(event.target).attr('class');
var $idOfPhoto = event.target.id;
if ($target == "photo") {
$('#lightBox').lightbox_me({
centered:true,
onLoad:function() {
$('#lightBox').empty();
$('#lightBox').prepend('<img src="/Victoria/images/photoGallery/'
+ $idOfPhoto + '" />');
}
});
}
});
Here is the code in its entirety:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Victoria Mendiola</title>
<link rel="stylesheet" href="css/style.css">
<script
src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<link type="text/css" href="css/jquery.jscrollpane.css"
rel="stylesheet" media="all" />
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript"
src="css/jquery.mousewheel.js"></script>
<script type="text/javascript"
src="css/jquery.jscrollpane.min.js"></script>
<script src="/resources/library/jquery.lightbox_me.js"></script>
<script src="/resources/library/jquery.browser.js"></script>
<script src="jquery.cycle.all.js"></script>
</head>
<body>
<div id="lightBox">
</div>
<div class="container">
<div class="logo">
<img class="victoriaLogo" src="images/Victoria-logo.png" />
</div>
<div class="navigation">
<a class="navText" href="index.php">Home</a>
<a class="navText" href="gallery.php">Gallery</a>
<a class="navText" href="#about">About</a>
<a class="navText" href="contact.php">Contact</a>
</div>
<script>
$(function()
{
$('.galleryContainer').jScrollPane();
});
</script>
<div class="galleryContainer">
<?php
require 'DB.php';
try{
$stmt ='SELECT * FROM victoria';
foreach ($conn->query($stmt) as $row)
{
echo ('<div class="photo" id="' . $row['name'] . '">
<img src="images/photoGallery/thumbnails/' . $row['name'] . '" />
</div> </a>');
}
} catch (PDOException $e){
echo 'Connection failed: ' . $e->getMessage();
}
?>
</div>
<script>
$("body").click(function(event) {
var $target = $(event.target).attr('class');
var $idOfPhoto = event.target.id;
if ($target == "photo") {
$('#lightBox').lightbox_me({
centered:true,
onLoad:function() {
$('#lightBox').empty();
$('#lightBox').prepend('<img
src="/Victoria/images/photoGallery/' + $idOfPhoto + '"
/>');
}
});
}
});
</script>
</div>
</body>
</html>

C++ read the whole file in buffer

C++ read the whole file in buffer

What is a good approach to read the whole file content in a buffer for
C++? While in plain C I could use fopen(), fseek(), fread() function
combination and read the whole file to a buffer, is it still a good idea
to use the same for C++? If yes, then how could I use RAII approach while
opening, allocating memory for buffer, reading and reading file content to
buffer. Should I create some wrapper class for buffer which, deallocates
memory, allocated for buffer, in it's destructor, and the same wrapper for
file handling?

Rails making new cron jobs based on user input

Rails making new cron jobs based on user input

In my application, I want to invoke an action every two weeks based on
when the user triggered an action. I guess what's confusing is why there
doesn't seem to be a straight forward way of doing this.
Ideally, the repeated job would be set in the model, not some other file.
For example, the whenever gem has these instructions:
Getting started
$ cd /apps/my-great-project
$ wheneverize .
This will create initial config/schedule.rb file for you.
But I don't want to put my schedules in there. I want the schedule to be
in my model. The schedule isn't being set by me, it's being set by my
users.
Is there any straightforward way of implementing this? I've been stumped
on this for weeks.

Can I have multiple lists in a Django generic.ListView?

Can I have multiple lists in a Django generic.ListView?

As a Django beginner I'm working on the the tutorial provided by django
docs at https://docs.djangoproject.com/en/1.5/intro/tutorial04/
In it they demonstrate a list of multiple polls that are listed using a
query by publication date. Could I add another list to be also used in the
template to be used as well. Example Displaying a list of latest polls by
date and another by alphabetical order on the same page.
class IndexView(generic.ListView):
template_name = 'polls/index.html'
context_object_name = 'latest_poll_list'
def get_queryset(self):
"""Return the last five published polls."""
return Poll.objects.order_by('-pub_date')[:5]

Calculating from inputboxes, with error message for letter input

Calculating from inputboxes, with error message for letter input

I've been struggelig with an embarrassing and annoying little problem in
visual basic (I'm, as you probbably see, a beginner). The problem is the
error message system for when letters are entered instead of numbers. I
get "can't convert from integer to string.
Any help on this would be most appreciated.
Here is my code:
Dim number1, number2 As Integer
Dim sum As String
number1 = InputBox("first value:")
number2 = InputBox("second value:")
sum = number1 + number2
If IsNumeric(sum) Then
MsgBox("The sum of the numbers " & number1 & " and " & number2 & "
is: " & sum)
ElseIf Not IsNumeric(sum) Then
MsgBox("You may only type numbers into the fields!, trie again")
End If
In advance, thank you :)!

Saturday 14 September 2013

How do I stop some form of text wrapping happening between divs?

How do I stop some form of text wrapping happening between divs?


When I change the font and the size I get some weird wrapping as shown in
the second picture below. Not sure how to stop this and why its happening?
I've pasted the HTML and CSS code below thats being used.
<div class="wrap">
<div id="block1">
<p><img src="img/cheese1.jpg" alt="Cheese Picture" id="intro_pic" ></p>
<h2 id="intro">
The best selection of cheese I've ever seen! Cannot wait for our
next order!
</h2>
</div>
</div>
<div class="wrap">
<div id="block2">
<h2 id="intro2">
The best selection of cheese I've ever seen! Cannot wait for our
next order!
</h2>
<p><img src="img/cheese1.jpg" alt="Cheese Picture" id="intro_pic2" ></p>
</div>
.wrap {
margin: 0 auto;
max-width: 58%;
-webkit-columns: 100px 2;
box-sizing: border-box;
margin: 50px auto;
padding: 40px;
width: 78%;
border: 1px solid rgba(87,104,115, .9);
border-radius: 12px;
background: rgba(255,255,255,.9);
}
#intro {
padding: 1.3em 0 1.3em 0;
text-align: left;
float: right;
font-size: 3em;
line-height: 1.5;
letter-spacing: -1px;
color: #2B9BD4;
margin: 1.35em 0 .8em 0;
overflow: hidden;
}
#intro2 {
padding: 1.3em 0 1.3em 0;
text-align: right;
float: right;
font-size: 3em;
line-height: 1.5;
letter-spacing: -1px;
color: #2B9BD4;
margin: 1.35em 0 .8em 0;
overflow: hidden;
}
#intro_pic {
text-align: left;
float: right;
}
#intro_pic2 {
text-align: right;
float: left;
}

How to put a picture as transparent background in html or css for android app

How to put a picture as transparent background in html or css for android app

okay, so my friend gave me an html and javascript application for android.
i want to edit it a little bet and make another application. what i want
to do is add a transparent background but keep the buttons functioning and
everything, i know this might sound like i am asking a lot but i have no
idea what i am doing. so can someone give me the CSS or HTML code for a
transparent background picture. i am no good at programming and this is
the first anything i ever edit, so take it easy with me :).

Object Required error when I clearly have an object

Object Required error when I clearly have an object

Have searched and have come up short on any solutions to this. I am
relatively new to VB for the record. The variable minDate here is declared
in the module outside of the procedure. I have tried declaring it inside
the procedure, using set, let, and passing the argument as a range
variable. Nothing.
Sub SocialTimeSinceFirstComment() ' ' SocialTimeSinceFirstComment Macro '
Range("A11").Select ActiveCell.FormulaR1C1 = "=MIN(SocialTransform!C[4])"
minDate =
Application.WorksheetFunction.Min(Workbook.SocialTransform!.Range("c4").End(xlDown))

error: request for member ... which is of non-class type

error: request for member ... which is of non-class type

I realize the error is coming from using vectors in a custom class, but I
have been struggling how to fix them. How do I call vector methods when
its part of the class object? I'm just learning c++ so bare with me if
there are some basic mistakes. Thanks for any help!
These are the errors I am getting:
Word.cpp: In member function 'void Word::addPosition(int)':
Word.cpp:20: error: request for member 'push_back' in
'((Word*)this)->Word::positions', which is of non-class type
'std::vector<int, std::allocator<int> >*'
Word.cpp: In member function 'int Word::getPosition(int)':
Word.cpp:26: error: request for member 'size' in
'((Word*)this)->Word::positions', which is of non-class type
'std::vector<int, std::allocator<int> >*'
Word.cpp:27: error: request for member 'size' in
'((Word*)this)->Word::positions', which is of non-class type
'std::vector<int, std::allocator<int> >*'
Word.cpp:29: error: cannot convert 'std::vector<int, std::allocator<int>
>' to 'int' in return
Header
#pragma once
#include <string>
#include <vector>
class Word {
public:
Word();
~Word();
void setWord(std::string);
void addPosition(int);
std::string getWord();
int getPosition(int);
private:
std::string word;
std::vector<int> *positions;
};
Implementation
#include "Word.h"
#include <string>
#include <vector>
Word::Word() {
this->word = "";
this->positions = new std::vector<int>(5);
}
void Word::setWord(std::string s) {
this->word = s;
}
void Word::addPosition(int i) {
this->positions.push_back(i);
}
std::string Word::getWord() {
return this->word;
}
int Word::getPosition(int i) {
if (i < this->positions.size() && i > 0) {
for (int j = 0; j < this->positions.size(); i++) {
if (i == j) {
return positions[j];
}
}
}
return -1;
}

UITextField and NSURL URLWithString

UITextField and NSURL URLWithString

I have built a translate application in ios. The application uses the
Yandex translation api. I followed this tutorial:
http://www.raywenderlich.com/5492/working-with-json-in-ios-5 My
ViewController.m looks like this (I took out my api key):
#define kBgQueue
dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) //1
#define TranslateText [NSURL URLWithString:
@"https://translate.yandex.net/api/v1.5/tr.json/translate?key=apikey&lang=en-es&text=To+be,+or+not+to+be%3F"]
//2
#import "ViewController.h"
@end
@interface NSDictionary(JSONCategories)
+(NSDictionary*)dictionaryWithContentsOfJSONURLString:(NSString*)urlAddress;
-(NSData*)toJSON;
@end
@implementation NSDictionary(JSONCategories)
+(NSDictionary*)dictionaryWithContentsOfJSONURLString:(NSString*)urlAddress
{
NSData* data = [NSData dataWithContentsOfURL: [NSURL URLWithString:
urlAddress] ];
__autoreleasing NSError* error = nil;
id result = [NSJSONSerialization JSONObjectWithData:data
options:kNilOptions error:&error];
if (error != nil) return nil;
return result;
}
-(NSData*)toJSON
{
NSError* error = nil;
id result = [NSJSONSerialization dataWithJSONObject:self
options:kNilOptions error:&error];
if (error != nil) return nil;
return result;
}
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
dispatch_async(kBgQueue, ^{
NSData* data = [NSData dataWithContentsOfURL: TranslateText];
[self performSelectorOnMainThread:@selector(fetchedData:)
withObject:data waitUntilDone:YES];
});
}
- (void)fetchedData:(NSData *)responseData {
//parse out the json data
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData //1
options:kNilOptions
error:&error];
NSArray* TranslatedText = [json objectForKey:@"text"]; //2
NSLog(@"Text that was translated: %@", TranslatedText); //3
// 1) Get the latest loan
//NSDictionary* ttext = [TranslatedText objectAtIndex:0];
NSString* ttext = [TranslatedText objectAtIndex:0];
// 3) Set the label appropriately
humanReadble.text = [NSString stringWithFormat:@"%@",
//[ttext objectForKey:@"name"],
ttext];
}
@end`
I want to add a text field into the interface so that a user can type in
their own text to be translated, and I have put in a text field, and
connected it to ViewController.h, as IBOutlet UITextField *textfield;
I am not sure how to implement the button, but when I change the NSURL
URLWithString section in my ViewController .m file to
#define TranslateText [NSURL URLWithString:
@"https://translate.yandex.net/api/v1.5/tr.json/translate?apikeyes&text=To+be,+or+not+to+be%3F":[textfield.text]],
I get the error No Known class method for selector 'URLWithString::'. How
do I properly implement the text field and button?

How can i generate device specific unique number in Rhomobile

How can i generate device specific unique number in Rhomobile

I need to send a unique number per device to server to trace the
application install and create its specific device number.
When i use to generate the unique number by some logic, and make it to
store in the local db, but on uninstalling and again installing the
application, the generated number is different. So i'm not able to get the
data for that device been used previously.
Do we have some way to make/generate this unique number ?

How to regain the cached object in android for a music app

How to regain the cached object in android for a music app

Well this question of mine doesnt relate to any code especially, but what
I wanted to ask is that How do I achieve something like
1: Play the music on my application.
2: Then press the home key on the device, whilst the music is been played.
3: Then again long press the home key n regain access to the object that
was playing the file, which is a common user expectation, but what my
player does is the 4th step.
4: Whilst continuing to play the previous file, it launches a whole new
interface of the player , wherein the seekbar is at 0 the play button is
in the idle mode. Hence leads to confusion.
5: N if I touch the play button the player starts playing another file
from the start along with the previous one, so now I have 2 files played
by my player
How do I avoid this?
Is singleton that is necessary to be applied here? Plz guide me in some
manner.

Notify click action on button in webView

Notify click action on button in webView

Windows store App - hi I have webView in my xaml page. This webview show
page on some http adress. In loaded page is easy formular for login and I
need when user press login button notify in my app. Is there any options?
html part: <input type="submit" value="Login me" id="login">
I find something like this :
webView1.Document.GetElementById("").InvokeMember("click"); but its not in
RT/W8

Friday 13 September 2013

sending message to multiple users using php and mysql

sending message to multiple users using php and mysql

I need help. I'm trying to send a message to multiple users or you might
call recipients. So far the code below works to send a message to one
recipients only. I want to use a regular form where the usernames name can
be separated by a comma and than a message or messages can be sent to all
the users while being stored in a mysql database. Its a database based
email system and not a send to a different e-mail address system.
I have gotten commas to separate the usernames inside the username field
using jquery but than i get stuck after that.
<?php
include('connector.php');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11 /DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>How To Use jQuery Lightbox With A Database</title>
</head>
<body>
<div>You may click the images below.</div>
<div id="gallery"> <!-- id to detect images for lightbox -->
<?php
// if something was posted, start the process...
if(isset($_POST['submit']))
{
// define the posted file into variables
$message=$_POST['message'];
$title=$_POST['title'];
$recip=$_POST['recip'];
$username = $_SESSION['username'];
$id = $_SESSION['id'];
$who=$_POST['who'];
$what=$_POST['what'];
//We check if the recipient exists
$dn1 = mysql_fetch_array(mysql_query('select count(id) as
recip, id as recipid, (select count(*) from pm) as npm
from header where username="'.$recip.'"'));
if($dn1['recip']==1)
echo 'recip exists';
else
{
//Otherwise, we say the recipient does not exists
$error = 'The recipient does not exists.';
}
//We send the message
;
include_once('connector.php');
// the query that will add this to the database
mysql_query('insert into pm (id, id2, title,
name, size, type, content, who, what,
user1, user2, message, timestamp, user1read,
user2read)values("'.$id.'", "1",
"'.$title.'", "'.$name.'", "'.$size.'",
"'.$type.'", "'.$content.'", "'.$who.'",
"'.$what.'", "'.$_SESSION['id'].'",
"'.$dn1['recipid'].'", "'.$message.'",
"'.time().'", "yes", "no")')
or die (mysql_error());
mysql_close();
echo "Successfully uploaded your picture to database also!";
}
?>
<a href="dddd.php">List of my Personal messages</a></div>
<div class="content">
<form action="importantnotice.php" method="post"
enctype="multipart/form-data" name="data"> <h1>New Personal
Message</h1>
Please fill the following form to send a Personal message.<br />
<label for="recip">Recipient<span
class="small">(Username)</span></label> <input type="text"
value="<?php echo htmlentities($orecip, ENT_QUOTES, 'UTF-8'); ?>"
id="recip" name="recip" /><br />
Upload your file to the database...
<tr>
<td><div align="right">when:</div></td>
<td><input name="message" type="text" id="message" size="80"
maxlength="80" /> </td>
</tr>
<tr>
<td><div align="right">when:</div></td>
<td><input name="who" type="text" id="who" size="80" maxlength="80"
/></td>
</tr>
<tr>
<td><div align="right">where:</div></td>
<td><input name="what" type="text" id="what" size="80"
maxlength="80" /></td>
</tr>
<tr>
<input name="submit" type="submit" id="submit" value="submit">
</tr>
</form>
</div>
<div class="foot"><a href="list_pm.php">Go to my Personal
messages</a> - <a
href="http://www.add.com/">Webestools</a></div>
</body>
</html>

Image gallery that order by size and dimention like Flickr

Image gallery that order by size and dimention like Flickr

I have no idea how to make image gallery that can automatically order the
position, dimention and size. When Pulling those image from database.
THis is the site inspiration (also flickr)
http://bodybuildersupclose.tumblr.com/archive
I know my question is quite short. I don´t even know what kind of
technique to use. Is that jQuery or just Css ?

Changing a variable's value based on another variable in PHP

Changing a variable's value based on another variable in PHP

first let me say I am trying very hard to learn PHP, and the more I learn,
the more I want to learn and use the language. I'm primarily an HTML5/CSS3
coder, and am trying to make my sites more efficient by using PHP.
Here is my current dilemma. I am attempting to utilize variables to change
values as required. At the beginning of each page file I have declared the
page name, called my functions file and called head and header functions:
<?php
$page = 'contact';
include('functions.php');
head();
header();
?>
A slight variation of this is included in all page files. Things are good.
Now, in my functions.php I have a variable for the meta title value, i.e.
$title, and have declared it as a global.
How do I change the value of this variable based on the value of the $page
variable? Here is what I have added to the functions.php file, but I am
quite sure it is incorrect, as it is not working:
$title = array {
if ($page == 'contact') {
echo 'Contact Us';
}
}
I'm not just looking for the right code, but an explanation if possible.
Thanks in advance for your assistance.

unable to print write supplier name in a single gremlin query

unable to print write supplier name in a single gremlin query

unable to solve. I know the problem is behind first inV() while creating
vertex. while executing the first row in the result is ok. but when
iterating to next outE().inV..it again fetch node CP which should be ANZ
this time. buyer side is working fine.
gremlin>
g.v(0).outE().inV.as('supplier').bothE('Sell','Buy').as('tx_amount').inV.as('buyer').select{it.name}{it.amount}{it.name}.sort{it[2]}
==> [supplier:CP, tx_amount:100, buyer:ANZ]
==> [supplier:CP, tx_amount:200, buyer:CP]

Why am i getting this php error?

Why am i getting this php error?

$username = $_POST['username'];
$ppassword = $_POST['password'];
$password = md5("$ppassword");
This is the code and i am getting this error
Notice: Undefined index: username in C:\wamp\www\php\compare.php on line 14
Call Stack
# Time Memory Function Location
1 0.0004 250440 {main}( ) ..\lognet.php:0
2 0.0007 260000 include( 'C:\wamp\www\php\compare.php' )
..\lognet.php:3
Notice: Undefined index: password in C:\wamp\www\php\compare.php on line 15
Call Stack
# Time Memory Function Location
1 0.0004 250440 {main}( ) ..\lognet.php:0
2 0.0007 260000 include( 'C:\wamp\www\php\compare.php' )
..\lognet.php:3

Error when returning a pointer

Error when returning a pointer

I am practicing coding binary search tree in C and I ran into an error.
#include <stdio.h>
#include <stdlib.h>
/*struct Node*/
typedef struct Node{
int data;
struct Node* left;
struct Node* right;
}Node;
/*Forward declaration*/
Node *createNode(int data);
int main(int argc, char** argv) {
Node *root;
root = createNode(3); //ERROR
}
Node* createNode(int data){
Node* newNode = (Node*)malloc(sizeof(Node));
if(newNode==NULL){
fprintf(stderr,"Failed to allocate node\n");
exit(1);
}
newNode->data = data;
newNode->left = NULL;
newNode->right= NULL;
return newNode; //ERROR OCCURS HERE
}
I get a failed run when I try to run this. The error occurs during the
return newNode. I am not sure why the point is not returning.
I am using netbeans and this is what it says

Thursday 12 September 2013

Solve error javax.mail.AuthenticationFailedException

Solve error javax.mail.AuthenticationFailedException

I'm not familiar with this function to send mail in java.I'm getting an
error while sending email to reset password. Hope you can give me a help.
Thanks in advance.
Rgds, Fatin
Below is code in SendMail :
public synchronized static boolean sendMailAdvance(String emailTo, String
subject, String body)
{
String host = AppConfigManager.getProperty("SENDER-EMAIL-SMTP-ADDRESS");
String userName = AppConfigManager.getProperty("SENDER-EMAIL-SMTP-USERNAME");
String password = AppConfigManager.getProperty("SENDER-EMAIL-SMTP-PASSWORD");
String port = AppConfigManager.getProperty("SENDER-EMAIL-SMTP-PORT");
String starttls = AppConfigManager.getProperty("SENDER-EMAIL-SMTP-STARTTLS");
String socketFactoryClass =
AppConfigManager.getProperty("SENDER-EMAIL-SMTP-SOCKET-CLASS");
String fallback =
AppConfigManager.getProperty("SENDER-EMAIL-SMTP-ALLOW-FALLBACK");
try
{
java.util.Properties props = null;
props = System.getProperties();
props.put("mail.smtp.user", userName);
props.put("mail.smtp.host", host);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.debug", "true");
if(!"".equals(port))
{
props.put("mail.smtp.port", port);
props.put("mail.smtp.socketFactory.port", port);
}
if(!"".equals(starttls))
props.put("mail.smtp.starttls.enable",starttls);
if(!"".equals(socketFactoryClass))
props.put("mail.smtp.socketFactory.class",socketFactoryClass);
if(!"".equals(fallback))
props.put("mail.smtp.socketFactory.fallback", fallback);
Session session = Session.getDefaultInstance(props, null);
session.setDebug(true);
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(userName));
msg.setSubject(subject);
msg.setText(body, "ISO-8859-1");
msg.setSentDate(new Date());
msg.setHeader("content-Type",
"text/html;charset=\"ISO-8859-1\"");
msg.addRecipient(Message.RecipientType.TO, new
InternetAddress(emailTo));
msg.saveChanges();
Transport transport = session.getTransport("smtp");
transport.connect(host, userName, password);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
return true;
}
catch (Exception mex)
{
mex.printStackTrace();
return false;
}
}
In my showlog error throws :
DEBUG: setDebug: JavaMail version 1.4.1ea-SNAPSHOT
DEBUG: getProvider() returning
javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun
Microsystems, Inc]
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: trying to connect to host "smtp.gmail.com", port 465, isSSL
false 220 mx.google.com ESMTP m4sm5929870pbg.38 - gsmtp
DEBUG SMTP: connected to host "smtp.gmail.com", port: 465
EHLO fatin
250-mx.google.com at your service, [175.139.198.14]
250-SIZE 35882577
250-8BITMIME
250-AUTH LOGIN PLAIN XOAUTH XOAUTH2 PLAIN-CLIENTTOKEN
250-ENHANCEDSTATUSCODES
250 CHUNKING
DEBUG SMTP: Found extension "SIZE", arg "35882577"
DEBUG SMTP: Found extension "8BITMIME", arg ""
DEBUG SMTP: Found extension "AUTH", arg "LOGIN PLAIN XOAUTH XOAUTH2
PLAIN-CLIENTTOKEN"
DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""
DEBUG SMTP: Found extension "CHUNKING", arg ""
DEBUG SMTP: Attempt to authenticate
AUTH LOGIN
334 VXNlcm5hbWU6
YWNjb3VudEBibG9vbWluZy5jb20ubXk=
334 UGFzc3dvcmQ6
Ymxvb21pbmc=
535-5.7.8 Username and Password not accepted. Learn more at
535 5.7.8 http://support.google.com/mail/bin/answer.py?answer=14257
m4sm5929870pbg.38 - gsmtp
[STDOUT] javax.mail.AuthenticationFailedException
[STDOUT] at javax.mail.Service.connect(Service.java:319)
[STDOUT] at javax.mail.Service.connect(Service.java:169)
[STDOUT] at com.vlee.util.mail.SendMail.sendMailAdvance(SendMail.java:283)
[STDOUT] at
com.vlee.servlet.ecommerce.DoMemberLogin.fnSendPwd(DoMemberLogin.java:251)
[STDOUT] at
com.vlee.servlet.ecommerce.DoMemberLogin.doPost(DoMemberLogin.java:72)

How do "const", "&", and "&&" affect overloading of a parameterless function?

How do "const", "&", and "&&" affect overloading of a parameterless function?

Consider a class defined as below:
struct A
{
void f();
void f() const;
void f() &;
void f() const &;
void f() &&;
void f() const &&;
};
What are the differences between:
1) void A::f(); and void A::f() &;
2) void A::f() const; and void A::f() const &;
3) void A::f() &&; and void A::f() const &&;

Select column in query based on other table

Select column in query based on other table

I have a table called A where records contains some column name of table B.
table A Id, columnName
1 col1 2 col2 3 col3
table B ID, col1, col2, col3, col4, col5
I want to select columns of B based on the value of table A. Example
Select col1, col2, col3 from B

Programming Project Ideas for web based bioinformatics projects

Programming Project Ideas for web based bioinformatics projects

I am looking for project ideas for some bioinformatics projects that
incorporate web technologies. Basically i am looking to create a website
that can be useful in bioinformatics domain as well. Although this is a
very generic question, but I have done a lot of research in this regard
and my stumbling block is that either i am not able to find resources
related to bioinformatics or I am unable to understand the practical
usefulness of some of these projects. Any suggestions will be highly
appreciated. Also, please let me know if you are aware of any web-based
bioinformatics projects that are already working so that I can get an idea
on what the users expect from a website. I am newbie in bioinformatics, so
my expertise is at beginner level and I am interested in something that
can be completed in 2 months timeframe. I can work with Java, JavaScript,
HTML, CSS, PSP, Databases and Python.

What does "response too long" means in MongoDB Java driver?

What does "response too long" means in MongoDB Java driver?

Sometimes I get this exception from MongoDB Java driver 2.10.1:
java.lang.IllegalArgumentException: response too long: 1912733750
at com.mongodb.Response.<init>(Response.java:47)
at com.mongodb.DBPort.go(DBPort.java:124)
at com.mongodb.DBPort.call(DBPort.java:74)
at com.mongodb.DBTCPConnector.innerCall(DBTCPConnector.java:286)
at com.mongodb.DBTCPConnector.call(DBTCPConnector.java:257)
at com.mongodb.DBApiLayer$MyCollection.__find(DBApiLayer.java:310)
at com.mongodb.DBApiLayer$MyCollection.__find(DBApiLayer.java:295)
at com.mongodb.DBCursor._check(DBCursor.java:368)
at com.mongodb.DBCursor._hasNext(DBCursor.java:459)
at com.mongodb.DBCursor.hasNext(DBCursor.java:484)
Obviously, my response is not that long. Actually it's rather small, there
are just 1000 items in the collection, 100-500 bytes each. Why this may
happen?

Using Deface to prepopulate Billing Address

Using Deface to prepopulate Billing Address

I am trying to populate my billing address with prepopulated values. I
have written a deface as :
Deface::Override.new(:virtual_path => 'spree/address/_form',
:name => 'prepopulate_billing_address',
:set_attributes =>
'p#order_bill_address_attributes_phone',
:attributes => {:value => "122344"}
)
and the content belongs to app/overrides/autofill_billing_address.rb
I am trying to replace this view Spree form view
with the above deface but the deface logs say
Deface: 'prepopulate_billing_address' matched 0 times with
'p#order_bill_address_attributes_phone'
The id from the spree instance running is
order_bill_address_attributes_phone and is wrapped in <p>. Any idea?
Thanks for the help!

Hide a JFrame and run an other class in the background?

Hide a JFrame and run an other class in the background?

Is it possible to hide my JFrame window and start an main method from
another class in an action like this?
Here the code of the action:
private AbstractAction start = new AbstractAction("start") {
@Override
public void actionPerformed(ActionEvent arg0) {
}
};

php preg_match mathematical expresion

php preg_match mathematical expresion

I wanna make a check before php eval(string), so I wonder how should i
check if string is correct mathematical expression?
Need:
preg_match for 0123456789 + - * / ( )
and should start with ( or number
It shouldnt accept incorrect math expression like (1+1)+)
edit: I've tryed both
^([-+/*]\d+(\.\d+)?)*^
and
/[^0-9\+\-\*\/\(\)\.]/
but these doesnt catch incorrect math.

C++ QT Creator Sleep/Pause

C++ QT Creator Sleep/Pause

How do I "Sleep/Pause" inside Qt Creator.
I want the UI to remain responsive while the code is sleeping.
while(Tablet.IsConnected() == false){
LogText("[Prep] Tablet not turned back on... Retrying...");
//Sleep for three seconds here
}
LogText("[Prep] Tablet Detected!");
ELI5 - I`m new to QT.

Setting webview to occupy remaining place in the layout

Setting webview to occupy remaining place in the layout

I'm designing android layout as following image
Is there any way to set my webview to occupy remaining place in the layout.
code I have tried:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/linearLayout1"
android:layout_width="750dp"
android:layout_height="800dp"
android:orientation="vertical" >
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="45dp"
android:layout_marginTop="60dp"
android:orientation="horizontal" >
<!-- for image-->
<WebView
android:id="@+id/imageView1"
android:layout_width="260dp"
android:layout_height="310dp"
android:layout_marginTop="30dp" />
<!-- for text-->
<TextView
android:id="@+id/pricetext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="skjnfksjngk"
android:textColor="#5E327D"
android:textSize="30dp" />
</RelativeLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/webback" >
<!-- for webview>
<WebView
android:id="@+id/webview"
android:layout_width="500dp"
android:layout_height="150dp"
android:layout_marginLeft="45dp"
android:layout_marginTop="20dp"
android:layout_weight="2.74"
android:scrollbars="vertical" />
</LinearLayout>
</LinearLayout>
Pls help any body to achieve above design.Thank You.

Dealing with zero's in a moving average

Dealing with zero's in a moving average

EDIT
My original post was not the best explination, so I have rewritten it.
So what I'm trying to do is calculate the moving average on an array of
data. Each average is taken over, for example, the 24 values. However, I
have two conditions that need to be changed in my current function.
Take an average over 24 values that ARE NOT zero as zero is considered as
bad data, so I want 24 'good' values for the average.
If there are five consecutive zeros, I do not want to take the average and
simply say the average is zero.
I need to Here is my current function for this, but it needs updating to
encompass these changes.
def averaged_rel_track(navg, rel_values, nb):
'''function to average the relative track values for each blade. This is
dependant on the number values specified by the user to average over in a
rolling average'''
avg_rel_track=[]
for blade in range(0,int(nb)):
av_values=[]
rel_blade=rel_values[:,int(blade)]
for rev in range(0,len(rel_blade)):
section=rel_blade[rev-int(navg)+1:rev+1]
print section
if np.any(section==0):
av_value=0
else:
av_value=np.sum(section)/int(navg)
print av_value
av_values.append(av_value)
avg_rel_track.append(av_values)
avg_rel_track=np.array(avg_rel_track)
return avg_rel_track.transpose()
At the moment there is alot of checking involved.
Is there a function where you can select X number of values that are not
zero/none? Currently what I'm attempting to do works like this:
Select a section of data than is N values long
x= number of zeros/nan's in the data
Extend section by x values
But this doesn't work as then I need to check that the new section does
not contain zeros and it would detect the original zeros. I could check
the extension for zeros, repeating the process, but this seems like a very
long winded way to do this.
I know of scipy.stats.nanmean that will ignore the none values when
averaging the data.
If anyone could help that would be great, but the main question I would
like advice on is:
Is there a function that will select N values that are not zero or one?