Thursday, 3 October 2013

Delay before switching windows

Delay before switching windows

I'm working on a game which runs on Windows and can be run in a standalone
mode and in browser using Kalydo Player. Sometimes (80% of time), when I
try to switch window by clicking on another tab in windows bar or another
tab in browser, switching happens after 3-4 seconds delay.
I would provide additional information, but I don't even now what may
cause such a problem. Any thoughts?

Wednesday, 2 October 2013

All images including background disappears

All images including background disappears

I have two links and ReWrite rules for them. And the rules do change the
links. But all the images including the background disappears.
This code
#/viewgallery.php?cname=Colorado-Fall to /photos/Colorado-Fall RewriteCond
%{THE_REQUEST} ^[A-Z]{3,}\s/+viewgallery\.php\?cname=([^&\s]+) RewriteRule
^ /photos/%1/? [L,R=301] RewriteRule ^photos/([^/]+)/?$
/viewgallery.php?cname=$1 [L,NC,QSA]
changes
http://www.xyz.com/viewgallery.php?cname=Colorado-Fall
to
http://www.xyz.com/photos/Colorado-Fall/
Then this
# /viewgallery.php?cname=Colorado-Fall&pcaption=Poked to
/photos/Colorado-Fall/Poked.jpg
RewriteCond %{THE_REQUEST}
^[A-Z]{3,}\s/+viewgallery\.php\?cname=([^&]+)&pcaption=([^&\s]+)
RewriteRule ^ /photos/%1/%2/? [R=301,L]
RewriteRule ^photos/([^/]+)/([^.]+)/$
/viewgallery.php?cname=$1&pcaption=$2 [L,NC,NE]
changes the link
http://www.xyz.com/viewgallery.php?cname=Colorado-Fall&pcaption=Facing-Colors
to
http://www.xyz.com/photos/Colorado-Fall/Light-On-Fall-Colors/
What am I doing wrong here? I am using absolute paths in my PHP code.Like
these..
"<a
href=/viewgallery.php?cname=$cname&pcaption=".$caption_array[$next]."><img
src=/photos/assets/left.png border=0 ></a>";

mergesorting array not working with large arrays

mergesorting array not working with large arrays

could someone tell me why my code can't sort arrays of large sizes,
basically anything larger than size 3. I've been debugging for a while but
can't seem to find the problem, any help is appreciated. Thanks alot.
import java.util.*;
import java.io.*;
// No need to change anything in this class
class MergeSortQuestion {
// merges sorted subarrays A[start...firstThird],
A[firstThird+1,secondThird], and A[secondThird+1,stop]
public static void mergeThreeWay(int A[], int start, int firstThird,
int secondThird, int stop)
{
int indexLeft = start; //index for first third half
of array A
int indexMiddle = firstThird+1; //index for the middle element
of A
int indexRight = secondThird+1; //index for the right half of A
int [] temp = new int [A.length]; //create a new temporary array
of same type and size of array A
int tempIndex = start; //index for the temporary
array
if (tempIndex <= stop) {
//The following is valid if all 3 subdivisions of the array are
not used up
while ((indexLeft <= firstThird) && (indexMiddle <=
secondThird) && (indexRight <=stop))
{
if ((A[indexLeft] <= A[indexMiddle]) && (A[indexLeft] <=
A[indexRight]))
{
temp[tempIndex] = A[indexLeft]; //select the left element
indexLeft++;
}
else if ((A[indexMiddle] <= A[indexLeft]) &&
(A[indexMiddle] <= A[indexRight]))
{
temp[tempIndex] = A[indexMiddle]; //select the middle
element
indexMiddle++;
}
else if ((A[indexRight] <= A[indexLeft]) && (A[indexRight]
<= A[indexMiddle]))
{
temp[tempIndex] = A[indexRight]; //select the right
element
indexRight++;
}
tempIndex++;
}
//Executes when the last 3rd of the array has been used up
while ((indexLeft <= firstThird) && (indexMiddle
<=secondThird) && (indexRight > stop))
{
if (A[indexLeft]<= A[indexMiddle])
{
temp[tempIndex] = A[indexLeft];
indexLeft++;
}
else if (A[indexLeft] >= A[indexMiddle])
{
temp[tempIndex] = A[indexMiddle];
indexMiddle++;
}
tempIndex++;
}
//Executes when the middle half of the array has been used up
while ((indexLeft <= firstThird) && (indexMiddle >
secondThird) && (indexRight <= stop))
{
if (A[indexLeft]<= A[indexRight])
{
temp[tempIndex] = A[indexLeft];
indexLeft++;
}
else if (A[indexLeft] >= A[indexRight])
{
temp[tempIndex] = A[indexRight];
indexRight++;
}
tempIndex++;
}
//Executes when the first half of the array has been used up
while ((indexLeft > firstThird) && (indexMiddle <=
secondThird) && (indexRight <= stop))
{
if (A[indexMiddle] <= A[indexRight])
{
temp[tempIndex] = A[indexMiddle];
indexMiddle++;
}
else if (A[indexMiddle] >= A[indexRight])
{
temp[tempIndex] = A[indexRight];
indexRight++;
}
tempIndex++;
}
//Executes in the case where both the left and middle sections
are used up
while ((indexLeft > firstThird) && (indexMiddle > secondThird)
&& (indexRight <= stop))
{
temp[tempIndex]=A[indexRight];
indexRight++;
tempIndex++;
}
//Executes in the case where both the left and last sections
are used up
while ((indexLeft > firstThird) && (indexMiddle <=
secondThird) && (indexRight > stop))
{
temp[tempIndex]=A[indexMiddle];
indexMiddle++;
tempIndex++;
}
//Executes in the case where both the middle and last sections
are used up
while ((indexLeft <= firstThird) && (indexMiddle >
secondThird) && (indexRight > stop))
{
temp[tempIndex]=A[indexLeft];
indexLeft++;
tempIndex++;
}
}
//Now, we copy the temporary array back into array A
for (int i=0; i<A.length; i++) {
A[i]=temp[i];
}
}
// sorts A[start...stop]
public static void mergeSortThreeWay(int A[], int start, int stop) {
if (((stop-start)==1)&&(A[1]<A[0])){
int temp = A[1];
A[1] = A[0];
A[0] = temp;
}
if (start < stop) {
int firstThird = ((stop-start)/3 + start);
int secondThird = 2*(stop-start)/3 + start;
mergeSortThreeWay (A, start, firstThird);
mergeSortThreeWay (A, firstThird+1,secondThird);
mergeSortThreeWay (A, secondThird+1, stop);
mergeThreeWay(A, start, firstThird, secondThird, stop);
}
}
public static void main (String args[]) throws Exception {
int myArray[] = {3,1,4}; // an example array to be sorted. You'll need
to test your code with many cases, to be sure it works.
mergeSortThreeWay(myArray,0,myArray.length-1);
System.out.println("Sorted array is:\n");
for (int i=0;i<myArray.length;i++) {
System.out.println(myArray[i]+" ");
}
}
}

Strange new iOS 7 errors: receiver from DB / ForceShrinkPersistentStore_NoLock

Strange new iOS 7 errors: receiver from DB /
ForceShrinkPersistentStore_NoLock

Good day.
I have a project that uses a lot of network connections with SSL. This
project runs fine and without errors on iOS 5 and 6. But with new iOS 7 i
keep getting these two errors:
ERROR: unable to get the receiver data from the DB
ForceShrinkPersistentStore_NoLock -delete- We do not have a BLOB or TEXT
column type. Instead, we have 5.
They are not connected in any way and i did keep getting first one for few
weeks, then later i got this second one too.
They are received on my application start, at that point i send few HTTP
POST's and process received data. I cannot catch where do these errors
come from.
I could find them if i could understand them. Anyone know what do they
mean or on what cases one can cause them?

types of nodes in DOM

types of nodes in DOM

I am reading the book "Dom Scripting" by Jeremy Keith. I read that there
are total 12 types of nodes in DOM. I am just aware of five of them which
are -
Document
Element
Text
Attribute
Comment
I don't know about any other node. Please provide me with the knowledge
that I don't have.

Tuesday, 1 October 2013

Gson: illegalStateExcetpion: expected an int but NAME at line 1 column 3

Gson: illegalStateExcetpion: expected an int but NAME at line 1 column 3

I want to define my own serilaize and deserialize for Student class, so I
extends TypeAdapter and override its methods, but now deserialize does not
work. why ?
public class GSONFormat {
@Test
public void run()
{
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(Student.class, new StudentAdapter());
Gson gson = builder.create();
Student s = new Student();
s.setAge(11);
s.setName("hiway");
System.out.println(gson.toJson(s));
String str = "{\"age\":11,\"name\":\"hiway\"}";
s = gson.fromJson(str, Student.class);
System.out.println(s);
}
}
class Student{
private int age;
private String name;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
class StudentAdapter extends TypeAdapter<Student>
{
@Override
public void write(JsonWriter out, Student s) throws IOException {
out.beginObject();
out.name("age");
out.value(s.getAge());
out.name("name");
out.value(s.getName());
out.endObject();
}
@Override
public Student read(JsonReader in) throws IOException {
in.beginObject();
Student s = new Student();
s.setAge(in.nextInt());
s.setName(in.nextString());
in.endObject();
return s;
}
}

MySQL - Why would nearly 2 identical queries result in 2 different results? GROUP BY

MySQL - Why would nearly 2 identical queries result in 2 different
results? GROUP BY

I have 2 queries that are nearly identical, one with a GROUP BY, one
without. The results are very different. The GROUP BY query results in
over double the non-GROUP BY query result.
Query 1:
SELECT table2.name, COUNT(DISTINCT(op.id))
FROM op INNER JOIN table1 ON table1.EID = op.ID
INNER JOIN table3 ON table3.id = table1.jobid
INNER JOIN table2 ON table2.id = table3.CatID
WHERE op.BID = 1
AND op.ActiveStartDate <= NOW()
AND op.ActiveEndDate >= NOW()
GROUP BY table2.name
ORDER BY COUNT(*) DESC;
Query 2:
SELECT op.Type, COUNT(DISTINCT op.id)
FROM op
WHERE op.BID = 1
AND op.ActiveStartDate <= NOW()
AND op.ActiveEndDate >= NOW()
ORDER BY op.Type ASC;
These should result in the same result. When playing around with them,
once I remove the "GROUP BY" from query 1, the result is the same. If I
put the "GROUP BY" back into Query 1, the result is more than doubled.

Jboss lost connections to MongoDB "WARNING [com.mongodb] emptying DBPortPool to /x.x.x.x:27017 b/c of error"

Jboss lost connections to MongoDB "WARNING [com.mongodb] emptying
DBPortPool to /x.x.x.x:27017 b/c of error"

I have a few Jboss 5.1 servers which uses MongoDB data set. Till yesterday
I had 3 Mongo 2.0 nodes in this dataset. Yesterday I added 2 Mongo 2.4.6
secondaries to this dataset; and after that I see many warnings like that:
WARNING [com.mongodb] emptying DBPortPool to /x.x.x.x:27017 b/c of error
"Many" - about 30/day instead of 5/day before. Another thing that I don't
understand - according to jboss log, it started to use 2 new nodes, even I
didn't add them to mongo-ds.xml.
Any ideas why number of dropped connections increased and why jboss
started to use new nodes?
TIA, Vitaly
my mongo-ds is:
<mongo:mongo host="none"
replica-set="mongo1:27017,mongo2:27017,mongo3:27017">

PowerDNS master server doesn't notify

PowerDNS master server doesn't notify

I have a PowerDNS based master nameserver with 3 slaves. Zone transfer
works through AXFR (automatically once every hour it gets checked by the
slaves). When I change a record through our panel the notified_serial gets
updated correctly as well as the serial in the SOA record.
The nameserver uses a MySQL backend. The slaves don't get notified when
changes occur. Nothing is logged when it was supposed to send a Notify.
When I force a notify (like: pdns_control notify example.com) the slaves
get notified properly.
The config is as follows:
master=yes
setuid=pdns
setgid=pdns
local-address=xx.xxx.xx.xxx
allow-axfr-ips=xx.xxx.xx.xxx
use-logfile=yes
log-dns-details=yes
log-failed-updates=yes
logging-facility=0
loglevel=4
launch=gmysql
gmysql-host=localhost
gmysql-user=xxxxxxxxxxxxxxxx
gmysql-password=xxxxxxxxxxxxxxx
gmysql-dbname=powerdns

Monday, 30 September 2013

Choosing the best estimator

Choosing the best estimator

Given yield measurements $X_1,X_2,X_3$ from three independent runs of an
experiment with variance $\sigma^2$, which is the better of the two
estimators: $\hat\theta_{1}$= $\frac{X_1+X_2+X_3}{3}$,
$\hat\theta_{2}$=$\frac{X_1+2X_2+X_3}{4}$
I know that in order to find the best estimator if both are unbiased, we
are supposed to choose the one with the smallest variance. I need help
just starting this problem. Thank you.

Exact sequence and Tor functor.

Exact sequence and Tor functor.

Say $M$ is an $R$-module and $\operatorname{gld}(R)=n$, i.e. global
dimension of $R$ is n.
Is then $\operatorname{Tor}_i^{R}(M,N)=0$ for any $i>n$ and $M,N$ any
$R$-module?
Is it possible to choose $pd(M)\leq n$ to apply pd Lemma 4.1.6, p.93 in
Weibel's Introduction to Homological Algebra ?
I have an exact sequence \begin{align} 0 \rightarrow A \rightarrow P_2
\rightarrow P_1 \rightarrow P_0 \rightarrow
\mathbb{Z}_{(p)}/t\mathbb{Z}_{(p)}\rightarrow 0 \end{align} $P_i$ are
projective $\mathbb{Z}_{(p)}$-modules. I guess that somehow I apply
Weibel's Lemma to gain $A$ to be projective too. Applying
$\mathbb{Z}/p\mathbb{Z} \otimes_{\mathbb{Z}_{(p)}}-$ yields to
\begin{align} 0 \rightarrow \mathbb{Z}/p\mathbb{Z}
\otimes_{\mathbb{Z}_{(p)}}A \rightarrow \mathbb{Z}/p\mathbb{Z}
\otimes_{\mathbb{Z}_{(p)}}P_2 \rightarrow \mathbb{Z}/p\mathbb{Z}
\otimes_{\mathbb{Z}_{(p)}}P_1 \rightarrow \mathbb{Z}/p\mathbb{Z}
\otimes_{\mathbb{Z}_{(p)}}P_0 \rightarrow
\mathbb{Z}/p\mathbb{Z}\rightarrow 0 \end{align} Why is the first arrow
injective?

Can RemoteObjects be used with Granites´s Tide to enable Lazy Loading?

Can RemoteObjects be used with Granites´s Tide to enable Lazy Loading?

We have a Spring+Hibernate+Mysql+Flex/Cairngorm(2)/BlazeDS application. We
need to update this application so it can scale better, specifically we
need to use the lazy loading feature. So we decided to migrate from
BlazeDS to Granite Data Service. We have:
1.- Added the ant gas3 generation tool task for automatic synchronization
between domain objects
2.- We have a working application that loads the first level of our
graphs, but not deeper objects of the graph.
Our flex project uses RemoteObjects. I understand that to be able to use
Lazy Loading we need tide. To use tide api, we would need to change a
bunch of code. My question is, can I use RemoteObjects and Tide so I can
get Lazy Loading without changing our Flex code, just the configuration
files ?

specifying the "request method" in externalinterface.call method?

specifying the "request method" in externalinterface.call method?

When the user try to download the file ,i need to open a new html window
and download the file , currently iam using "ExternalInterface.call" but i
need to set the "requestmethod" otherwise server is throwing the error
,how to specify "requestmethod"?

Sunday, 29 September 2013

Memory management with Log4cpp

Memory management with Log4cpp

Im attempting to use log4cpp as a series of static member functions:
debug, error and info are each a function. Just pass in the relevant
formatted text and it writes to the configured location.
This is all well and good until I try to clean up the allocated memory.
Looking at the 'simple example' on this page it really looks like several
pointers are leaked. To avoid this I've tried several approaches but each
leads to a SIGSEGV:
smart pointers:
int main(int argc, char** argv)
{
//Setting up Appender, layout and Category
auto_ptr appender(new log4cpp::FileAppender( "FileAppender", LOGFILE ));
auto_ptr layout(new log4cpp::PatternLayout());
layout->setConversionPattern("%d: (%c)%p - %m %n");
log4cpp::Category& category = log4cpp::Category::getInstance( strCategory );
appender->setLayout( layout.get() );
category.setAppender( *appender );
category.setPriority( log4cpp::Priority::DEBUG );
category.debug( "debug message" );
}
This gives a segmentation fault when run.
Change this line:
auto_ptr layout(new log4cpp::PatternLayout());
to
log4cpp::PatternLayout* layout = new log4cpp::PatternLayout();
and add 'delete layout;' after the output.
Segmentation fault again.
Omitting the 'delete' line lets it run normally but it seems like it would
leak. (Im testing this on an ARM device using Debian 6.x - unfortunately
valgrind isn't available).
I'm missing something big and obvious here. Clue me in.

Can syntactic constructors in Python be overridden?

Can syntactic constructors in Python be overridden?

Couldn't find a way to phrase the title better, feel free to correct.
I'm pretty new to Python, currently experimenting with the language.. I've
noticed that all built-ins types cannot be extended with other members..
I'd like for example to add an each method to the list type, but that
would be impossible. I realize that it's designed that way for efficiency
reasons, and that most of the built-ins types are implemented in C.
Well, one why I found to override this behavior is be defining a new
class, which extends list but otherwise does nothing. Then I can assign
the variable list to that new class, and each time I would like to
instantiate a new list, I'd use the list constructor, like it would have
been used to create the original list type.
class MyList(list):
def each(self, func):
for item in self:
func(item)
list = MyList
my_list = list((1,2,3,4))
my_list.each(lambda x: print(x))
Output:
1
2
3
4
The idea can be generalize of course by defining a method that gets a
built it type and returns a class that extends that type. Further more,
the original list variable can be saved in another variable to keep an
access to it.
Only problem I'm facing right now, is that when you instantiate a list by
it's syntactic form, (i.e. [1,2,3,4]), it will still use the original list
constructor (or does it?). Is there a way to override this behavior? If
the answer is no, do you know of some other way of enabling the user to
extend the built-ins types? (just like javascript allows extending
built-ins prototypes).
I found this limitation of built-ins one of Python's drawbacks, making it
inconsistent with other user-defined types... Overall I really love the
language, and I really dont understand why this limitation is REALLY
necessary.

Error in Fscanf

Error in Fscanf

My code is a singly-linked that uses typedef struct which is in the form
of an array.
The program will ask the user for the text file to read, then the program
uses fscanf to store the data of the text file into the respective
variables.
The code contains while(!feof(file pointer))
The file of the user is in the format of
name(with spaces)
name2(with spaces)
number1
number2
.... until number10. And there are multiple "sets" of data with that
format within the file whose numbers of sets I do not know if.
I used *mygets for the names, (mygets = function which is basically fgets
that eliminate creation of newline.) then the rest, I used fscanf without
encountering any system error.
Now, I created a sample text file just to see if my codes are functioning
correctly.
The sample text file contains 2 "sets" of the data following the structure
mentioned earlier.
The problem is: The program reads and prints the First set of the data to
their respective variables correctly, but when the program prints the
Second set, it prints the First set again as if the Second set is ignored.
Code below:
void load_hero(hero *curr[])
{
char filename[256];
int totalwarrior;
hero *head;
hero *tail;
FILE *fwarrior;
head = NULL;
tail = NULL;
totalwarrior = 0;
printf("Name of Roster File for Warriors?(without .extension): \n");
scanf("%s",&filename);
strcat(filename,".txt");
fwarrior = fopen(filename,"r");
while(!feof(fwarrior))
{
curr[totalwarrior] = malloc(sizeof(hero));
curr[totalwarrior+1] = malloc(sizeof(hero));
mygets(curr[totalwarrior]->name,30,fwarrior);
mygets(curr[totalwarrior]->title,30,fwarrior);
fscanf(fwarrior,"%d\n",&curr[totalwarrior]->encoding);
fscanf(fwarrior,"%d\n",&curr[totalwarrior]->startstr);
fscanf(fwarrior,"%lf\n",&curr[totalwarrior]->incstr);
fscanf(fwarrior,"%d\n",&curr[totalwarrior]->startdex);
fscanf(fwarrior,"%lf\n",&curr[totalwarrior]->incdex);
fscanf(fwarrior,"%d\n",&curr[totalwarrior]->startintel);
fscanf(fwarrior,"%lf\n",&curr[totalwarrior]->incintel);
fscanf(fwarrior,"%d\n",&curr[totalwarrior]->basemindmg);
fscanf(fwarrior,"%d\n",&curr[totalwarrior]->basemaxdmg);
fscanf(fwarrior,"%lf\n",&curr[totalwarrior]->bat);
fscanf(fwarrior,"%lf\n",&curr[totalwarrior]->basearmor);
if (head == NULL)
{
head = curr[totalwarrior];
}
else
{
tail->next=curr[totalwarrior];
}
tail = curr[totalwarrior];
if (head!=NULL)
{
curr[totalwarrior] = head;
do {
printf("\n ::%s::Name\n",curr[totalwarrior]->name);
printf("\n ::%s::Title\n",curr[totalwarrior]->title);
printf("\n ::%d::Encoding\n",curr[totalwarrior]->encoding);
printf("\n ::%.d::Starting
Strength\n",curr[totalwarrior]->startstr);
printf("\n ::%.1lf::Increasing
Strength\n",curr[totalwarrior]->incstr);
printf("\n ::%.d::Starting
Dexterity\n",curr[totalwarrior]->startdex);
printf("\n ::%.1lf::Increasing
Dexterity\n",curr[totalwarrior]->incdex);
printf("\n ::%d::Starting
Intelligence\n",curr[totalwarrior]->startintel);
printf("\n ::%.1lf::Increasing
Intelligence\n",curr[totalwarrior]->incintel);
printf("\n ::%d::Base Minimum
Damage\n",curr[totalwarrior]->basemindmg);
printf("\n ::%d::Base Maximum
Damage\n",curr[totalwarrior]->basemaxdmg);
printf("\n ::%.1lf::Base Attack Time\n",curr[totalwarrior]->bat);
printf("\n ::%.1lf::Base Armor\n",curr[totalwarrior]->basearmor);
curr[totalwarrior] = curr[totalwarrior]->next =
curr[totalwarrior+1];
curr[totalwarrior] = NULL;
printf("Before Total %d\n",totalwarrior);
totalwarrior++;
printf("Now Total %d\n",totalwarrior);
}while(curr[totalwarrior-1] != NULL);
} free(curr[totalwarrior]);
}
}

How to keep the session with angular-http-auth?

How to keep the session with angular-http-auth?

I use angular-http-auth for authentication in an angular-js app.
If the user is already logged-in and he opens a new tab or if he reloads
the page, he has to log-in again.
How can is it possible to avoid that and to keep the session open if the
user reloads the page or comes from an external link ?
PS: i have a related unanswered question here : how to pass credentials
with angular-http-auth?

Saturday, 28 September 2013

Case insensitive array contains query in Postgres

Case insensitive array contains query in Postgres

I would like to match {TEST@EXAMPLE.COM} with {test@example.com,
other@example.com}
Doing the case sensitive query is each enough:
select * from users where email @> '{test@example.com}'
However, I cannot find a way to run a case insensitive contains query
against an array column.
This page does not instill confidence that this is possible, as there is
no mention of case sensitivity. Any thoughts?

I need help on my java program

I need help on my java program

import java.util.Scanner;
public class WordLines {
public static void main(String [] args) {
Scanner sca = new Scanner(System.in);
System.out.println("Enter a sentence");
String s = sca.nextLine();
int count = 0;
for(int j=0; j<s.length(); j++)
System.out.println(s.charAt(j));
}
}
I am trying to write a program that reads certain line from user input and
then displays only one word from than sentence to new line at a time.
For example
Input: The hill is very-steep!!
It would print out
The
hill
is
very-steep!!
So far I have done this much!!

rspec-rails: testing a controller action that renders a partial

rspec-rails: testing a controller action that renders a partial

I have a UsersController that has index and new actions. I use haml, the
index haml file contains the following code:
= link_to 'Add User', new_user_path, { :remote => true, 'data-toggle' =>
'modal',
'data-target' => '#modal-window', 'class' => 'btn btn-primary pull-right' }
So when the user clicks 'Add User' the _new.html.haml partial is presented
to the user as a modal. It works great.
Now in my controller spec I am trying to do the following:
describe "new action" do
before do
get new_user_path
end
# specs for 'new' action go here
end
However that gives an error
Failure/Error: get 'new'
ActionView::MissingTemplate:
Missing template users/new, application/new with {:locale=>[:en],
:formats=>[:html], :handlers=>[:erb, :builder, :coffee, :haml]}.
Searched in:
*
"#<RSpec::Rails::ViewRendering::EmptyTemplatePathSetDecorator:0x007faa44b03218>"
Presumably because it can't find new.html.haml which of course doesn't
exist because the file is a partial named _new.html.haml. What is the
correct syntax for getting the partial? If not, how can I test the new
action?

Make Div tag like body tag

Make Div tag like body tag

I want to add background to div. If content height will be small,
background will be cutted. If I add min-height, when window height is
small, there are apeears scrollbar.. Help please)

Friday, 27 September 2013

load a select tag with values ​​of DB action is done if the user has changed the value of another select tag

load a select tag with values &#8203;&#8203;of DB action is done if the
user has changed the value of another select tag

My problem is to fill the opions of the first select tag values
&#8203;&#8203;of the DB, action is done if the user has changed the value
of another tag select. i use php5 with CodeIgniter framework. Thank you in
advance.

Setting up localhost

Setting up localhost

System Specs: Windows 7; Notes/Desinger: 9.0; ExtLib: most current version
Trying to test my XPages on my localhost, but everything I have found and
tried has failed. I updated the local security to allow both localhost and
127.0.0.1. I updated the host file so the localhost line wasn't commented
out. I changed some registry setting. The only thing I have yet to do is
create local server machines and install domino server because I don't
have the server license to do that.
Anyone have other suggestions?

add user input to list

add user input to list

I want it to ask the user to input their favorite film and it to add that
input at the end of the list and then display the list again. as well as
making sure the film entered is not in the least already. this is how far
ive got up to :
films = ["Star Wars", "Lord of the Rings", "Shawshank Redemption", "God
father"]
for films in films:
print ("%s" % films)
add = input("Please enter a film: ")
films.insert(-1,add)
print (films)
Edit:
When I tried that I get an error:
Traceback (most recent call last):
File "H:\Modules (Year 2)\Advanced programming\Python\Week 2 - Review and
Arrays\Week 2.2 - Exercises.py", line 48, in films.append(add)
AttributeError: 'str' object has no attribute 'append'

Aviary jquery pass a form variable to post url

Aviary jquery pass a form variable to post url

I am trying to send an image name using aviary and need the image name
included. I have a hidden field in my form "img" Here is the code:
<script type='text/javascript'>
var featherEditor = new Aviary.Feather({
apiKey: 'yogbsxwbf3bl74f4',
apiVersion: 3,
theme: 'dark', // Check out our new 'light' and 'dark' themes!
tools: 'enhance,crop,orientation,brightness,sharpness,redeye,resize,text',
appendTo: '',
onSave: function(imageID, newURL) {
var img = document.getElementById(imageID);
img.src = newURL;
},
onError: function(errorObj) {
alert(errorObj.message);
},
postUrl: 'http://198.57.135.205/~gsidev/gallery/post.php',
postData : document.getElementById(img),// this is the field I need and
does not work?
});
function launchEditor(id, src) {
featherEditor.launch({
image: id,
url: src
});
return false;
}
</script>
Thanks for any guidance. The support for php implementation is terrible on
Aviary...

Unicode render issue to PDF using iTextSharp

Unicode render issue to PDF using iTextSharp

I was trying to render Gujarati language HTML text to PDF which get render
but not correctly. I was trying to render
"&#2709;&#2750;&#2736;&#2765;&#2732;&#2728;
&#2709;&#2759;&#2734;&#2759;&#2744;&#2765;&#2719;&#2765;&#2736;&#2752;"
text to PDF but it get render like "&#2709;&#2750;&#2736;&#2732;&#2728;
&#2709;&#2759;&#2734;&#2744;&#2719;&#2736;&#2752;"
Could you please help to render it properly.
protected void btnPDF_Click(object sender, EventArgs e)
{
Document doc = new Document(iTextSharp.text.PageSize.LETTER, 10,
10, 42, 35);
BaseFont Gujarati =
iTextSharp.text.pdf.BaseFont.CreateFont("C:\\WINDOWS\\Fonts\\ARIALUNI.TTF",
BaseFont.IDENTITY_H, BaseFont.EMBEDDED); // --> CHANGED
iTextSharp.text.Font fontNormal = new iTextSharp.text.Font(Gujarati);
PdfWriter wri = PdfWriter.GetInstance(doc, new
FileStream("c:\\Test11.pdf", FileMode.Create));
//Open Document to write
doc.Open();
//Write some content
Paragraph paragraph = new
Paragraph("&#2709;&#2750;&#2736;&#2765;&#2732;&#2728;
&#2709;&#2759;&#2734;&#2759;&#2744;&#2765;&#2719;&#2765;&#2736;&#2752;",
fontNormal); // --->> CHANGED Specify the font to use
// Now add the above created text using different class object to
our pdf document
doc.Add(paragraph);
doc.Close(); //Close document
}

R rownames(foo[bar]) prints as null but can be successfully changed - why?

R rownames(foo[bar]) prints as null but can be successfully changed - why?

I've written a script that works on a set gene-expression data. I'll try
to separate my post in the short question and the rather lengthy
explanation (sorry about that long text block). I hope the short question
makes sense in itself. The long explanation is simply to clarify if I
don't get the point along in the short question.
I tried to aquire basic R skills and something that puzzles me occurred,
and I didn't find any enlightment via google. I really don't understand
this. I hope that by clarifying what is happening here I can better
understand R. That said I'm not a programmer so please bear with my bad
code.
SHORT QUESTION:
When I have rownames(foo) e.g.
> print(rownames(foo))
"a" "b" "c" "d"
and I try to access it via print(rownames(foo[bar]) it prints it as null. E.g
> print(rownames(foo[2]))
NULL
Here in the second answer Richie Cotton explains this as "[...] that where
there aren't any names, [...]" This would indicate to me, that either
rownames(foo) is empty - which is clearly not the case as I can print it
with "print(rownames(foo))" - or that this method of access fails.
However when I try to change the value at position bar, i get a warning
message, that the replacement length wouldn't match. However the operation
nevertheless succeeds - which pretty much proves, that this method of
access is indeed successful. E.g.
> bar = 2
> rownames(foo[bar]) = some.vector(rab)
> print(rownames(foo[bar])
NULL
> print(rownames(foo))
"a" "something else" "c" "d"
Why is this working? Obviously the function can't properly access the
position of bar in foo, as it prints it as empty. Why the heck does it
still replace the value successfully and not fail in a horrific way? Or
asked the other way around: When it successfully replaces the value at
this position why is the print function not returning the value properly?
LONG BACKGROUND EXPLANATION:
The data source contains the number in the list, the entrez-id of the
gene, the official gene symbol, the affimetrix probe id and then the
increase or decrease values. It looks something like this:
No Entrez Symbol Probe_id Sample1_FoldChange Sample2_FoldChange
1 690244 Sumo2 1367452_at 1.02 0.19
Later when displaying the data I want it to print out only the gene symbol
and the increases. Now if there is no gene-symbol in the data set it is
printed as "n/a", this is obviously of no value for me, as I can't
determine which one of many genes it is. So I made a first processing
step, that only for this cases exchanges the "n/a" result with "n/a(12345)
where 12345 is the entrez-id.
I've written the following script to do this. (Note as I'm not a
programmer and I am new with R I doubt that it is pretty code. But that's
not the point I want to discuss.)
no.symbol.idx <-which(rownames(expr.table) == "n/a")
c1 <- character (length(rownames(expr.table)))
c2 <- c1
for (x in 1:length(c1))
{
c1[x] <- "n/a ("
}
for (x in 1:length(c2))
{
c2[x] <- ")"
}
rownames(expr.table)[no.symbol.idx] <- paste(c1, (expr.table[no.symbol.idx
, "Entrez"]),c2, sep="")
The script works and it does what it should do. However I get the
following error message.
Warning message:
In rownames(expr.table)[no.symbol.idx] <- paste(c1,
(expr.table[no.symbol.idx, :
number of items to replace is not a multiple of replacement length
To find out what happened here is i put some text output into the script.
no.symbol.idx <-which(rownames(expr.table) == "n/a")
c1 <- character (length(rownames(expr.table)))
c2 <- c1
for (x in 1:length(c1))
{
c1[x] <- "n/a ("
}
for (x in 1:length(c2))
{
c2[x] <- ")"
}
print("print(rownames(expr.table)):")
print(rownames(expr.table))
print("print(no.symbol.idx):")
print(no.symbol.idx)
print("print(rownames(expr.table[no.symbol.idx])):")
print(rownames(expr.table[no.symbol.idx]))
print("print(rownames(expr.table[14])):")
print(rownames(expr.table[14]))
print("print(rownames(expr.table[15])):")
print(rownames(expr.table[15]))
cat("print(expr.table[no.symbol.idx,\"Entrez\"]):\n")
print(expr.table[no.symbol.idx,"Entrez"])
rownames(expr.table)[no.symbol.idx] <- paste(c1, (expr.table[no.symbol.idx
, "Entrez"]),c2, sep="")
print("print(rownames(expr.table)):")
print(rownames(expr.table))
print("print(rownames(expr.table[no.symbol.idx])):")
print(rownames(expr.table[no.symbol.idx]))
And I get the following output in the console.
[1] "print(rownames(expr.table)):"
[1] "Sumo2" "Cdc37" "Copb2" "Vcp" "Ube2d3" "Becn1" "Lypla2" "Arf1"
"Gdi2" "Copb1" "Capns1" "Phb2" "Puf60" "Dad1" "n/a"
[1] "print(no.symbol.idx):"
[1] 15
[1] "print(rownames(expr.table[no.symbol.idx])):"
NULL
[1] "print(rownames(expr.table[14])):"
NULL
[1] "print(rownames(expr.table[15])):"
NULL
... (to be continued) so obviously no.symbol.idx gets the right position
for the n/a value. When I try to print it however it claims that rownames
for this position was empty and returns NULL. When I try to access this
position "by hand" and use expr.table[15] it also returns NULL. This
however has nothing to do with the n/a value as the same holds true for
the value stored at position 14.
... (the continuation)
print(expr.table[no.symbol.idx,"Entrez"]):
[1] "116727"
[1] "print(rownames(expr.table)):"
[1] "Sumo2" "Cdc37" "Copb2" "Vcp" "Ube2d3"
"Becn1" "Lypla2" "Arf1" "Gdi2"
[10] "Copb1" "Capns1" "Phb2" "Puf60" "Dad1"
"n/a (116727)"
[1] "print(rownames(expr.table[no.symbol.idx])):"
NULL
and this is the result that surprises me. Despite this it is working. It
claims everything would be NULL but the operation is successful. I don't
understand this.

Thursday, 19 September 2013

How to retrieve locations of theaters through google

How to retrieve locations of theaters through google

I am not sure if this is even possible, or if I am just in need of a
database or something. However, I am wondering if there is any way in an
android app to get a list of the lat and long of specific buildings near
the user's location. Basically what I want is for my app to have a set of
known theaters for example, and when the user is within a certain radius
of these locations then an action will occur. I know how to do the second
part using the location manager and firing an intent when the user is
within the specified radius, see the google developer guide. However, I do
not know how to get the location of the theaters in the city or area that
the user resides.

Conditional column rendering

Conditional column rendering

I'm working with jsf 2.0. I have this datatable
<h:dataTable value="#{agreement.licenseProducts}"
var="licenseProduct"
styleClass="pnx-table pnx-table-bdr pnx-table-unstyled mp-license-info">
<h:column>
<f:facet name="header">
<h:outputText value="Product" />
</f:facet>
<h:outputText value="#{licenseProduct.description}" />
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="Serial Number" />
</f:facet>
<h:outputText value="#{licenseProduct.serialNumber}" />
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="#{agreement.labelForConcurrency}" />
</f:facet>
<h:outputText value="#{licenseProduct.concurrent}" />
</h:column>
<ui:fragment rendered="#{agreement.managementTool != 'NONE'}">
<h:column>
<f:facet name="header">
<h:outputText value="#{agreement.labelForLicenseType}" />
<span class="pnx-icon-right pnx-icon-info pnx-tooltip">
<div class="pnx-tooltip-content">
<h:outputText value="Tooltip content" />
</div>
</span>
</f:facet>
<h:outputText value="#{licenseProduct.licenseBase}" />
</h:column>
</ui:fragment>
<h:column>
<f:facet name="header">
<h:outputText value="#{agreement.labelForSeatCount}" />
</f:facet>
<h:outputText value="#{licenseProduct.seats}" />
</h:column>
</h:dataTable>
The problem is that the ui:fragment part is not working. No matter what
the attribute's value is, it will NEVER show the column.
Any ideas?

How to properly align something that resizes in a specific location

How to properly align something that resizes in a specific location

Alright I am working on a webpage and when you attempt to fill in a login
form or register form it has a message pop-up if anything goes wrong... Or
right. And I would like it in the center of the planet image. It is a Div.
Also to note the planet image has text as part of it underneath so using
the image for a center reference is out of the question. I merely want to
know how I can Set the middle point to always be the same so when more
than one error/message occurs it won't be off center and it would look
nice as it grows with every message added. I'm not disclosing the name of
the site for personal reasons.
Image: ( Sorry for the potato quality )
CSS:
#banner{
width: 800px;
margin-left: -400px;
left:50%;
top: 100px;
margin-bottom: 20px;
font-size: 15px;
font-weight: bold;
color:rgb(255,255,255);
text-align: center;
line-height: 30px;
border-radius: 15px;
position: absolute;
}
Html and Php:
<?php
if (empty($_SESSION['errors']) === false) {
echo '<div id="banner" style="background-color:rgb(120,0,0);">';
output_errors($_SESSION['errors']);
echo '</div>';
$_SESSION['errors'] = NULL;
}
if (empty($_SESSION['message']) === false) {
echo '<div id="banner" style="background-color:rgb(0,100,0);">';
output_errors($_SESSION['message']);
echo '</div>';
$_SESSION['message'] = NULL;
}
?>
The function output_errors just turns an array to a string and echos it.

difficulties with SOAP client parameters

difficulties with SOAP client parameters

I'm breaking my head on this one and searched ages to find topics that
would point me in the right direction but without luck.
All I need to do is send a couple of parameters for this request, not too
hard. My normal request I do with the php Soap function:
$client = new SoapClient("http://SOAPURL");
$result = $client->__soapCall("FUNCTION", array('PARAMETERS' => 'value'));
But here it comes: In the following wsdl I'm having an issue with the
second parameter Membership. How on earth is my parameter array going to
look like with the values of Membership in it? I seriously tried tons of
variations but none of 'm is giving me success.
<soapenv:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:urn="urn:NAMESOAPIntf-INSOAP">
<soapenv:Header/>
<soapenv:Body>
<urn:SC_Insert_Membership
soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<Check_Only xsi:type="xsd:int">0</Check_Only>
<Membership xsi:type="urn:TMembership" xmlns:urn="urn:NSKIVSOAPIntf">
<MEMBERSHIP_AUTOPAYCODE_ID
xsi:type="xsd:string">0</MEMBERSHIP_AUTOPAYCODE_ID>
<MEMBERSHIP_PAYACCOUNT_ID
xsi:type="xsd:string">(number)</MEMBERSHIP_PAYACCOUNT_ID>
<MEMBERSHIP_RELATION_ID
xsi:type="xsd:int">(number)</MEMBERSHIP_RELATION_ID>
<MEMBERSHIP_SOURCE_ID
xsi:type="xsd:string">(number)</MEMBERSHIP_SOURCE_ID>
</Membership>
</urn:SC_Insert_Membership>
</soapenv:Body>
</soapenv:Envelope>
Who can help me?
Thanks for your time.

Excel IF show picture

Excel IF show picture

I have a list of codes in sheet 1 (COLUMN A - No of category, COLUMN B -
empty)
In the second sheet i have two columns (COLUMN A - No of category, COLUMN
B - graphic)
How do i use VLOOKUP or any other function to find the matching category
and display the appropriate image in the COLUMN B of sheet 1.
I havent really tried much because i've got no clue of how to do it.
Thank you so much!
http://i.stack.imgur.com/WKyWI.png

CMD how to use if and tasklist with find /C

CMD how to use if and tasklist with find /C

Anyone knows how to use IF and tasklist with find /C. I want to compare
running instances or certain application to predefined number.
Application name= test.exe
number of instances that should run=2 (If there are less then do stuff
else report OK)
Here is my doo-bey-doo so far:
tasklist /FI "IMAGENAME eq test.exe" | find /I /C "test.exe"
This works great. I get the correct figure of running instances. But when
I put it into IF sentence in a BATCH file that's where the hell breaks
loose. So where I go wrong here?
if tasklist /FI "IMAGENAME eq test.exe" | find /I /C "test.exe" EQU 2 :
ECHO OK
ELSE ( GOTO doStuff )
:doStuff

How to show last screen of Youtube Video when youtube video finishes?

How to show last screen of Youtube Video when youtube video finishes?

I am adding youtube video link in my web application using following
JavaScript code. This is working Fine. But when Video finishes by default
youtube video gives other links divided in small square boxes, I dont want
this.
When video finishes then black screen should appear or whatever is the end
screen there in video should appear.
Can we do this? If yes then how?
youtubeLoadVideos : function () {
var videos = document.getElementsByClassName("youtube");
for (var i=0; i<videos.length; i++) {
var youtube = videos[i];
var iframe = document.createElement("iframe");
iframe.setAttribute("src", "http://www.youtube.com/embed/" +
youtube.id);
// The height and width of the iFrame should be the same as
parent
iframe.style.width = youtube.style.width;
iframe.style.height = youtube.style.height;
iframe.style.clear = 'both';
youtube.parentNode.appendChild(iframe, youtube);
//youtube.appendChild(youtube.id);
}
}

Exception occured while replacing "[" String in java

Exception occured while replacing "[" String in java

I want to remove "[" and "]" character from string.
My Code is:
String original=data.replaceAll("]|[", "");
I am getting error:
09-19 13:25:55.755: E/AndroidRuntime(25007): FATAL EXCEPTION: main
09-19 13:25:55.755: E/AndroidRuntime(25007):
java.util.regex.PatternSyntaxException: Syntax error
U_REGEX_MISSING_CLOSE_BRACKET near index 3:
09-19 13:25:55.755: E/AndroidRuntime(25007): ]|[
09-19 13:25:55.755: E/AndroidRuntime(25007): ^
09-19 13:25:55.755: E/AndroidRuntime(25007): at
com.ibm.icu4jni.regex.NativeRegEx.open(Native Method)
09-19 13:25:55.755: E/AndroidRuntime(25007): at
java.util.regex.Pattern.compileImpl(Pattern.java:383)
09-19 13:25:55.755: E/AndroidRuntime(25007): at
java.util.regex.Pattern.<init>(Pattern.java:341)
09-19 13:25:55.755: E/AndroidRuntime(25007): at
java.util.regex.Pattern.compile(Pattern.java:358)
09-19 13:25:55.755: E/AndroidRuntime(25007): at
java.lang.String.replaceAll(String.java:2004)

Wednesday, 18 September 2013

extract js data fromw eb page using scrapy

extract js data fromw eb page using scrapy

I am crawling a web page using scrapy.
Now there's some data in script tag. i got all data in script tag using
xpath and looks like this.
<script>
some data
abc.xyz=[ ["mohit","gupta","456123"]
]
some data
I want data in abc.xyz now I am stuck that how to handle this..
thanks in advance

Web Cam in use notification on Windows

Web Cam in use notification on Windows

Is there a way for my Windows program to get notifications when a video
device is in use. I know how to enumerate the devices using
http://msdn.microsoft.com/en-us/library/dd377566(v=vs.85).aspx I can also
use ffmpeg to open the video device to check if it is available but it
opens up the camera for that fraction of a time which I don't want. Any
help will be appreciated. Thanks.

Newbie error: XamlParseException occured in WPF application

Newbie error: XamlParseException occured in WPF application

I'm trying to build a WPF application using the example here: Windows
sample WPF application . However I'm getting the following error as I work
through it
'Provide value on 'System.Windows.StaticResourceExtension' threw an
exception.' Line number '36' and line position '55'.
And its thrown on the following line
<ListBox Name="peopleListBox" Grid.Column="1" Grid.Row="2"
ItemsSource="{Binding Source={StaticResource ExpenseDataSource},
XPath=Person}"
ItemTemplate="{StaticResource nameItemTemplate}">
</ListBox>
The inner exception provides the following details
{"Cannot find resource named 'nameItemTemplate'. Resource names are case
sensitive."}
Here's the problematic xaml.
<Page x:Class="ExpenseIt.ExpenseItHome"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300"
Title="ExpenseIt-Home">
<Grid Margin="10,0,10,10">
<Grid.Background>
<ImageBrush ImageSource="2012-12-20 13.27.57.jpg" />
</Grid.Background>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="230" />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition Height="Auto"/>
<RowDefinition />
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<!-- People list -->
<Label Grid.Column="1" Style="{StaticResource headerTextStyle}" >
View Expense Report
</Label>
<Border Grid.Column="1" Grid.Row="1" Style="{StaticResource
listHeaderStyle}">
<Label Style="{StaticResource listHeaderTextStyle}">Names</Label>
</Border>
<ListBox Name="peopleListBox" Grid.Column="1" Grid.Row="2"
ItemsSource="{Binding Source={StaticResource ExpenseDataSource},
XPath=Person}"
ItemTemplate="{StaticResource nameItemTemplate}">
</ListBox>
<!-- View report button -->
<Button Grid.Column="1" Grid.Row="3" Click="Button_Click"
Style="{StaticResource buttonStyle}">View</Button>
<Grid.Resources>
<!-- Expense Report Data -->
<XmlDataProvider x:Key="ExpenseDataSource" XPath="Expenses">
<x:XData>
<Expenses xmlns="">
<Person Name="Mike" Department="Legal">
<Expense ExpenseType="Lunch"
ExpenseAmount="50" />
<Expense ExpenseType="Transportation"
ExpenseAmount="50" />
</Person>
<Person Name="Lisa" Department="Marketing">
<Expense ExpenseType="Document printing"
ExpenseAmount="50"/>
<Expense ExpenseType="Gift"
ExpenseAmount="125" />
</Person>
<Person Name="John" Department="Engineering">
<Expense ExpenseType="Magazine subscription"
ExpenseAmount="50"/>
<Expense ExpenseType="New machine"
ExpenseAmount="600" />
<Expense ExpenseType="Software"
ExpenseAmount="500" />
</Person>
<Person Name="Mary" Department="Finance">
<Expense ExpenseType="Dinner"
ExpenseAmount="100" />
</Person>
</Expenses>
</x:XData>
</XmlDataProvider>
<!-- Name item template -->
<DataTemplate x:Key="nameItemTemplate">
<Label Content="{Binding XPath=@Name}"/>// isnt this enough?
</DataTemplate>
</Grid.Resources>
</Grid>
</Page>
Any help on what Im doing wrong and how I could correct it, would be
greatly appreciated! Thanks!

SSIS REGEX CLEAN transformation error

SSIS REGEX CLEAN transformation error

I have used RegexClean Transformation to clean my data
match : [!@#$%^&*_+`{};':,./<>?0123456789](?<empty>)
replace : ${empty}
It is removing the special characters but the only problem is it is giving
me nulls for the rows which are correct So I am little confused why
exactly is this error occuring
NUM VEH NAME NAME_Clean
1 CREDEUR CYNTHIA D NULL
2 FLUKE NANCY C NULL
017 1 CLARK, WILLIAM CLARK WILLIAM
037 2 DESORMEAUX, MICHELLE DESORMEAUX MICHELLE
043 1 FALCON, JENNIFER, FALCON JENNIFER
073 2 WINTERS, ALLEN WINTERS ALLEN
084 1 UNKNOWN NULL
094 2 UNKNOWN NULL

Increase number of form inputs with js or php

Increase number of form inputs with js or php

I've created a script for a project using php and mysql to allow users to
create questions with multiple choice answers. By default I've set it so
that you can only have one question in your quiz but I am trying to add a
button that when clicked you can add new input box's in order to add more
questions to your quiz. I thought I should do this in javascript because
it is client side and therefor wont alter what is already entered in the
previous input boxes? I tried a for loop with a counter and increment the
counter on click but this doesn't seem to work because I think the page
needs to refresh. I don't mind if the solution is in php or javascript.
var limit = 1;
function addQuestion(){
limit++;
}
for(var i=1; i <= limit; i++)...

sql query times out...case / if / what to do

sql query times out...case / if / what to do

I have the following sql server sproc:
PROCEDURE [dbo].[GetSoftwareProgramsGrid]
@SoftwareTitle varchar(1000)='All',
@CategoryID varchar(100)='All',
@ManufacturerID varchar(50)='All',
@ModelID int=0, -- 0 means all
@AssetID int=0, -- 0 means all
@AssetStatus int=0, --0 is active, 1 is inactive, and 2 is all
@Status int=0, --0 is active, 1 is inactive, and 2 is all
@Type varchar(100)='All',
@Site varchar(100)='All',
@Department varchar(100)='All',
@Manager varchar(100)='All',
@Employee varchar(100)='All',
@SortExpression varchar(100)='Software',
@SortOrder int=0
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
SELECT
*
FROM
(
SELECT DISTINCT
Program AS Software
FROM
AssetProgram ap
LEFT JOIN
AssetAssignment aa
ON
aa.AssetID = ap.AssetID
LEFT JOIN
[MyLinkedServer].MyDB.dbo.Login l
ON
l.LoginID = aa.LoginID
LEFT JOIN
Asset a
ON
a.AssetID = ap.AssetID
INNER JOIN Model m
ON
a.ModelID = m.ModelID
INNER JOIN
Category c
ON
c.CategoryID = m.CategoryID
INNER JOIN Manufacturer ma
ON
ma.ManufacturerID = m.ManufacturerID
WHERE
(
--Software filters
(ap.Program = @SoftwareTitle OR @SoftwareTitle='All')
--Asset filters
AND (c.CategoryID = @CategoryID OR @CategoryID='All')
--filter category
AND (ma.ManufacturerID = @ManufacturerID OR
@ManufacturerID='All') --filter manufacturer
AND (m.ModelID = @ModelID OR @ModelID = 0) --filter model
AND (a.AssetID = @AssetID OR @AssetID = 0) --filter by asset
name (the actual asset id)
AND (((a.Inactive=@AssetStatus) OR (@AssetStatus=2)))
AND (aa.Inactive=0)
AND (ap.Inactive=0)
--Employee filters
/*AND ((l.Inactive=@Status) OR (@Status=2)) --status of
employee 2 is all, 1 is inactive, and 0 is active
AND (@Type='All' OR (@Type='Contractor' AND l.IsContractor=1)
OR (@Type='Regular' AND l.IsContractor=0)) --contractor or
regular employee
AND (@Site='All' OR @Site=l.ClientID) --the site
AND (@Department='All' OR @Department=l.FunctionalGroupID)
--the department
AND ((l.Manager = @Manager OR l.FullName=@Manager) OR
@Manager='All') --the manager
AND (l.FullName = @Employee OR @Employee='All') --the employee
*/
)) ttt
ORDER BY
CASE WHEN @SortExpression='Software' AND @SortOrder=0 THEN
Software END ASC,
CASE WHEN @SortExpression='Software' AND @SortOrder=1 THEN
Software END DESC
This query has to include a linked server, due to our setup. The query
runs fine and is fast as long as I comment out my employee parameters,
namely this section:
--Employee filters
/*AND ((l.Inactive=@Status) OR (@Status=2)) --status of
employee 2 is all, 1 is inactive, and 0 is active
AND (@Type='All' OR (@Type='Contractor' AND
l.IsContractor=1) OR (@Type='Regular' AND
l.IsContractor=0)) --contractor or regular employee
AND (@Site='All' OR @Site=l.ClientID) --the site
AND (@Department='All' OR @Department=l.FunctionalGroupID)
--the department
AND ((l.Manager = @Manager OR l.FullName=@Manager) OR
@Manager='All') --the manager
AND (l.FullName = @Employee OR @Employee='All') --the
employee
*/
The minute I bring even the first line of that section in, for example
just this one:
AND ((l.Inactive=@Status) OR (@Status=2))
The entire sproc hangs (times out)....I've properly indexed my tables and
I even have an index on the Inactive field within my linked table...If I
take that same line above and just say:
AND (l.Inactive=0)
It runs fine, so the OR condition is causing it (boolean). However, I need
this condition as a parameter is passed that needs to be satisfied. What
are my other options, do I have to IF BEGIN... using all these parameters?
It seems cumbersome...For anyones information the AssetProgram table has a
total of 50k rows, so that isn't too much.

Instantiating ImageButtons outside of Activity

Instantiating ImageButtons outside of Activity

Hi Im using several Image buttons that are displayed at the bottom of each
activity, and I was wondering if there is any way to instantiate each
object as they do the same thing in each activity and I do not want to be
repeating code in each activity.
Any advice would be greatly appreciated thanks. Marc

Divide by zero gives unicode #8734 character in Scala

Divide by zero gives unicode #8734 character in Scala

I'm using a velocity template in my Scala app which logs to a file. If I'm
dividing by zero why do I get a unicode representation (&#8734;) in my
templated log file and Infinity printed on Eclipse console when debugging
the below code?
val params = MMap.empty[String, Any]
params.put("percent", ((23.6 * 100.0) / 0.0))
debug(params.get("percent")).toDouble + "")

Tuesday, 17 September 2013

Change space for comma as column delimeter with columns of different length

Change space for comma as column delimeter with columns of different length

Hi I'm trying to fix a text with a batch file but no success. I have the
text like this:
05052013 20:10 12345 12310 12345678 00:00:24 5 05222013 10:15 12346 12311
5512345690 00:00:20 5 5800 05282013 10:10 12347 12312 5512345691 00:00:25
5 5700
And I need it like this:
05052013,20:10,12345,12310,12345678 ,00:00:24,5,
05222013,10:15,12346,12311,5512345690 ,00:00:20,5,5800
05282013,10:10,12347,12312,5512345691 ,00:00:25,5,5700
I'd appreciate any help...
Thanks in advance

Is my return written correctly for this type of connection?

Is my return written correctly for this type of connection?

My return is not returning back anything when attempting to find a
username, the sql is able to connect. Here is my code:
function usernameExists($username) {
global $conn;
$sql = "SELECT active FROM user
WHERE username='" . fixstr($username) . "' LIMIT 1";
if(returns_result($sql) > 0) {
return true;
} else {
return false;
}
}
Here is my connection:
/* Create a new mysql connect object with database connection parameters */
$conn = mysql_connect(db_server, db_user, db_pass);
if (!$conn)
die("Could not connect: " . mysql_error());
mysql_select_db(db_name, $conn);
My connection is not able to return anything but it does connect to the
server through fixstr.
Here is fixstr:
function fixstr($str){
$str = trim($str);
$str = str_replace("'", "''", $str);
return $str;
}
Why is my return not returning any results.

Notepad++ Replace new line inside text

Notepad++ Replace new line inside text

I have this sample, because is one of one million rows with that. I have
this text:
<tr class="even">
<td><a href="http://www.ujk.edu.pl/">Jan Kochanowski
University of Humanities and Sciences (Swietokrzyska Pedagogical
University) / Uniwersytet Humanistyczno Przyrodniczy Jana Kochanowskiego
w Kielcach</a></td>
I want to replace to be like that:
<tr class="even">
<td><a href="http://www.ujk.edu.pl/">Jan Kochanowski University of
Humanities and Sciences (Swietokrzyska Pedagogical University) /
Uniwersytet Humanistyczno Przyrodniczy Jana Kochanowskiegow
Kielcach</a></td>
I tried that REGEX: (.*) But didn't work.

XML serialization - bypass container class?

XML serialization - bypass container class?

I am trying to serialize an object in a particular manner. The main class
has a container class that holds some attributes, but really these
attributes should be on the main class, from the point of view of the
schema. Is there a way to bypass the container class and treat the
properties on the container class as properties on the main class, for the
purposes of serialization?
I am trying to create XML along the lines of:
<Main foo="3" bar="something">
<Others>etc</Others>
</Main>
from this code:
[System.Xml.Serialization.XmlRootAttribute("Main", Namespace = "")]
public class MainObject
{
public HelperContainer { get; set; }
public string Others { get; set; }
}
public class HelperContainer
{
[System.Xml.Serialization.XmlAttributeAttribute(AttributeName = "foo")]
public int Foo { get; set; }
[System.Xml.Serialization.XmlAttributeAttribute(AttributeName = "bar")]
public string Bar { get; set; }
}

Multi-language GUI setup with a string array

Multi-language GUI setup with a string array

I am working on the Keil uv4 IDE with an ARM Cortex-M3 in a bare metal C
application. I have a GUI that I created that is currently in English, but
I would like to give the user the ability to go between other languages
like you can on a cell phone.
I have created a structure with all the words that are used called
string_table_t.
struct string_table_t
{
char *word1;
char *word2;
char *word3;
};
My thought process was to have plain text files for the different
languages and the list of words used contained in each one. Then I would
do a load function that would link the pointers of the string table with
the actual word.
Now, my initial menu is created statically by defining it like so. It is
based off of Altium software platform.
// Test structure
struct string_table_t string_table = {"Main Menu","test1","test2"};
form_t mainmenu_form =
{
.obj.x = 0,
.obj.y = 0,
.obj.width = 240,
.obj.height = 320,
.obj.draw = form_draw,
.obj.handler = mainmenu_form_handler,
.obj.parent = NULL,
.obj.agui_index = 0,
.obj.visible = __TRUE,
.obj.enabled = __TRUE,
.caption.x = 0,
.caption.y = 0,
.caption.text = "Main Menu",
.caption.font = &helveticaneueltstdltext18_2BPP,
.caption.color = RGB(230,230,230),
.caption_line_color = RGB(241,101,33),
.caption.fontstyle = FS_NONE,
.caption.align = ALIGN_CENTRE,
.captionbarcolor = RGB(88,89,91),
.children = mainmenu_children,
.n_children = 4,
.relief = RELIEF_NONE,
.color = RGB(65,64,66),
};
What I want to do is replace the "Main Menu" of the caption.text with
string_table.word1. Therefore, if I load a different language set, the
menu will automatically be pointing to the correct char array. Doing this
currently results in a error expression must have a constant value.
Now, I can get this to work by leaving the text null in the menu component
and adding:
mainmenu_form.caption.text = string_table.Main_menu_text;
This will compile and work, but I would rather not have to have 100 or so
of these statements. Is there a more optimal way of doing this?

Unable to send email

Unable to send email

In the below codeigniter i want to send a email but i cant send it pls
help me.
Controller:
<?php
/**
* SENDS EMAIL WITH GMAIL
*/
class Email extends CI_Controller
{
function index()
{
$config['protocol'] = 'smtp';
$config['smtp_host'] = "smtp.gmail.com";
$config['smtp_port'] = 465;
$config['smtp_user'] = 'mosesvickson65@gmail.com';
$config['smtp_pass'] = 'mosesvickson65@gmail.com';
$this->load->library('email', $config);
$this->email->set_newline("\r\n");
$this->email->from('mosesvickson65@gmail.com', 'moses');
$this->email->to('mosesvickson65@gmail.com');
$this->email->subject('This is an email test');
$this->email->message('It is working. Great!');
if($this->email->send())
{
echo 'Your email was sent, successfully.';
}
else
{
show_error($this->email->print_debugger());
}
}
}
?>
It is showing error hello: The following SMTP error was encountered:
Failed to send AUTH LOGIN command. Error: from: The following SMTP error
was encountered: to: The following SMTP error was encountered: data: The
following SMTP error was encountered:
The following SMTP error was encountered: Unable to send email using PHP
SMTP. Your server might not be configured to send mail using this method.

Sunday, 15 September 2013

List operations getting a list's index

List operations getting a list's index

I have a class in my Windows application like so:
public class Pets
{
String Name {get;set;}
int Amount {get;set;}
}
In one of my other classes i made a List of that class like so.
List<Pets> myPets = new List<Pets>();
myPets.Add(new Pets{ Name = "Fish", Amount = 8});
myPets.Add(new Pets{ Name = "Dogs", Amount = 2});
myPets.Add(new Pets{ Name = "Cats", Amount = 2});
Is there a way i can get the Index of the Pets whos Name = "Fish"?
I realize i can do this
int pos = 0;
for(int x = 0; x<myPets.Count;x++)
{
if( myPets[x].Name == "Fish")
{
pos = x;
}
}
But in the case that i have ALOT of items in myPets it would take long to
loop through them to find the one i am looking for. Is there another way
to complete the task above. That would make my application run quicker? In
the case that myPets has a lot of items in it.

Some contact form emails not being sent due to spam filtering on host

Some contact form emails not being sent due to spam filtering on host

I need my contact form on my website to be adjusted. It's a PHP/Ajax
Contact Form.
Currently i have a problem - When a client fills out my contact form NAME
- EMAIL - SUBJECT - MESSAGE there is an issue with my DREAMHOST Server due
to their new anti spam policy and i dont receive some messages - If their
email is @hotmail.com that's fine. But if their email is @gmail.com i dont
get the message etc.
DREAMHOST TELLS ME:
Thanks for contacting Tech Support I checked the logs for the form on your
site and did see that the emails are being bounced by the server due to
recently implemented anti spam policies which won't allow email sent from
the server using non-Dreamhost outgoing servers or "send from" email
addresses. You can read more details on this policy here:
http://wiki.dreamhost.com/Sender_Domain_Policy_and_Spoofing
Your mail form uses the visitor's email address as the 'From' address
which in most cases is not a Dreamhost hosted email address. Due to the
spam policy above, the server will block mail being sent off the server if
the email addresses are not using Dreamhost mail servers. So what you will
need to do is either set the mail form to use your Dreamhost hosted
address as the 'From' address.
Or you will need to find another mail form that will allow you to set a
fixed email address as the 'From' address. This way you can set a
Dreamhost hosted email address in the form as the 'From' address.
THE CODE AS FOLLOWS:
<?php
/*
Credits: Bit Repository
URL: http://www.bitrepository.com/
*/
include dirname(dirname(__FILE__)).'/config.php';
error_reporting (E_ALL ^ E_NOTICE);
$post = (!empty($_POST)) ? true : false;
if($post)
{
include 'functions.php';
$name = stripslashes($_POST['name']);
$email = trim($_POST['email']);
$subject = stripslashes($_POST['subject']);
$message = stripslashes($_POST['message']);
$error = '';
// Check name
if(!$name)
{
$error .= 'Please enter your name.<br />';
}
// Check email
if(!$email)
{
$error .= 'Please enter an e-mail address.<br />';
}
if($email && !ValidateEmail($email))
{
$error .= 'Please enter a valid e-mail address.<br />';
}
// Check message (length)
if(!$message || strlen($message) < 15)
{
$error .= "Please enter your message. It should have at least 15
characters.<br />";
}
if(!$error)
{
$mail = mail(WEBMASTER_EMAIL, $subject, $message,
"From: ".$name." <".$email.">\r\n"
."Reply-To: ".$email."\r\n"
."X-Mailer: PHP/" . phpversion());
if($mail)
{
echo 'OK';
}
}
else
{
echo '<div class="notification_error">'.$error.'</div>';
}
}
?>
All i need to know is what i need to do to the code so i can receive all
submissions of my contact form. I would really be grateful if someone
could help.

AutoHotKey (AHK) How to make a gui that doesn't take over

AutoHotKey (AHK) How to make a gui that doesn't take over

I'm trying to make a script that when I'm typing, I can press a button and
a frameless window will pop up, i can select one of the options with the
1-3 keys, and it will take that text and put it where i was typing. How
would I do this? I'm so far gotten a Gui to pop up, but when i press one
of the keys, it doesn't send the text to where i was typing before. Are
there any tags that need to be added to the GUI code to make it so it
doesn't take over as the active window, but will still take input on which
button i press with?

Lazarus - Mac OSX Debugging Error

Lazarus - Mac OSX Debugging Error

everyone!
I used to use Delphi 7 on my PC, but now that I bought a MacBook (Mid 2012
- OSX Mountain Lion), I wanted to continue programming in Pascal and have
a similar Interface. Lazarus seems to deliver most of the things I wanted,
but it seems to run into a lot of errors, when compiling even the simplest
applications! To test it, I made a simple "Russian Roulette" application,
just for fun, but the program just freezes, when launched or even when
compiled inside Lazarus. When launching it from command line, It shows me
the following error:
TCarbonButton.SetFocus Error: SetKeyboardFocus failed with result -30585
I don't think my coding is the problem, but I guess I should include it:
unit RussianRouletteUnit;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls,
Buttons, ExtCtrls;
type
{ TForm1 }
TForm1 = class(TForm)
Button1: TButton;
Kugeln: TLabeledEdit;
Memo1: TMemo;
procedure Button1Click(Sender: TObject);
private
{ private declarations }
public
{ public declarations }
end;
var
Form1: TForm1;
Number: Integer;
implementation
{$R *.lfm}
{ TForm1 }
procedure TForm1.Button1Click(Sender: TObject);
begin
if Random(StrToInt(Kugeln.Text))+1 = 1 then
begin
Button1.SetFocus;
Memo1.Color := clred;
Memo1.Text := 'BOOM';
Memo1.Lines.Add('HEADSHOT');
end;
end;
initialization
randomize;
end.
I hope you guys can help me out, any help is apprechiated :D

Conditionally change CSS with AngularJS

Conditionally change CSS with AngularJS

I'm trying to change the background-color of a div based on the value of
an Angular expression. I have the following div:
<div class="outer">
<h4 class="weather-heading">It's currently {{weather}}</h4>
</div>
Based on the value of {{weather}} (i.e. sunny, cloudy), I want to change
the background-color of the outer div. What's the best way to do this with
angular?

extracting the svn log

extracting the svn log

I am doing a code review now there is a branch in which different
developers have commited the code now I can go to unix box and type svn
log and can see the code commited by different developers for a particular
bug but can I extract the log graphically also means I have installed the
svn plugin in eclipse is there any graphical way to extract the log for a
particular branch from eclipse itself

Using open source resources in application

Using open source resources in application

Im about to submit my first application. I have used a few open source
classes. Do i need to include any license or anything? I dont have any
idea about the application submission process in app store. Any feedback
or past experience about submitting apps to apple without any hassle would
be appreciated!

python can't find redis

python can't find redis

i bump into this: &#10140; iPokeMon-Server git:(dev) sudo python server.py
)git:(dev[] Password: Traceback (most recent call last): File "server.py",
line 2, in import redis ImportError: No module named redis
here are some clue
&#10140; iPokeMon-Server git:(dev) sudo easy_install redis )git:(dev[]
Searching for redis Best match: redis 2.8.0 Processing
redis-2.8.0-py2.7.egg redis 2.8.0 is already the active version in
easy-install.pth
Using /Library/Python/2.7/site-packages/redis-2.8.0-py2.7.egg Processing
dependencies for redis Finished processing dependencies for redis
&#10140; iPokeMon-Server git:(dev) sudo pip install redis )git:(dev[]
Requirement already satisfied (use --upgrade to upgrade): redis in
/Library/Python/2.7/site-packages/redis-2.8.0-py2.7.egg Cleaning up...

Saturday, 14 September 2013

Regex MULTILINE not working?

Regex MULTILINE not working?

In the example module below. The pattern only matches the first part of
the string. How to make it match and display all the substrings matching
the pattern?
filtered ='\n\rweakmoves (1835) seeking 5 0 unrated blitz ("play 89" to
respond)\n\r\n\rGuestKCCZ (++++) seeking 15 0 unrated standard ("play 91"
to respond)\n\r\n\rGuestKKKP (++++) seeking 3 0 unrated blitz f ("play
59" to respond)\n\r'
rgxseeking
=re.compile(r'^\S+\s\(([\d+-]+)\)\s+seeking\s+(\d+\s\d+)\s+(\S{1,7})\s(\S{1,9})(\s\[\S+\])?((\s[fm])?)((\s[fm])?)\s\("play\s\d{1,3}\"\sto\srespond\)$',re.MULTILINE)
seeking= re.search(rgxseeking,filtered)
if seeking:
print seeking.group()

select the last added element using JQuery

select the last added element using JQuery

So I have a simple bit of code. Nothing serious, or life-threatening. I'm
just trying to use JavaScript to fill out an empty html file with some
basic 100x100 elements by clicking on the last element created. Problem
is: I can't actually get my code to register the last element created,
only the last initial element. What could I be doing wrong?
<!DOCTYPE html>
<html>
<head>
<title>Container Rainbow</title>
<style type="text/css">
div{ width:100px;height:100px; }
#head{ background-color:rgba(100,0,100,.8);}
#wrapper{width:100%;height:auto;}
div#wrapper > div{float:left;}
</style>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"
type="text/javascript"></script>
<script type="text/javascript">
var lastDiv;
var rgba = new Array();
rgba[0] = 110; rgba[1] = 0; rgba[2] = 110; rgba[3] = 1;
$(document).ready(function(){
lastDiv = $("div").last();
lastDiv.on("click", function(){
rgba[0] += 5;
rgba[2] += 5;
var newDiv = $("<div></div>")
.addClass("hatchling")
.css("background-color",
"rgba("+rgba[0]+",0,"+rgba[2]+",1)")
$(this).after(newDiv);
lastDiv=newDiv;
});
});
</script>
</head>
<body>
<div id="wrapper">
<div id="head"></div>
</div>
</body>
</html>

while checking account number is numeric or no it is giving Syntax error. any one please help me

while checking account number is numeric or no it is giving Syntax error.
any one please help me

if[[ ${accoun_num} =~ ^[0-9]+$ ]]
while checking account number is numeric or no it is giving Syntax error.
any one please help me
Actually in my code I have space. the original code is look like below
if [[ ${account_nr} =~ ^[0-9]+$ && ${from_account_nr} =~ ^[0-9]+$ ]]

Navigation bar collapsing when shrinking window

Navigation bar collapsing when shrinking window

First off here is the code:
#menu {
padding:0;
margin-top:0px;
position:absolute;
top:0px;
width:100%;
float:left;
overflow:hidden;
}
#menu li {
list-style:none;
float: left;
position: relative;
border-bottom-right-radius: 20px;
border-bottom-left-radius: 20px;
border:1px solid black;
background-image: linear-gradient(#F2FF00, #AEFF00);
margin-left:10px;
}
#menu a {
display:block;
padding:auto;
text-align:center;
padding:10px 10px;
color: #0095FF;
text-transform: uppercase;
font: bold 25px Arial, Helvetica;
text-decoration: none;
text-shadow: 1px 1px 2px #0095FF;
}
The buttons move down when I shrink the window. If can set the height to
menu so it wont change, but still the buttons go outside of the menu
element, why does this happen?
Here is jsFiddle:http://jsfiddle.net/nqdXc/

why is myvar undefined after myvar = $(this)

why is myvar undefined after myvar = $(this)

So I am making a little game about a survivor in a desert. The survivor
has to drink from wells scattered throughout the desert on his way back to
Gold Rush Ghost Town. Some wells are good to drink from but others are
poisoned. I am displaying a tooltip on those TD elements of a table that
have the class "well". Inside the tooltip's initialization object, I need
to get a reference to the current TD element, so I can pass it to a
function that sets the tooltip's "content" property. Inside that function
I must test if the current TD has the class "poisoned" too.
function initWellsTooltip() {
$("#water-table tbody td.well").tooltip({
content: function () {
var well$ = $( this ); //
// at this point stepping through the code in the debugger,
// well$ is undefined and I don't understand why,
// because $(this).hasClass("poisoned") succeeds.
// VS2010 debugger shows as follows:
// ?$(this).hasClass("poisoned")
// true
// ?well$
// 'well$' is undefined
if (well$.hasClass("poisoned")) {
return "poisoned!";
} else {
return "potable";
}
},
items: "td.well",
position: { my: "left+15 center", at: "left top" }
});
}

MySQL collation and Glassfish default-charset encoding

MySQL collation and Glassfish default-charset encoding

I have a Glassfish 4 and MySQL 5.5 running on my local machine. The
database collation and Glassfish default-charset encoding is UTF-8. it
works with no problem.
However, when I deploy this application on a VPS linux server I can't seem
to save any record with UTF-8 character in it using the application. ª
becomes ? I checked my SQL server's collation and glassfish encoding
default-charset they are all UTF-8!
Is there something I am missing? Only difference is that my local runs
Windows 7 OS and the VPS is a Linux Ubuntu machine!
I would appreciate any help.

Friday, 13 September 2013

File Not Found Exception - Can't see the issue

File Not Found Exception - Can't see the issue

I've tried directly linking using the entire path but that hasn't solved
it either.
package eliza;
import java.io.*;
public class Eliza {
public static void main(String[] args) throws IOException {
String inputDatabase = "src/eliza/inputDataBase.txt";
String outputDatabase = "src/eliza/outputDataBase.txt";
Reader database = new Reader();
String[][] inputDB = database.Reader(inputDatabase);
String[][] outputDB = database.Reader(outputDatabase);
}
}
Here is the reader class:
package eliza;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;
public class Reader {
public String[][] Reader(String name) throws IOException {
int length = 0;
String sizeLine;
FileReader sizeReader = new FileReader(name);
BufferedReader sizeBuffer = new BufferedReader(sizeReader);
while((sizeLine = sizeBuffer.readLine()) != null) {
length++;
}
String[][] database = new String[length][1];
return (database);
}
}
Here's a photo of my directory. I even put these text files in the "eliza"
root folder: http://i.imgur.com/nMDrQoa.png
Any ideas?

R read.table loops row column entries to next row

R read.table loops row column entries to next row

This is the first time I encountered this problem using read.table: For
row entries with very large number of columns, read.table loops the column
entries into the next rows.
I have a .txt file with rows of variable and unequal length. For reference
this is the .txt file I am reading:
http://www.broadinstitute.org/gsea/msigdb/download_file.jsp?filePath=/resources/msigdb/4.0/c5.bp.v4.0.symbols.gmt
Here is my code:
tabsep <- gsub("\\\\t", "\t", "\\t")
MSigDB.collection = read.table(fileName, header = FALSE, fill = TRUE,
as.is = TRUE, sep = tabsep)
Partial output: first columns
V1
V2
V3 V4 V5 V6
1 TRNA_PROCESSING
http://www.broadinstitute.org/gsea/msigdb/cards/TRNA_PROCESSING ADAT1
TRNT1 FARS2
2 REGULATION_OF_BIOLOGICAL_QUALITY
http://www.broadinstitute.org/gsea/msigdb/cards/REGULATION_OF_BIOLOGICAL_QUALITY
DLC1 ALS2 SLC9A7
3 DNA_METABOLIC_PROCESS
http://www.broadinstitute.org/gsea/msigdb/cards/DNA_METABOLIC_PROCESS
XRCC5 XRCC4 RAD51C
4 AMINO_SUGAR_METABOLIC_PROCESS
http://www.broadinstitute.org/gsea/msigdb/cards/AMINO_SUGAR_METABOLIC_PROCESS
UAP1 CHIA GNPDA1
5 BIOPOLYMER_CATABOLIC_PROCESS
http://www.broadinstitute.org/gsea/msigdb/cards/BIOPOLYMER_CATABOLIC_PROCESS
BTRC HNRNPD USE1
6 RNA_METABOLIC_PROCESS
http://www.broadinstitute.org/gsea/msigdb/cards/RNA_METABOLIC_PROCESS
HNRNPF HNRNPD SYNCRIP
7 INTS6
LSM5 LSM4 LSM3 LSM1
8 CRK
9 GLUCAN_METABOLIC_PROCESS
http://www.broadinstitute.org/gsea/msigdb/cards/GLUCAN_METABOLIC_PROCESS
GCK PYGM GSK3B
10 PROTEIN_POLYUBIQUITINATION
http://www.broadinstitute.org/gsea/msigdb/cards/PROTEIN_POLYUBIQUITINATION
ERCC8 HUWE1 DZIP3
...
Partial output: last columns
V403 V404 V405 V406 V407 V408 V409 V410 V411 V412
V413 V414 V415 V416 V417 V418 V419 V420 V421
1
2 CALCA CALCB FAM107A CDK11A RASGRP4 CDK11B SYN3 GP1BA TNN ENO1
PTPRC MTL5 ISOC2 RHAG VWF GPI HPX SLC5A7 F2R
3
4
5
6 IRF2 IRF3 SLC2A4RG LSM6 XRCC6 INTS1 HOXD13 RP9 INTS2 ZNF638
INTS3 ZNF254 CITED1 CITED2 INTS9 INTS8 INTS5 INTS4 INTS7
7 POU1F1 TCF7L2 TNFRSF1A NPAS2 HAND1 HAND2 NUDT21 APEX1 ENO1 ERF
DTX1 SOX30 CBY1 DIS3 SP1 SP2 SP3 SP4 NFIC
8
9
10
For instance, column entries for row 6 gets looped to fill row 7 and row
8. I seem to only this problem for row entries with very large number of
columns. This occurs for other .txt files as well but it breaks at
different column numbers. I inspected all the row entries at where the
break happens and there are no unusual characters in the entries (they are
all standard upper case gene symbols).
I have tried both read.table and read.delim with the same result. If I
convert the .txt file to .csv first and use the same code, I do not have
this problem (see below for the equivalent output). But I don't want to
convert each file first .csv and really I just want to understand what is
going on.
Correct output if I convert to .csv file:
MSigDB.collection = read.table(fileName, header = FALSE, fill = TRUE,
as.is = TRUE, sep = ",")
V1
V2
V3 V4 V5 V6
1 TRNA_PROCESSING
http://www.broadinstitute.org/gsea/msigdb/cards/TRNA_PROCESSING ADAT1
TRNT1 FARS2 METTL1
2 REGULATION_OF_BIOLOGICAL_QUALITY
http://www.broadinstitute.org/gsea/msigdb/cards/REGULATION_OF_BIOLOGICAL_QUALITY
DLC1 ALS2 SLC9A7 PTGS2
3 DNA_METABOLIC_PROCESS
http://www.broadinstitute.org/gsea/msigdb/cards/DNA_METABOLIC_PROCESS
XRCC5 XRCC4 RAD51C XRCC3
4 AMINO_SUGAR_METABOLIC_PROCESS
http://www.broadinstitute.org/gsea/msigdb/cards/AMINO_SUGAR_METABOLIC_PROCESS
UAP1 CHIA GNPDA1 GNE
5 BIOPOLYMER_CATABOLIC_PROCESS
http://www.broadinstitute.org/gsea/msigdb/cards/BIOPOLYMER_CATABOLIC_PROCESS
BTRC HNRNPD USE1 RNASEH1
6 RNA_METABOLIC_PROCESS
http://www.broadinstitute.org/gsea/msigdb/cards/RNA_METABOLIC_PROCESS
HNRNPF HNRNPD SYNCRIP MED24
7 GLUCAN_METABOLIC_PROCESS
http://www.broadinstitute.org/gsea/msigdb/cards/GLUCAN_METABOLIC_PROCESS
GCK PYGM GSK3B EPM2A
8 PROTEIN_POLYUBIQUITINATION
http://www.broadinstitute.org/gsea/msigdb/cards/PROTEIN_POLYUBIQUITINATION
ERCC8 HUWE1 DZIP3 DDB2
9 PROTEIN_OLIGOMERIZATION
http://www.broadinstitute.org/gsea/msigdb/cards/PROTEIN_OLIGOMERIZATION
SYT1 AASS TP63 HPRT1