Stuck in grub rescue limbo- Please help
I installed ubuntu about a year ago and yesterday I deleted the partition
because my parents were annoyed with the startup menu. I didn't know I had
to fix the mbr.
Now every time I try to boot the computer the grub menu pops up and says
that the partition cannot be found. I made an ubuntu dvd but it doesn't
turn on automatically and I have no clue how to do it manually.
Please help me, I have no clue what to do.
Could someone atleast tell me how to retrieve data or documents.
Monday, 30 September 2013
How iPhone 5S can have such a big aperture=?iso-8859-1?Q?=3F_f/2.2=3F_=96_photo.stackexchange.com?=
How iPhone 5S can have such a big aperture? f/2.2? – photo.stackexchange.com
I thought that in order to have a big aperture such as f/2.2 a big amount
of light should be able to enter to the sensor and in order to do it, a
big lens was needed. How is it possible that in the …
I thought that in order to have a big aperture such as f/2.2 a big amount
of light should be able to enter to the sensor and in order to do it, a
big lens was needed. How is it possible that in the …
Is there an awk one-liner or two-liner for doing this? [merge lines and add column values]
Is there an awk one-liner or two-liner for doing this? [merge lines and
add column values]
So I have a laaaaaaaarge file like this:
Item|Cost1|Cost2
Pizza|50|25
Sugar|100|100
Spices|100|200
Pizza|100|25
Sugar|200|100
Pizza|50|100
I want to add all Cost1s and Cost2s for a particular item and produce a
merged output.
I've written a python code to do this,
item_dict = {}
for line in file:
fields = line.split('|')
item = fields[0]
cost1 = fields[1]
cost2 = fields[2]
if item_dict.has_key(item):
item_dict[item][0] += int(cost1)
item_dict[item][1] += int(cost2)
else:
item_dict[item] = [int(cost1),int(cost2)]
for key, val in item_dict.items():
print key,"|".join(val)
Is there anyway to do this very efficiently and quickly in awk or using
any other wizardry?
Or can I make my python more elegant and faster?
Expected Output
Pizza|200|150
Sugar|300|200
Spices|100|200
add column values]
So I have a laaaaaaaarge file like this:
Item|Cost1|Cost2
Pizza|50|25
Sugar|100|100
Spices|100|200
Pizza|100|25
Sugar|200|100
Pizza|50|100
I want to add all Cost1s and Cost2s for a particular item and produce a
merged output.
I've written a python code to do this,
item_dict = {}
for line in file:
fields = line.split('|')
item = fields[0]
cost1 = fields[1]
cost2 = fields[2]
if item_dict.has_key(item):
item_dict[item][0] += int(cost1)
item_dict[item][1] += int(cost2)
else:
item_dict[item] = [int(cost1),int(cost2)]
for key, val in item_dict.items():
print key,"|".join(val)
Is there anyway to do this very efficiently and quickly in awk or using
any other wizardry?
Or can I make my python more elegant and faster?
Expected Output
Pizza|200|150
Sugar|300|200
Spices|100|200
mySql: getting latest transaction made for a row from another table
mySql: getting latest transaction made for a row from another table
I'm trying to query for the last transaction made for each item on
tbl_invty that doesn't have the transaction type "Idle" from table
tbl_trans. The multiplicity of transactions is confusing me on getting my
query right and all I was able to do so far was joining the two tables
below on tbl_invty.code=tbl_trans.code. How do I go about this so I could
output only rows 2 and 3 from tbl_invty joined with rows 5 and 8 from
tbl_trans based on the column code?
tbl_invty
+------+-------------+
| CODE | DESCRIPTION |
+------+-------------+
| 1 | abc |
| 2 | bbb |
| 3 | cdf |
+------+-------------+
tbl_trans
+----------+------+--------+------------+
| TRANS_ID | CODE | TYPE | TRANS_DATE |
+----------+------+--------+------------+
| 1 | 1 | NEW | 2012-09-29 |
| 2 | 1 | UPDATE | 2012-09-30 |
| 3 | 1 | IDLE | 2012-09-30 |
| 4 | 2 | NEW | 2012-09-29 |
| 5 | 2 | UPDATE | 2012-09-30 |
| 6 | 3 | NEW | 2012-09-29 |
| 7 | 3 | UPDATE | 2012-09-30 |
| 8 | 3 | UPDATE | 2012-09-30 |
+----------+------+--------+------------+
I'm trying to query for the last transaction made for each item on
tbl_invty that doesn't have the transaction type "Idle" from table
tbl_trans. The multiplicity of transactions is confusing me on getting my
query right and all I was able to do so far was joining the two tables
below on tbl_invty.code=tbl_trans.code. How do I go about this so I could
output only rows 2 and 3 from tbl_invty joined with rows 5 and 8 from
tbl_trans based on the column code?
tbl_invty
+------+-------------+
| CODE | DESCRIPTION |
+------+-------------+
| 1 | abc |
| 2 | bbb |
| 3 | cdf |
+------+-------------+
tbl_trans
+----------+------+--------+------------+
| TRANS_ID | CODE | TYPE | TRANS_DATE |
+----------+------+--------+------------+
| 1 | 1 | NEW | 2012-09-29 |
| 2 | 1 | UPDATE | 2012-09-30 |
| 3 | 1 | IDLE | 2012-09-30 |
| 4 | 2 | NEW | 2012-09-29 |
| 5 | 2 | UPDATE | 2012-09-30 |
| 6 | 3 | NEW | 2012-09-29 |
| 7 | 3 | UPDATE | 2012-09-30 |
| 8 | 3 | UPDATE | 2012-09-30 |
+----------+------+--------+------------+
Sunday, 29 September 2013
Whats the right way to publish an Alpha / Beta Android App?
Whats the right way to publish an Alpha / Beta Android App?
I'm just getting started with writing Android apps.
I have something I want to make available to a few interested testers, but
I'm a long way from having an app. ready for the general public.
How do I make it available for testers without putting it on Play?
I'm just getting started with writing Android apps.
I have something I want to make available to a few interested testers, but
I'm a long way from having an app. ready for the general public.
How do I make it available for testers without putting it on Play?
To null check or not to do a null check?
To null check or not to do a null check?
Here is a code authored by Josh bloch, ( Linkedlist.java)
* @throws NullPointerException if the specified collection is null
*/
public boolean addAll(int index, Collection<? extends E> c) {
checkPositionIndex(index);
Object[] a = c.toArray();
int numNew = a.length;
if (numNew == 0)
return false;
Node<E> pred, succ;
if (index == size) {
succ = null;
pred = last;
} else {
succ = node(index);
pred = succ.prev;
}
Here I dont see any null ptr check for Collection c. On contrary effective
java very much stresses on parameter validation, emphasizing null pointer
check. If an invalid parameter value is passed to a method and the method
checks its parameters before execution, it will fail quickly and cleanly
with an appropriate exception.
I need to know what I am missing ? In other words why did he not do a null
check for addAll function ?
Here is a code authored by Josh bloch, ( Linkedlist.java)
* @throws NullPointerException if the specified collection is null
*/
public boolean addAll(int index, Collection<? extends E> c) {
checkPositionIndex(index);
Object[] a = c.toArray();
int numNew = a.length;
if (numNew == 0)
return false;
Node<E> pred, succ;
if (index == size) {
succ = null;
pred = last;
} else {
succ = node(index);
pred = succ.prev;
}
Here I dont see any null ptr check for Collection c. On contrary effective
java very much stresses on parameter validation, emphasizing null pointer
check. If an invalid parameter value is passed to a method and the method
checks its parameters before execution, it will fail quickly and cleanly
with an appropriate exception.
I need to know what I am missing ? In other words why did he not do a null
check for addAll function ?
gcc make install error
gcc make install error
I try to compile gcc with make install and it gives me this:
make[1]: Entering directory `/media/BOSS/sources/gcc-build'
/bin/bash ../gcc-4.8.1/mkinstalldirs /tools /tools
/bin/bash: line 3: cd: ./fixincludes: No such file or directory
make[1]: *** [install-fixincludes] Error 1
make[1]: Leaving directory `/media/BOSS/sources/gcc-build'
make: *** [install] Error 2
I am currently compiling it for lfs also I am in a seprate directory on a
32 bit computer
I try to compile gcc with make install and it gives me this:
make[1]: Entering directory `/media/BOSS/sources/gcc-build'
/bin/bash ../gcc-4.8.1/mkinstalldirs /tools /tools
/bin/bash: line 3: cd: ./fixincludes: No such file or directory
make[1]: *** [install-fixincludes] Error 1
make[1]: Leaving directory `/media/BOSS/sources/gcc-build'
make: *** [install] Error 2
I am currently compiling it for lfs also I am in a seprate directory on a
32 bit computer
Splicing together symbols with Scala macros
Splicing together symbols with Scala macros
I am trying to call a specialized collections library like FastUtil or
Trove from generic Scala code. I would like to implement something like
def openHashMap[@specialized K, @specialized V]: ${K}2${V}OpenHashMap =
new ${K}2${V}OpenHashMap()
Where the $(X} is just my notation for text substitution like shells, so
that openHashMap[Long, Double] would return a Long2DoubleOpenHashMap the
type would be known at compile time. Is this possible with Scala macros.
If so, which flavour? I know there are def macros, implicit macros, fundep
materialization, macro annotations, type macros (now discontinued) ... and
I think these are different in plain Scala-2.10, 2.10 macro paradise and
Scala-2.11. Which, if any, of these are appropriate for this?
I am trying to call a specialized collections library like FastUtil or
Trove from generic Scala code. I would like to implement something like
def openHashMap[@specialized K, @specialized V]: ${K}2${V}OpenHashMap =
new ${K}2${V}OpenHashMap()
Where the $(X} is just my notation for text substitution like shells, so
that openHashMap[Long, Double] would return a Long2DoubleOpenHashMap the
type would be known at compile time. Is this possible with Scala macros.
If so, which flavour? I know there are def macros, implicit macros, fundep
materialization, macro annotations, type macros (now discontinued) ... and
I think these are different in plain Scala-2.10, 2.10 macro paradise and
Scala-2.11. Which, if any, of these are appropriate for this?
Saturday, 28 September 2013
CodeAcademy: Just Averages
CodeAcademy: Just Averages
Thanks for your help in advance. I'm trying to get a weighted average of
these students test scores but I get the following error message from
CodeAcademy "Oops, try again! Does your get_average function take exactly
one parameter (a student)? Your code threw a "string indices must be
integers, not str" error." What are they talking about?
Specifically, I'm trying to get the average function to work.
lloyd = {
"name": "Lloyd",
"homework": [90.0, 97.0, 75.0, 92.0],
"quizzes": [88.0, 40.0, 94.0],
"tests": [75.0, 90.0]
}
alice = {
"name": "Alice",
"homework": [100.0, 92.0, 98.0, 100.0],
"quizzes": [82.0, 83.0, 91.0],
"tests": [89.0, 97.0]
}
tyler = {
"name": "Tyler",
"homework": [0.0, 87.0, 75.0, 22.0],
"quizzes": [0.0, 75.0, 78.0],
"tests": [100.0, 100.0]
}
def average(some):
return sum(some)/len(some)
students = [lloyd, alice, tyler]
def get_class_average(students):
total = 0
for student in students:
total += average(student['homework'])
return float(total) / len(students)
homework_average = get_class_average(students)
def get_average(students):
total = 0
for student in students:
total += average(student['homework'])*.1 + .6*
average(student['tests']) + .3 * average(student['quizzes'])
return (total) /len(students)
print get_average(students)
print homework_average
Thanks for your help in advance. I'm trying to get a weighted average of
these students test scores but I get the following error message from
CodeAcademy "Oops, try again! Does your get_average function take exactly
one parameter (a student)? Your code threw a "string indices must be
integers, not str" error." What are they talking about?
Specifically, I'm trying to get the average function to work.
lloyd = {
"name": "Lloyd",
"homework": [90.0, 97.0, 75.0, 92.0],
"quizzes": [88.0, 40.0, 94.0],
"tests": [75.0, 90.0]
}
alice = {
"name": "Alice",
"homework": [100.0, 92.0, 98.0, 100.0],
"quizzes": [82.0, 83.0, 91.0],
"tests": [89.0, 97.0]
}
tyler = {
"name": "Tyler",
"homework": [0.0, 87.0, 75.0, 22.0],
"quizzes": [0.0, 75.0, 78.0],
"tests": [100.0, 100.0]
}
def average(some):
return sum(some)/len(some)
students = [lloyd, alice, tyler]
def get_class_average(students):
total = 0
for student in students:
total += average(student['homework'])
return float(total) / len(students)
homework_average = get_class_average(students)
def get_average(students):
total = 0
for student in students:
total += average(student['homework'])*.1 + .6*
average(student['tests']) + .3 * average(student['quizzes'])
return (total) /len(students)
print get_average(students)
print homework_average
Overwrite all prints at the same place in perl
Overwrite all prints at the same place in perl
I want overwrite my all print result at the same place . It should not
scroll. and I want it infinite time. For that I have used while(1) and it
is working properly. But the problem is every time I print the statement ,
it scrolls down and that I want to change. I want it to print it or you
could say overwrite it at the same place.
Could some please help me with this??
I also tried to use \r in both print statements but it only updates the
last print statement at the same place.
while(1)
{
.... // some lines of code //
print("\n******** Interrupts *********\n");
for($k=0; $k<$t_intr; $k++)
{
$intr_diff = $total_intr_curr[$k] - $total_intr_prev[$k];
#push(@intr_diff_arr,$intr_diff);
print("Intr : $intr_diff\n"); // want to update this print at same
place //
}
print("\n******** Context switches *********\n");
for($l=0; $l<$t_ctxt; $l++)
{
$cntx_min = 0;
$ctxt_diff = $total_ctxt_curr - $total_ctxt_prev;
push(@ctxt_diff_arr,$ctxt_diff);
$min = min @ctxt_diff_arr;
$max = max @ctxt_diff_arr;
print("Ctxt : $ctxt_diff Minimum : $min Maximum : $max\n"); // want to
update this print also at same place //
}
}// infinite while loop end //
Thank you.
I want overwrite my all print result at the same place . It should not
scroll. and I want it infinite time. For that I have used while(1) and it
is working properly. But the problem is every time I print the statement ,
it scrolls down and that I want to change. I want it to print it or you
could say overwrite it at the same place.
Could some please help me with this??
I also tried to use \r in both print statements but it only updates the
last print statement at the same place.
while(1)
{
.... // some lines of code //
print("\n******** Interrupts *********\n");
for($k=0; $k<$t_intr; $k++)
{
$intr_diff = $total_intr_curr[$k] - $total_intr_prev[$k];
#push(@intr_diff_arr,$intr_diff);
print("Intr : $intr_diff\n"); // want to update this print at same
place //
}
print("\n******** Context switches *********\n");
for($l=0; $l<$t_ctxt; $l++)
{
$cntx_min = 0;
$ctxt_diff = $total_ctxt_curr - $total_ctxt_prev;
push(@ctxt_diff_arr,$ctxt_diff);
$min = min @ctxt_diff_arr;
$max = max @ctxt_diff_arr;
print("Ctxt : $ctxt_diff Minimum : $min Maximum : $max\n"); // want to
update this print also at same place //
}
}// infinite while loop end //
Thank you.
Convert ascii characters to normal text
Convert ascii characters to normal text
I have text like this:
‘The zoom animations everywhere on the new iOS 7 are literally
making me nauseous and giving me a headache,’wroteforumuser
Ensorceled.
I understand that #8216 is an ASCII character.How can i convert it to
normal characters without using .replace which is cumbersome.
I have text like this:
‘The zoom animations everywhere on the new iOS 7 are literally
making me nauseous and giving me a headache,’wroteforumuser
Ensorceled.
I understand that #8216 is an ASCII character.How can i convert it to
normal characters without using .replace which is cumbersome.
Compile-time Base class pointer offset to Derive class
Compile-time Base class pointer offset to Derive class
class Base1 {
int x;
};
class Base2 {
int y;
};
class Derive : public Base1, public Base2 {
public:
enum {
PTR_OFFSET = ((int) (Base2*)(Derive*)1) - 1,
};
};
But the compiler complains
expected constant expression
Everyone knows that the expression values 4 except the compiler, what goes
wrong?
How, then, to get the offset at compile time?
class Base1 {
int x;
};
class Base2 {
int y;
};
class Derive : public Base1, public Base2 {
public:
enum {
PTR_OFFSET = ((int) (Base2*)(Derive*)1) - 1,
};
};
But the compiler complains
expected constant expression
Everyone knows that the expression values 4 except the compiler, what goes
wrong?
How, then, to get the offset at compile time?
Friday, 27 September 2013
Javascript function call says undefined but function is defined
Javascript function call says undefined but function is defined
In my html I have the following function call
<input value="Roll" onclick="roll()" type="button">
which should call the function roll() that is defined as follows before:
<head>
<script language="javascript">
// roll function
// roll button pressed to roll the die and update as needed
function roll(){
wintotal = document.JForm.totalpoints.value;
var validate = Validate();
var p1total = document.JForm.p1turn.value;
var p2total = document.JForm.p2turn.value;
var dienumber = Math.floor(Math.random() * (6 - 1 +1)) + 1;
if (validate){
// put together image for die graphic that was rolled
document.getElementById("dice").innerHTML = '<img
src="die_face_'+dienumber+'.png"/>';
}
else if (validate == 0){
document.getElementById("message").innerHTML ="ERROR: Play to
points not in range";
}
else{
document.getElementById("message").innerHTML ="ERROR: Play to
points not in valid integer";
}
} // end roll function
</script>
</head><body>
however when i click the button the HTML page I get an error saying roll
is undefined even though it is clearly defined above it, anyone have any
ideas?
In my html I have the following function call
<input value="Roll" onclick="roll()" type="button">
which should call the function roll() that is defined as follows before:
<head>
<script language="javascript">
// roll function
// roll button pressed to roll the die and update as needed
function roll(){
wintotal = document.JForm.totalpoints.value;
var validate = Validate();
var p1total = document.JForm.p1turn.value;
var p2total = document.JForm.p2turn.value;
var dienumber = Math.floor(Math.random() * (6 - 1 +1)) + 1;
if (validate){
// put together image for die graphic that was rolled
document.getElementById("dice").innerHTML = '<img
src="die_face_'+dienumber+'.png"/>';
}
else if (validate == 0){
document.getElementById("message").innerHTML ="ERROR: Play to
points not in range";
}
else{
document.getElementById("message").innerHTML ="ERROR: Play to
points not in valid integer";
}
} // end roll function
</script>
</head><body>
however when i click the button the HTML page I get an error saying roll
is undefined even though it is clearly defined above it, anyone have any
ideas?
TypeError: unsupported operand type(s) for +=: 'builtin_function_or_method' and 'int'
TypeError: unsupported operand type(s) for +=:
'builtin_function_or_method' and 'int'
I am receiving this error (TypeError: unsupported operand type(s) for +=:
'builtin_function_or_method' and 'int') when trying to run this code
totalExams = 0
for totalExams in range (1, 100001):
sum += totalExams
print(sum)
sum = 0
totalExams = 0
while count <= 100000:
sum += totalExams
totalExams += 1
print(sum)
sum = int("Please enter Exam grade, or press 999 to end: ")
while true:
if sum <= 100:
sum += totalExams
totalExams += 1
elif sum == "999":
print(sum / totalExams)
over all i just need to run the program until 999 is entered, and then
find the average of all the numbers entered. At least a little help will
be nice.
'builtin_function_or_method' and 'int'
I am receiving this error (TypeError: unsupported operand type(s) for +=:
'builtin_function_or_method' and 'int') when trying to run this code
totalExams = 0
for totalExams in range (1, 100001):
sum += totalExams
print(sum)
sum = 0
totalExams = 0
while count <= 100000:
sum += totalExams
totalExams += 1
print(sum)
sum = int("Please enter Exam grade, or press 999 to end: ")
while true:
if sum <= 100:
sum += totalExams
totalExams += 1
elif sum == "999":
print(sum / totalExams)
over all i just need to run the program until 999 is entered, and then
find the average of all the numbers entered. At least a little help will
be nice.
Need Help for Salesforce ios SDK (aka i want to call login screen VC )
Need Help for Salesforce ios SDK (aka i want to call login screen VC )
I have been using the salesforce ios native sdk i have been encountering a
problem can any body help me out.I have been notified that [[[SFRestAPI
sharedInstance] coordinator] authenticate]; command would push/call the
login screen but its not.
I get the message "view is not in the window hierarchy! "
But i have instantiated the storyboard from app delegate once the user
does the authentication using following method
(UIViewController*)newRootViewController {
[self addDeviceTokenToChatter];
[self getTheUcsfUserId];
UIStoryboard *sb = [UIStoryboard storyboardWithName:@"MainStoryboard"
bundle:nil];
UINavigationController * myStoryBoardInitialViewController = [sb
instantiateInitialViewController];
return myStoryBoardInitialViewController;
}
Now i have tried logging out using the following function
-(void)logoutofTheApp
{
[[[SFRestAPI sharedInstance] coordinator] revokeAuthentication];
[[[SFRestAPI sharedInstance] coordinator] authenticate];
// [[UIApplication sharedApplication] openURL:[NSURL
URLWithString:@"prefs://"]];
}
i get this message "view is not in the window hierarchy! "
I have been using the salesforce ios native sdk i have been encountering a
problem can any body help me out.I have been notified that [[[SFRestAPI
sharedInstance] coordinator] authenticate]; command would push/call the
login screen but its not.
I get the message "view is not in the window hierarchy! "
But i have instantiated the storyboard from app delegate once the user
does the authentication using following method
(UIViewController*)newRootViewController {
[self addDeviceTokenToChatter];
[self getTheUcsfUserId];
UIStoryboard *sb = [UIStoryboard storyboardWithName:@"MainStoryboard"
bundle:nil];
UINavigationController * myStoryBoardInitialViewController = [sb
instantiateInitialViewController];
return myStoryBoardInitialViewController;
}
Now i have tried logging out using the following function
-(void)logoutofTheApp
{
[[[SFRestAPI sharedInstance] coordinator] revokeAuthentication];
[[[SFRestAPI sharedInstance] coordinator] authenticate];
// [[UIApplication sharedApplication] openURL:[NSURL
URLWithString:@"prefs://"]];
}
i get this message "view is not in the window hierarchy! "
Unique Lines and Words? How to implement it?
Unique Lines and Words? How to implement it?
I'm having trouble with this program. The program is supposed to tell the
user the number of lines, words, characters, unique lines, and unique
words there are in a given input. So far, words and characters are okay.
However, if the user wants to input more than one line, how do I do that?
The functions will only output the results of one line at a time, rather
than adding the results of both lines together. Also, I can't get the
Unique Lines and Unique Words to work properly. I just got into C++ so I
don't really have much experience. Can someone please help me?
Problems:
Program reads one line at a time, so when the user inputs multiple times,
the program produces the results separately rather than adding it together
as one entity.
Unique Lines and Unique Words are not working. Any ideas how to implement
it using the library used in the program.
Blockquote
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
#include <string>
using std::string;
#include <set>
using std::set;
// write this function to help you out with the computation.
unsigned long countLines()
{
return 1;
}
unsigned long countWords(const string& s)
{
int nw =1;
for (size_t i = 0; i < s.size(); i++)
{
if (s[i] == ' ') //everytime the function encounters a
whitespace, count increases by 1)//
{
nw++;
}
}
return nw;
}
unsigned long countChars(const string& s)
{
int nc = 0;
for (size_t i = 0; i < s.size(); i++)
{
if ( s[i] != ' ') //everytime the function encounters a character
other than a whitespace, count increases//
{
nc++;
}
}
return nc;
}
unsigned long countUnLines(const string& s, set<string>& wl)
{
/*CAT\nFOX
CAT_\n_CAT
m1 m2 m1 m2
Check for a \n character. From [h][e][l][l][o][\n][w][o][r][l][d][\0]
0 1 2 3 4 5 6 7 8 9 10 11
int m1 = 0;
int m2 = 0;
string substring;
for(m2 = 0; m2 <= s.size(); m2++){
if (m2 == '\n' || m2 == '\0'){
substring = s.substr(m1,m2);
wl.insert(substring);
m1 = m2 + 2;}
}
return wl.size();
int unl = 0;
wl.insert(s);
unl++;
return unl;
}
unsigned long countUnWords(const string& s, set<string>& wl)
{
int m1 = 0;
int m2 = 0;
string substring;
for(m2 = 0; m2 <= s.size(); m2++){
if (m2 != ' ' )
substring = s.substr(m1,m2);
wl.insert(substring);
m1 = m2 + 2;}
}
return wl.size();
int unw = 0;
wl.insert(s);
unw++;
return unw;
}
int main()
{
//stores string
string s;
//stores stats
unsigned long Lines = 0;
unsigned long Words = 0;
unsigned long Chars = 0;
unsigned long ULines = 0;
unsigned long UWords = 0;
//delcare sets
set<string> wl;
while(getline(cin,s))
{
Lines += countLines();
Words += countWords(s);
Chars += countChars(s);
ULines += countUnLines(s,wl);
UWords += countUnWords(s);
cout << Lines << endl;
cout << Words<< endl;
cout << Chars << endl;
cout << ULines << endl;
cout << UWords << endl;
Lines = 0;
Words = 0;
Chars = 0;
ULines = 0;
UWords = 0;
}
return 0;
}
I'm having trouble with this program. The program is supposed to tell the
user the number of lines, words, characters, unique lines, and unique
words there are in a given input. So far, words and characters are okay.
However, if the user wants to input more than one line, how do I do that?
The functions will only output the results of one line at a time, rather
than adding the results of both lines together. Also, I can't get the
Unique Lines and Unique Words to work properly. I just got into C++ so I
don't really have much experience. Can someone please help me?
Problems:
Program reads one line at a time, so when the user inputs multiple times,
the program produces the results separately rather than adding it together
as one entity.
Unique Lines and Unique Words are not working. Any ideas how to implement
it using the library used in the program.
Blockquote
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
#include <string>
using std::string;
#include <set>
using std::set;
// write this function to help you out with the computation.
unsigned long countLines()
{
return 1;
}
unsigned long countWords(const string& s)
{
int nw =1;
for (size_t i = 0; i < s.size(); i++)
{
if (s[i] == ' ') //everytime the function encounters a
whitespace, count increases by 1)//
{
nw++;
}
}
return nw;
}
unsigned long countChars(const string& s)
{
int nc = 0;
for (size_t i = 0; i < s.size(); i++)
{
if ( s[i] != ' ') //everytime the function encounters a character
other than a whitespace, count increases//
{
nc++;
}
}
return nc;
}
unsigned long countUnLines(const string& s, set<string>& wl)
{
/*CAT\nFOX
CAT_\n_CAT
m1 m2 m1 m2
Check for a \n character. From [h][e][l][l][o][\n][w][o][r][l][d][\0]
0 1 2 3 4 5 6 7 8 9 10 11
int m1 = 0;
int m2 = 0;
string substring;
for(m2 = 0; m2 <= s.size(); m2++){
if (m2 == '\n' || m2 == '\0'){
substring = s.substr(m1,m2);
wl.insert(substring);
m1 = m2 + 2;}
}
return wl.size();
int unl = 0;
wl.insert(s);
unl++;
return unl;
}
unsigned long countUnWords(const string& s, set<string>& wl)
{
int m1 = 0;
int m2 = 0;
string substring;
for(m2 = 0; m2 <= s.size(); m2++){
if (m2 != ' ' )
substring = s.substr(m1,m2);
wl.insert(substring);
m1 = m2 + 2;}
}
return wl.size();
int unw = 0;
wl.insert(s);
unw++;
return unw;
}
int main()
{
//stores string
string s;
//stores stats
unsigned long Lines = 0;
unsigned long Words = 0;
unsigned long Chars = 0;
unsigned long ULines = 0;
unsigned long UWords = 0;
//delcare sets
set<string> wl;
while(getline(cin,s))
{
Lines += countLines();
Words += countWords(s);
Chars += countChars(s);
ULines += countUnLines(s,wl);
UWords += countUnWords(s);
cout << Lines << endl;
cout << Words<< endl;
cout << Chars << endl;
cout << ULines << endl;
cout << UWords << endl;
Lines = 0;
Words = 0;
Chars = 0;
ULines = 0;
UWords = 0;
}
return 0;
}
I can ONLY use the "for" loop
I can ONLY use the "for" loop
How do I get an output like this? Use one and only one for loop to print
the following pattern in one dialog box. Do not use nested for loops. Use
only one for loop, not two or more. Do not use any other kind of loop. Do
not use a switch/case statement or if conditions. The same code should
work for 7 lines of asterisks or 17 lines of asterisks, simply by changing
the number of times the loop executes, from 7 to 17.
*
**
***
****
*****
******
*******
My code gives me this:
*
*
*
*
*
*
*
Here's my code:
String message7;
message7 = "";
for (count = 0; count < 8; count = count + 1)
{
message7 = message7 + "*\n";
}
JOptionPane.showMessageDialog(null,message7);
How do I get an output like this? Use one and only one for loop to print
the following pattern in one dialog box. Do not use nested for loops. Use
only one for loop, not two or more. Do not use any other kind of loop. Do
not use a switch/case statement or if conditions. The same code should
work for 7 lines of asterisks or 17 lines of asterisks, simply by changing
the number of times the loop executes, from 7 to 17.
*
**
***
****
*****
******
*******
My code gives me this:
*
*
*
*
*
*
*
Here's my code:
String message7;
message7 = "";
for (count = 0; count < 8; count = count + 1)
{
message7 = message7 + "*\n";
}
JOptionPane.showMessageDialog(null,message7);
Blinking a div with background-color in jquery using setInterval
Blinking a div with background-color in jquery using setInterval
the code :
<div id="divtoBlink" ></div>
css:
#divtoBlink{
width:100px;
height:20px;
background-color:#627BAE;
}
javascript:
setInterval(function(){
$("#divtoBlink").css("background-color","red");
},100)
but nothing is happening can anyone tell me what i am doing wrong ?
the code :
<div id="divtoBlink" ></div>
css:
#divtoBlink{
width:100px;
height:20px;
background-color:#627BAE;
}
javascript:
setInterval(function(){
$("#divtoBlink").css("background-color","red");
},100)
but nothing is happening can anyone tell me what i am doing wrong ?
WPF splashscreen active when form is loaded
WPF splashscreen active when form is loaded
I'm using a splashscreen with the following code:
var splashScreen = new SplashScreen("/Resources/enetricity.png");
splashScreen.Show(false);
InitializeComponent();
DataContext = viewModel;
// pump until loaded
PumpDispatcherUntilPriority(DispatcherPriority.Loaded);
// start a timer, after which the splash can be closed
var splashTimer = new DispatcherTimer
{
Interval = TimeSpan.FromSeconds(2)
};
splashTimer.Tick += (s, e) =>
{
splashTimer.Stop();
splashScreen.Close(splashTimer.Interval);
};
splashTimer.Start();
private static void PumpDispatcherUntilPriority(DispatcherPriority
dispatcherPriority)
{
var dispatcherFrame = new DispatcherFrame();
Dispatcher.CurrentDispatcher.BeginInvoke((ThreadStart)(() =>
dispatcherFrame.Continue = false), dispatcherPriority);
Dispatcher.PushFrame(dispatcherFrame);
}
But this is what happens: the splashscreen shows up, then the window shows
up and the splashscreen is back, and then after some time its gone. The
timer is good, when the splashscreen the second time is gone, all modules
and UI are loaded. But I don't want to see my window already.. So it
should only show up once
Greets
I'm using a splashscreen with the following code:
var splashScreen = new SplashScreen("/Resources/enetricity.png");
splashScreen.Show(false);
InitializeComponent();
DataContext = viewModel;
// pump until loaded
PumpDispatcherUntilPriority(DispatcherPriority.Loaded);
// start a timer, after which the splash can be closed
var splashTimer = new DispatcherTimer
{
Interval = TimeSpan.FromSeconds(2)
};
splashTimer.Tick += (s, e) =>
{
splashTimer.Stop();
splashScreen.Close(splashTimer.Interval);
};
splashTimer.Start();
private static void PumpDispatcherUntilPriority(DispatcherPriority
dispatcherPriority)
{
var dispatcherFrame = new DispatcherFrame();
Dispatcher.CurrentDispatcher.BeginInvoke((ThreadStart)(() =>
dispatcherFrame.Continue = false), dispatcherPriority);
Dispatcher.PushFrame(dispatcherFrame);
}
But this is what happens: the splashscreen shows up, then the window shows
up and the splashscreen is back, and then after some time its gone. The
timer is good, when the splashscreen the second time is gone, all modules
and UI are loaded. But I don't want to see my window already.. So it
should only show up once
Greets
Thursday, 26 September 2013
Call custom function inside shortcode
Call custom function inside shortcode
I have a function to display a list of files from a given directory as
links. I then have a shortcode to display the function, but I can't figure
out how to make the shortcode work without using inline php to call the
function. The shortcode only works right now because I have another
third-party plugin that allows inline php in the WordPress text editor.
Here's the function:
function showFiles($path){
if ($handle = opendir($path))
{
$up = substr($path, 0, (strrpos(dirname($path."/."),"/")));
while (false !== ($file = readdir($handle)))
{
if ($file != "." && $file != "..")
{
$fName = $file;
$file = $path.'/'.$file;
if(is_file($file)) {
echo "<li><a href='/".$file."'
target=_blank>".$fName."</a></li>";
}
}
}
closedir($handle);
}
}
And here's a pared down version of the shortcode function I'm using:
function sc_showfiles( $atts, $content = null ) {
extract( shortcode_atts( array(
'type' => '',
), $atts ) );
$showfiles = '<ul><?php
showFiles(\'files/'.$type.'files/'.do_shortcode($content).'\');
?></ul>';
return $showfiles;
}
add_shortcode('showfiles', 'sc_showfiles');
The content area allows the user to enter a shortcode with a user
generated meta so the directory it's pulling from will match the logged in
user.
I've tried about six different things, and haven't been able to achieve
this without calling the showFiles function using inline php. I came close
once using:
$files = showFiles('files/'.$type.'files/'.do_shortcode($content).);
and
$showfiles = '<ul>'.$files.'</ul>';
return $showfiles;
but that threw the list of files at the top of the page, I assume because
the original showFiles function is echoing the html output. But if I
change echo to return in the top function I get nothing.
I have a function to display a list of files from a given directory as
links. I then have a shortcode to display the function, but I can't figure
out how to make the shortcode work without using inline php to call the
function. The shortcode only works right now because I have another
third-party plugin that allows inline php in the WordPress text editor.
Here's the function:
function showFiles($path){
if ($handle = opendir($path))
{
$up = substr($path, 0, (strrpos(dirname($path."/."),"/")));
while (false !== ($file = readdir($handle)))
{
if ($file != "." && $file != "..")
{
$fName = $file;
$file = $path.'/'.$file;
if(is_file($file)) {
echo "<li><a href='/".$file."'
target=_blank>".$fName."</a></li>";
}
}
}
closedir($handle);
}
}
And here's a pared down version of the shortcode function I'm using:
function sc_showfiles( $atts, $content = null ) {
extract( shortcode_atts( array(
'type' => '',
), $atts ) );
$showfiles = '<ul><?php
showFiles(\'files/'.$type.'files/'.do_shortcode($content).'\');
?></ul>';
return $showfiles;
}
add_shortcode('showfiles', 'sc_showfiles');
The content area allows the user to enter a shortcode with a user
generated meta so the directory it's pulling from will match the logged in
user.
I've tried about six different things, and haven't been able to achieve
this without calling the showFiles function using inline php. I came close
once using:
$files = showFiles('files/'.$type.'files/'.do_shortcode($content).);
and
$showfiles = '<ul>'.$files.'</ul>';
return $showfiles;
but that threw the list of files at the top of the page, I assume because
the original showFiles function is echoing the html output. But if I
change echo to return in the top function I get nothing.
Wednesday, 25 September 2013
What's the start icon in eclipse? How to erase them?
What's the start icon in eclipse? How to erase them?
I'm using eclipse4.2.2.I cloned a repository from github and then created
a pydev project in the same directory.Here's what the navigator looks
like:
As you see,the star icons and red background color are really annoying.
Could somebody explain what those things are, and how to get rid of
them?Thank you!
I'm using eclipse4.2.2.I cloned a repository from github and then created
a pydev project in the same directory.Here's what the navigator looks
like:
As you see,the star icons and red background color are really annoying.
Could somebody explain what those things are, and how to get rid of
them?Thank you!
Thursday, 19 September 2013
How to include part of another git repository using git subtree and merge updates in both directions
How to include part of another git repository using git subtree and merge
updates in both directions
I have two git repositories show below. The first is structured like a
typical python project.
foo_repo/
.git/
setup.py
foo/
__init__.py
some_code.py
tests/
bar/
.git/
I would like to include the foo_repo/foo/ directory in bar/ as a subtree
and I want to be able to merge updates to foo_repo/foo/some_code.py both
from the foo_repo repository to bar and vice versa.
The initial setup isn't too bad. From the foo/ directory I use:
git subtree --prefix=foo/ split -b export
Then I have a new branch in foo_repo with only the contents of the
foo_repo/foo/ directory. To bring this into bar, I just go to the bar/
directory and:
git subtree --prefix=foo/ add ../foo_repo/.git export
Now that I'm all set up, I'd like to do some code development and keep
foo/ up to date in both repos. Pushing from bar I think I have figured
out. From bar/ directory:
touch foo/more_code.py
git add foo/more_code.py
git commit -m "more code"
git subtree --prefix=foo/ push ../foo_repo/.git export
Then from the foo_repo/ directory:
git checkout master
git subtree --prefix=foo/ merge export
Merging the other way is where I'm stuck. From foo_repo/:
git checkout master
touch foo/yet_more_code.py
git add foo/yet_more_code.py
git commit -m "yet more code"
???
Where the ??? is a command that merges the foo/ directory with the export
branch. Then from bar/:
git subtree --prefix=foo/ pull ../foo_repo/.git export
So I'm basically looking for the line that goes in the ??? spot, or a
different workflow that does the same thing. I've tried repeating git
subtree --prefix=foo/ split -b export_foo by that doesn't work.
updates in both directions
I have two git repositories show below. The first is structured like a
typical python project.
foo_repo/
.git/
setup.py
foo/
__init__.py
some_code.py
tests/
bar/
.git/
I would like to include the foo_repo/foo/ directory in bar/ as a subtree
and I want to be able to merge updates to foo_repo/foo/some_code.py both
from the foo_repo repository to bar and vice versa.
The initial setup isn't too bad. From the foo/ directory I use:
git subtree --prefix=foo/ split -b export
Then I have a new branch in foo_repo with only the contents of the
foo_repo/foo/ directory. To bring this into bar, I just go to the bar/
directory and:
git subtree --prefix=foo/ add ../foo_repo/.git export
Now that I'm all set up, I'd like to do some code development and keep
foo/ up to date in both repos. Pushing from bar I think I have figured
out. From bar/ directory:
touch foo/more_code.py
git add foo/more_code.py
git commit -m "more code"
git subtree --prefix=foo/ push ../foo_repo/.git export
Then from the foo_repo/ directory:
git checkout master
git subtree --prefix=foo/ merge export
Merging the other way is where I'm stuck. From foo_repo/:
git checkout master
touch foo/yet_more_code.py
git add foo/yet_more_code.py
git commit -m "yet more code"
???
Where the ??? is a command that merges the foo/ directory with the export
branch. Then from bar/:
git subtree --prefix=foo/ pull ../foo_repo/.git export
So I'm basically looking for the line that goes in the ??? spot, or a
different workflow that does the same thing. I've tried repeating git
subtree --prefix=foo/ split -b export_foo by that doesn't work.
get foreground mask with OpenCV
get foreground mask with OpenCV
BackgroundSubtractorMOG2 returns a contour of the foreground not a mask.
How to obtain a proper mask of a foreground using OpenCV?
Thanks, Sajid
BackgroundSubtractorMOG2 returns a contour of the foreground not a mask.
How to obtain a proper mask of a foreground using OpenCV?
Thanks, Sajid
Render the current page and show notice when error occurs?
Render the current page and show notice when error occurs?
I have an ActiveModel contact form in my "show" view.
My simple_form_for for however doesn't validate the fields. I saw in
another question that if we redirect, we lose the validation.
How can I stay in the same page and still show the flash notice message
when I do not fill the required fields? Something like
redirect_to :back
but with the notice.
def show
@post = Post.find(params[:id])
@message = Message.new
respond_to do |format|
format.html # show.html.erb
format.json { render json: @post }
end
end
def newmessage
@message = Message.new
end
def contact
@message = Message.new(params[:message])
@string = params[:receiver]
if @message.valid?
PostMailer.contact_poster(@message, @string).deliver
redirect_to(root_path, :notice => "Sent.")
else
flash.now[:notice] = "Error. Please fill all fields"
redirect_to(?????, :notice => "Error.")
end
end
I have an ActiveModel contact form in my "show" view.
My simple_form_for for however doesn't validate the fields. I saw in
another question that if we redirect, we lose the validation.
How can I stay in the same page and still show the flash notice message
when I do not fill the required fields? Something like
redirect_to :back
but with the notice.
def show
@post = Post.find(params[:id])
@message = Message.new
respond_to do |format|
format.html # show.html.erb
format.json { render json: @post }
end
end
def newmessage
@message = Message.new
end
def contact
@message = Message.new(params[:message])
@string = params[:receiver]
if @message.valid?
PostMailer.contact_poster(@message, @string).deliver
redirect_to(root_path, :notice => "Sent.")
else
flash.now[:notice] = "Error. Please fill all fields"
redirect_to(?????, :notice => "Error.")
end
end
Android NanoHTTPD not working
Android NanoHTTPD not working
I am trying to create a simple android server application and I am very
low on time so i thought I should give NanoHTTPD a try. I have added
NanoHTTPD.java file directly to my namespace and the following code below
works and launches perfectly but when I do an HTTP POST with a client
using asynchttp nothing happens. I am able to ping the IP and it seems to
be working.
import java.io.IOException;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import android.app.Activity;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.widget.TextView;
import com.ahmad.simplewebserver.NanoHTTPD.Response.Status;
public class MainActivity extends Activity {
private static final int PORT = 8765;
private TextView hello;
private MyHTTPD server;
private Handler handler = new Handler();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
hello = (TextView) findViewById(R.id.hello);
}
@Override
protected void onResume() {
super.onResume();
TextView textIpaddr = (TextView) findViewById(R.id.ipaddr);
WifiManager wifiManager = (WifiManager)
getSystemService(WIFI_SERVICE);
int ipAddress = wifiManager.getConnectionInfo().getIpAddress();
final String formatedIpAddress = String.format("%d.%d.%d.%d",
(ipAddress & 0xff), (ipAddress >> 8 & 0xff),
(ipAddress >> 16 & 0xff), (ipAddress >> 24 & 0xff));
textIpaddr.setText("Please access! http://" + formatedIpAddress +
":" + PORT);
try {
server = new MyHTTPD();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
protected void onPause() {
super.onPause();
if (server != null)
server.stop();
}
private class MyHTTPD extends NanoHTTPD {
public MyHTTPD() throws IOException {
super(PORT);
}
@Override
public Response serve(String uri, Method method, Map<String,
String> headers,
Map<String, String> parms, Map<String, String> files) {
Log.i("Testing", "Http Serve");
final StringBuilder buf = new StringBuilder();
for (Entry<String, String> kv : headers.entrySet())
buf.append(kv.getKey() + " : " + kv.getValue() + "\n");
handler.post(new Runnable() {
@Override
public void run() {
hello.setText(buf);
}
});
final String html = "<html><head><head><body><h1>Hello,
World</h1></body></html>";
return new NanoHTTPD.Response(Status.OK, MIME_HTML, html);
}
}
}
I am trying to create a simple android server application and I am very
low on time so i thought I should give NanoHTTPD a try. I have added
NanoHTTPD.java file directly to my namespace and the following code below
works and launches perfectly but when I do an HTTP POST with a client
using asynchttp nothing happens. I am able to ping the IP and it seems to
be working.
import java.io.IOException;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import android.app.Activity;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.widget.TextView;
import com.ahmad.simplewebserver.NanoHTTPD.Response.Status;
public class MainActivity extends Activity {
private static final int PORT = 8765;
private TextView hello;
private MyHTTPD server;
private Handler handler = new Handler();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
hello = (TextView) findViewById(R.id.hello);
}
@Override
protected void onResume() {
super.onResume();
TextView textIpaddr = (TextView) findViewById(R.id.ipaddr);
WifiManager wifiManager = (WifiManager)
getSystemService(WIFI_SERVICE);
int ipAddress = wifiManager.getConnectionInfo().getIpAddress();
final String formatedIpAddress = String.format("%d.%d.%d.%d",
(ipAddress & 0xff), (ipAddress >> 8 & 0xff),
(ipAddress >> 16 & 0xff), (ipAddress >> 24 & 0xff));
textIpaddr.setText("Please access! http://" + formatedIpAddress +
":" + PORT);
try {
server = new MyHTTPD();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
protected void onPause() {
super.onPause();
if (server != null)
server.stop();
}
private class MyHTTPD extends NanoHTTPD {
public MyHTTPD() throws IOException {
super(PORT);
}
@Override
public Response serve(String uri, Method method, Map<String,
String> headers,
Map<String, String> parms, Map<String, String> files) {
Log.i("Testing", "Http Serve");
final StringBuilder buf = new StringBuilder();
for (Entry<String, String> kv : headers.entrySet())
buf.append(kv.getKey() + " : " + kv.getValue() + "\n");
handler.post(new Runnable() {
@Override
public void run() {
hello.setText(buf);
}
});
final String html = "<html><head><head><body><h1>Hello,
World</h1></body></html>";
return new NanoHTTPD.Response(Status.OK, MIME_HTML, html);
}
}
}
Using OR in IF statement
Using OR in IF statement
I am trying to write a simple IF/Else statement. I don't want to write a
bunch of lines of If, else if, else if. I thought it would be easier to
do: "If variable = x OR y OR z, then do something, else, do something.
Below is my code. I thought I was supposed to use the "||" operator, but
the code fails to execute when I'm using it this way.
Below is my example. I created a variable named "content" that is getting
a value from a recordset. If content equals "" OR " " or is NULL, then I
want to type "Content Empty", otherwise type "Content goes here".
<?php $content = $row_rsContent['content'];
if ($content == "") || ($content == " ") || (empty($content)) {
echo "Content empty"; }
else { echo "Content goes here."; } ?>
I am trying to write a simple IF/Else statement. I don't want to write a
bunch of lines of If, else if, else if. I thought it would be easier to
do: "If variable = x OR y OR z, then do something, else, do something.
Below is my code. I thought I was supposed to use the "||" operator, but
the code fails to execute when I'm using it this way.
Below is my example. I created a variable named "content" that is getting
a value from a recordset. If content equals "" OR " " or is NULL, then I
want to type "Content Empty", otherwise type "Content goes here".
<?php $content = $row_rsContent['content'];
if ($content == "") || ($content == " ") || (empty($content)) {
echo "Content empty"; }
else { echo "Content goes here."; } ?>
Get the list ordered by how many times it appears in another table
Get the list ordered by how many times it appears in another table
I am using mysql and doctrine2.
I have two tables like these below
User.php
ID name
1 | John
2 | Jonas
3 | Nick
Class.php
ID attenduser
1 | 3
2 | 3
3 | 1
4 | 1
5 | 3
6 | 2
Class.attenduser is constraint with User.ID
it means Nick attends class three times. John two times and Jonas one time.
For now I get user list by this doctrine sql
SELECT p FROM UserBundle:User p
However,I want to get the user list ordered by how many times he attend
the class.
How should I change this?
I am using mysql and doctrine2.
I have two tables like these below
User.php
ID name
1 | John
2 | Jonas
3 | Nick
Class.php
ID attenduser
1 | 3
2 | 3
3 | 1
4 | 1
5 | 3
6 | 2
Class.attenduser is constraint with User.ID
it means Nick attends class three times. John two times and Jonas one time.
For now I get user list by this doctrine sql
SELECT p FROM UserBundle:User p
However,I want to get the user list ordered by how many times he attend
the class.
How should I change this?
PHP conditions depending on window width (media queries?)
PHP conditions depending on window width (media queries?)
I have a responsive website and I need some PHP conditions depending on
the windows width (or media queries).
Example:
if ($window_width > 1400px) {
echo 'Your window is wider than 1400px';
}
elseif ($window_width > 1000px) AND ($window_width < 1399px) {
echo 'Your window is between 1000px and 1399px';
}
else {
echo 'Your window is narrower than 1000px.';
}
Thanks for your help! I think I need some JS to detect the window width
and combine it with PHP.
I have a responsive website and I need some PHP conditions depending on
the windows width (or media queries).
Example:
if ($window_width > 1400px) {
echo 'Your window is wider than 1400px';
}
elseif ($window_width > 1000px) AND ($window_width < 1399px) {
echo 'Your window is between 1000px and 1399px';
}
else {
echo 'Your window is narrower than 1000px.';
}
Thanks for your help! I think I need some JS to detect the window width
and combine it with PHP.
Wednesday, 18 September 2013
Remove page numbers from marrangeGrob (or arrangeList) pdf
Remove page numbers from marrangeGrob (or arrangeList) pdf
marrangeGrob in the gridExtra arranges grobs (usually ggplots in my case)
in rows, columns and pages. It also numbers the pages.
require(ggplot2)
require(plyr)
require(gridExtra)
p <- function(plotdata) {
x <- ggplot(plotdata, aes(wt, mpg)) +
geom_point() +
ggtitle(plotdata$gear[1])
return(x)
}
all <- dlply(mtcars, .(gear), p)
allarranged <- do.call(marrangeGrob, c(all, nrow=1, ncol=2))
ggsave("multipage.pdf", allarranged, width=12)
That's a silly but reproducible example.
Now inspect the output of str(allarranged[[1]]) to reveal the objects of
the page numbers. Reduced to the essentials, they're here:
[[1]]
$ children :List of 5
..$GRID.frame.1925:List of 6
.. ..$ children :List of 5
.. .. ..$ GRID.cellGrob.1927:List of 10
.. .. .. ..$ children :List of 1
.. .. .. .. ..$ GRID.text.1845:List of 11
.. .. .. .. .. ..$ label : chr "page 1 of 2"
I made up the first few lines there because I'm having trouble writing the
output of str() to file. The point stands, though. $label is the
problem-child of many grandparents. There are also several $labels per
arrangelist (arrangeList is the output class of arrangeGrob).
Once you've figured out where the $labels are, then this works:
allarranged[[1]]$children$GRID.frame.1770$children$GRID.cellGrob.1772$children$GRID.text.1690$label
<- NULL
But how to predict that whole tree, or recurse through it looking for
$labels? If that weren't such an interesting problem I'd probably just
contact the gridExtra maintainer.
marrangeGrob in the gridExtra arranges grobs (usually ggplots in my case)
in rows, columns and pages. It also numbers the pages.
require(ggplot2)
require(plyr)
require(gridExtra)
p <- function(plotdata) {
x <- ggplot(plotdata, aes(wt, mpg)) +
geom_point() +
ggtitle(plotdata$gear[1])
return(x)
}
all <- dlply(mtcars, .(gear), p)
allarranged <- do.call(marrangeGrob, c(all, nrow=1, ncol=2))
ggsave("multipage.pdf", allarranged, width=12)
That's a silly but reproducible example.
Now inspect the output of str(allarranged[[1]]) to reveal the objects of
the page numbers. Reduced to the essentials, they're here:
[[1]]
$ children :List of 5
..$GRID.frame.1925:List of 6
.. ..$ children :List of 5
.. .. ..$ GRID.cellGrob.1927:List of 10
.. .. .. ..$ children :List of 1
.. .. .. .. ..$ GRID.text.1845:List of 11
.. .. .. .. .. ..$ label : chr "page 1 of 2"
I made up the first few lines there because I'm having trouble writing the
output of str() to file. The point stands, though. $label is the
problem-child of many grandparents. There are also several $labels per
arrangelist (arrangeList is the output class of arrangeGrob).
Once you've figured out where the $labels are, then this works:
allarranged[[1]]$children$GRID.frame.1770$children$GRID.cellGrob.1772$children$GRID.text.1690$label
<- NULL
But how to predict that whole tree, or recurse through it looking for
$labels? If that weren't such an interesting problem I'd probably just
contact the gridExtra maintainer.
CCNA Routing and motd banner
CCNA Routing and motd banner
I'm currently working on my CCNA 1 homework in packet tracers, I got 95
out of 100. I've been working on this for hours and could not figure out
how to get the banner motd works. I've tried these: R1-ISP(config)#banner
login [ Enter TEXT message. End with the character '['. Authorized
Personnel Only, STAY OUT! [
R1-ISP(config)#banner motd ^ Enter TEXT message. End with the character
'^'. Authorized Personnel Only, STAY OUT! ^ I've also have tried the
banner-exec and banner incoming but some how it showed me invalid
commands. Second question, I try to route Router2 to Router 1 and it wont
let me, but Router 1 to Router 2 worked. Router1: FastEthernet0/0
162.50.139.193 255.255.255.240
Serial0/0 162.50.139.209 255.255.255.252
Router2: FastEthernet0/0 162.50.139.1 255.255.255.128 Serial0/0
162.50.139.210 255.255.255.252 The command im working on is ip route I
tried: R2-MyNetwork(config)# ip route 162.50.139.193 255.255.240
162.50.139.209 and nothin happens :(
I'm currently working on my CCNA 1 homework in packet tracers, I got 95
out of 100. I've been working on this for hours and could not figure out
how to get the banner motd works. I've tried these: R1-ISP(config)#banner
login [ Enter TEXT message. End with the character '['. Authorized
Personnel Only, STAY OUT! [
R1-ISP(config)#banner motd ^ Enter TEXT message. End with the character
'^'. Authorized Personnel Only, STAY OUT! ^ I've also have tried the
banner-exec and banner incoming but some how it showed me invalid
commands. Second question, I try to route Router2 to Router 1 and it wont
let me, but Router 1 to Router 2 worked. Router1: FastEthernet0/0
162.50.139.193 255.255.255.240
Serial0/0 162.50.139.209 255.255.255.252
Router2: FastEthernet0/0 162.50.139.1 255.255.255.128 Serial0/0
162.50.139.210 255.255.255.252 The command im working on is ip route I
tried: R2-MyNetwork(config)# ip route 162.50.139.193 255.255.240
162.50.139.209 and nothin happens :(
How do I reference a file id from another Wix fragment?
How do I reference a file id from another Wix fragment?
I'm working on a Wix 3.6 installer. I've grouped all of my features into
different fragments (files). Some fragments are part of a another project
(WixLib). What I need to do is get the path of a file from another
fragment. For some reason this doesn't work. The variable is always empty.
For example, this is one of the fragments referenced from another Wix
project:
<Fragment>
<DirectoryRef Id="INSTALLLOCATION">
<Directory Id="ScriptsDir" Name="Scripts" FileSource="...">
<Component Id="ScriptsComponent" Guid="...">
<File Id="CTTEXE" Name="ctt.exe"/>
<File Name="ctt.exe.config"/>
</Component>
</Directory>
</DirectoryRef>
</Fragment>
This is how I try to access the variable:
[#CTTEXE]
I also tried referencing it as a property with PropertyRef but I get an
unresolved reference error.
What am I missing?
I'm working on a Wix 3.6 installer. I've grouped all of my features into
different fragments (files). Some fragments are part of a another project
(WixLib). What I need to do is get the path of a file from another
fragment. For some reason this doesn't work. The variable is always empty.
For example, this is one of the fragments referenced from another Wix
project:
<Fragment>
<DirectoryRef Id="INSTALLLOCATION">
<Directory Id="ScriptsDir" Name="Scripts" FileSource="...">
<Component Id="ScriptsComponent" Guid="...">
<File Id="CTTEXE" Name="ctt.exe"/>
<File Name="ctt.exe.config"/>
</Component>
</Directory>
</DirectoryRef>
</Fragment>
This is how I try to access the variable:
[#CTTEXE]
I also tried referencing it as a property with PropertyRef but I get an
unresolved reference error.
What am I missing?
How to Code phpMailer to prevent sending email if hidden field is filled in contact form
How to Code phpMailer to prevent sending email if hidden field is filled
in contact form
I like phpMailer but when I used a previous mailer it had an anti spam code.
You added a hidden field in the contact form and the mail.php script was
coded that if the hidden field was filled in (i.e. only a spam robot would
do that) the mail wouldnt send
How would I add that to this script?
This is my mail.php code as follows
<?php
// $email and $message are the data that is being
// posted to this page from our html contact form
$email = $_REQUEST['email'] ;
$message = $_REQUEST['message'] ;
$name = $_REQUEST['name'] ;
$phone = $_REQUEST['phone'] ;
$address = $_REQUEST['address'] ;
$postcode = $_REQUEST['postcode'] ;
$service = $_REQUEST['service'] ;
$height = $_REQUEST['height'] ;
$how = $_REQUEST['how'] ;
$website = $_REQUEST['website'] ;
$mail_intro ="The following enquiry came from your web site:";
// When we unzipped PHPMailer, it unzipped to
// public_html/PHPMailer_5.2.0
require("class.phpmailer.php");
$mail = new PHPMailer();
// set mailer to use SMTP
$mail->IsSMTP();
// As this email.php script lives on the same server as our email server
// we are setting the HOST to localhost
$mail->Host = "localhost"; // specify main and backup server
$mail->SMTPAuth = true; // turn on SMTP authentication
$mail->Username = "franchise@website.co.uk"; // SMTP username
$mail->Password = "passowrd"; // SMTP password
$mail->From = "noreply@website.co.uk";
$mail->FromName = "B";
$mail->AddReplyTo($email,$name);
$mail->AddAddress("franchise@website.co.uk", "B");
$mail->AddBCC("joseph@website.co.uk", "Joseph");
$response="$mail_intro\n<br />Name: $name\n<br />Email: $email\n<br
/>Phone: $phone\n<br />Address: $address\n<br /> Comments:\n$message\n<br
/> Website: $website\n";
// set word wrap to 50 characters
$mail->WordWrap = 50;
// set email format to HTML
$mail->IsHTML(true);
$mail->Subject = "Enquiry";
// $message is the user's message they typed in
// on our contact us page. We set this variable at
// the top of this page with:
// $message = $_REQUEST['message'] ;
$mail->Body = $response;
$mail->AltBody = $message;
//Autoresponder
$mailto="$email";
$subject="Franchisee Enquiry";
$body.="Thanks for your enquiry, the message below has been sent. \n";
$body.="If due to an unknown technical error you do not receive a response
within 4 hours please phone \n";
$body.="or email us directly at info@website.co.uk where we will be only
too happy to help.\n";
$body.="$mail_intro\n";
$body.="Name: $name\n";
$body.="Email: $email\n";
$body.="Phone: $phone\n";
$body.="Postcode: $postcode\n";
$body.="Service Required: $service\n";
$body.="How found: $how\n";
$body.="Comments:\n$message\n";
mail($mailto,$subject,$body,"From: noreply@website.co.uk\n");
if(!$mail->Send())
{
header("Location: http://website.co.uk/error.php");
echo "Mailer Error: " . $mail->ErrorInfo;
exit;
}
header("Location: http://website.co.uk/thankyou.php");
?>
in contact form
I like phpMailer but when I used a previous mailer it had an anti spam code.
You added a hidden field in the contact form and the mail.php script was
coded that if the hidden field was filled in (i.e. only a spam robot would
do that) the mail wouldnt send
How would I add that to this script?
This is my mail.php code as follows
<?php
// $email and $message are the data that is being
// posted to this page from our html contact form
$email = $_REQUEST['email'] ;
$message = $_REQUEST['message'] ;
$name = $_REQUEST['name'] ;
$phone = $_REQUEST['phone'] ;
$address = $_REQUEST['address'] ;
$postcode = $_REQUEST['postcode'] ;
$service = $_REQUEST['service'] ;
$height = $_REQUEST['height'] ;
$how = $_REQUEST['how'] ;
$website = $_REQUEST['website'] ;
$mail_intro ="The following enquiry came from your web site:";
// When we unzipped PHPMailer, it unzipped to
// public_html/PHPMailer_5.2.0
require("class.phpmailer.php");
$mail = new PHPMailer();
// set mailer to use SMTP
$mail->IsSMTP();
// As this email.php script lives on the same server as our email server
// we are setting the HOST to localhost
$mail->Host = "localhost"; // specify main and backup server
$mail->SMTPAuth = true; // turn on SMTP authentication
$mail->Username = "franchise@website.co.uk"; // SMTP username
$mail->Password = "passowrd"; // SMTP password
$mail->From = "noreply@website.co.uk";
$mail->FromName = "B";
$mail->AddReplyTo($email,$name);
$mail->AddAddress("franchise@website.co.uk", "B");
$mail->AddBCC("joseph@website.co.uk", "Joseph");
$response="$mail_intro\n<br />Name: $name\n<br />Email: $email\n<br
/>Phone: $phone\n<br />Address: $address\n<br /> Comments:\n$message\n<br
/> Website: $website\n";
// set word wrap to 50 characters
$mail->WordWrap = 50;
// set email format to HTML
$mail->IsHTML(true);
$mail->Subject = "Enquiry";
// $message is the user's message they typed in
// on our contact us page. We set this variable at
// the top of this page with:
// $message = $_REQUEST['message'] ;
$mail->Body = $response;
$mail->AltBody = $message;
//Autoresponder
$mailto="$email";
$subject="Franchisee Enquiry";
$body.="Thanks for your enquiry, the message below has been sent. \n";
$body.="If due to an unknown technical error you do not receive a response
within 4 hours please phone \n";
$body.="or email us directly at info@website.co.uk where we will be only
too happy to help.\n";
$body.="$mail_intro\n";
$body.="Name: $name\n";
$body.="Email: $email\n";
$body.="Phone: $phone\n";
$body.="Postcode: $postcode\n";
$body.="Service Required: $service\n";
$body.="How found: $how\n";
$body.="Comments:\n$message\n";
mail($mailto,$subject,$body,"From: noreply@website.co.uk\n");
if(!$mail->Send())
{
header("Location: http://website.co.uk/error.php");
echo "Mailer Error: " . $mail->ErrorInfo;
exit;
}
header("Location: http://website.co.uk/thankyou.php");
?>
c# webbrowser ajax document complete
c# webbrowser ajax document complete
How can I fire document loaded event when loads AJAX request? I have app,
that automaticaly open some links at one page. This links are AJAX
requests. How can I find out, that first link is loaded and I may click at
second link? Event document loaded will fire when I load first page via
navigate method. I want fire this event (or some else) when I load next
pages via AJAX request.
How can I fire document loaded event when loads AJAX request? I have app,
that automaticaly open some links at one page. This links are AJAX
requests. How can I find out, that first link is loaded and I may click at
second link? Event document loaded will fire when I load first page via
navigate method. I want fire this event (or some else) when I load next
pages via AJAX request.
PowerShell: Comparing Object stored in an array result unequal
PowerShell: Comparing Object stored in an array result unequal
In following code sample, the comparison of original object with its
stored copy in an array results in unequal status. I want to understand
this phenomena why they are not equal:
$MyArray=@()
$MyCFG="" | Select-Object -Property ProjName,ProCFG
$MyCFG.ProjName="p1"
$MyCFG.ProCFG="c1"
$MyArray+=$MyCFG.PsObject.Copy()
$MyCFG.ProjName="p2"
$MyCFG.ProCFG="c2"
$MyArray+=$MyCFG.PsObject.Copy()
$MyCFG.ProjName="p3"
$MyCFG.ProCFG="c3"
$MyArray+=$MyCFG.PsObject.Copy()
ForEach($obj in $MyArray)
{
if ($MyCFG -eq $obj)
{Write-Host "Equal"}
else
{Write-Host "Unequal"}
}
The last object values i.e. $MyCFG.ProjName="p3" and $MyCFG.ProCFG="c3"
are supposed to be same as stored in $MyArray, but they results in Unequal
as well.
Although, it can compare properly by comparing its property values i.e:
if (($MyCFG.ProjName -eq $obj.ProjName) -and ($MyCFG.ProCFG -eq $obj.ProCFG))
but wondering why Objects comparison results as unequal...
In following code sample, the comparison of original object with its
stored copy in an array results in unequal status. I want to understand
this phenomena why they are not equal:
$MyArray=@()
$MyCFG="" | Select-Object -Property ProjName,ProCFG
$MyCFG.ProjName="p1"
$MyCFG.ProCFG="c1"
$MyArray+=$MyCFG.PsObject.Copy()
$MyCFG.ProjName="p2"
$MyCFG.ProCFG="c2"
$MyArray+=$MyCFG.PsObject.Copy()
$MyCFG.ProjName="p3"
$MyCFG.ProCFG="c3"
$MyArray+=$MyCFG.PsObject.Copy()
ForEach($obj in $MyArray)
{
if ($MyCFG -eq $obj)
{Write-Host "Equal"}
else
{Write-Host "Unequal"}
}
The last object values i.e. $MyCFG.ProjName="p3" and $MyCFG.ProCFG="c3"
are supposed to be same as stored in $MyArray, but they results in Unequal
as well.
Although, it can compare properly by comparing its property values i.e:
if (($MyCFG.ProjName -eq $obj.ProjName) -and ($MyCFG.ProCFG -eq $obj.ProCFG))
but wondering why Objects comparison results as unequal...
Spring Message source wiht newlines
Spring Message source wiht newlines
I want to make a newline \n in my message source file. I tried with '\n'
but its not working. Can anybody help me ?
my text looks like:
error = User error 42 '\n' Try again!
thx
I want to make a newline \n in my message source file. I tried with '\n'
but its not working. Can anybody help me ?
my text looks like:
error = User error 42 '\n' Try again!
thx
Primefaces 4.0 RC1 Terminal can't render CRLF char
Primefaces 4.0 RC1 Terminal can't render CRLF char
I want display the terminal response strings that contain "\r\n" (CRLF). I
expect the following code output "AAA" "BBB" in seperated line, but it
always displayed in same line. the CRLF char being removed by terminal
render.
I'm using primeface 4.0 RC1.
Any suggestion to solve this issue ? thanks
<p:terminal id="terminal" widgetVar="term"
commandHandler="#{terminalController.handleCommand}" prompt="ssh$"
welcomeMessage="Welcome to SSH Terminal." />
public class TerminalController {
public TerminalController() {}
public String handleCommand(String command, String[] params) {
StringBuilder ret = new StringBuilder();
ret.append("AAA");
ret.append(" "); // ret.append("\n\r");
ret.append("BBB");
return ret.toString();
} }
I want display the terminal response strings that contain "\r\n" (CRLF). I
expect the following code output "AAA" "BBB" in seperated line, but it
always displayed in same line. the CRLF char being removed by terminal
render.
I'm using primeface 4.0 RC1.
Any suggestion to solve this issue ? thanks
<p:terminal id="terminal" widgetVar="term"
commandHandler="#{terminalController.handleCommand}" prompt="ssh$"
welcomeMessage="Welcome to SSH Terminal." />
public class TerminalController {
public TerminalController() {}
public String handleCommand(String command, String[] params) {
StringBuilder ret = new StringBuilder();
ret.append("AAA");
ret.append(" "); // ret.append("\n\r");
ret.append("BBB");
return ret.toString();
} }
Tuesday, 17 September 2013
How do I make the algorithm wait, so that all the machines handle the requests they are entitled to handle?
How do I make the algorithm wait, so that all the machines handle the
requests they are entitled to handle?
Following is a method that allocates machines in a round-robin order. A
machine is allocated(or returned) if it is not busy and
current-allocations for that machine doesn't exceed maximum-allocations
allowed for the machine.
A list named busyList is maintained that tells if the machine is busy or
is available.This list is automatically updated when a machine is freed or
is booked.
There is a bug in the following method. If at any point of time all the
machines come busy,instead of waiting for a machine to be available it
starts the round-robin from 0. It means it resets the allocation counters
for all the machines.This is wrong ! Next circle of round robin should
only start when, in the current circle all the machines have handled the
requests they are meant to handle.
@Override
public int getNextAvailableVm() {
synchronized(this) {
int machineID;
VmAllocation allocation;
for(Map.Entry<Integer,VmAllocation> entry : allMap.entrySet()) {
machineID = (Integer)(entry.getKey());
allocation = (VmAllocation)(entry.getValue());
if(!busyList.contains(machineID) &&
allocation.getCurrAlloc() < allocation.getMaxAlloc()) {
allocation.setCurrAlloc(allocation.getCurrAlloc() + 1);
return machineID;
}
}
for(Map.Entry<Integer, VmAllocation> entry: allMap.entrySet()) {
allocation = (VmAllocation)(entry.getValue());
allocation.setCurrAlloc(0);
}
allocation = (VmAllocation)allMap.get(0);
allocation.setCurrAlloc(1);
}
return 0;
}
How do I implement this logic ? I want that every machine should handle
the tasks they are entitled to handle before the starting the round-robin
circle again
Note : This method is called multiple times from another class.
requests they are entitled to handle?
Following is a method that allocates machines in a round-robin order. A
machine is allocated(or returned) if it is not busy and
current-allocations for that machine doesn't exceed maximum-allocations
allowed for the machine.
A list named busyList is maintained that tells if the machine is busy or
is available.This list is automatically updated when a machine is freed or
is booked.
There is a bug in the following method. If at any point of time all the
machines come busy,instead of waiting for a machine to be available it
starts the round-robin from 0. It means it resets the allocation counters
for all the machines.This is wrong ! Next circle of round robin should
only start when, in the current circle all the machines have handled the
requests they are meant to handle.
@Override
public int getNextAvailableVm() {
synchronized(this) {
int machineID;
VmAllocation allocation;
for(Map.Entry<Integer,VmAllocation> entry : allMap.entrySet()) {
machineID = (Integer)(entry.getKey());
allocation = (VmAllocation)(entry.getValue());
if(!busyList.contains(machineID) &&
allocation.getCurrAlloc() < allocation.getMaxAlloc()) {
allocation.setCurrAlloc(allocation.getCurrAlloc() + 1);
return machineID;
}
}
for(Map.Entry<Integer, VmAllocation> entry: allMap.entrySet()) {
allocation = (VmAllocation)(entry.getValue());
allocation.setCurrAlloc(0);
}
allocation = (VmAllocation)allMap.get(0);
allocation.setCurrAlloc(1);
}
return 0;
}
How do I implement this logic ? I want that every machine should handle
the tasks they are entitled to handle before the starting the round-robin
circle again
Note : This method is called multiple times from another class.
Hot reload external js file in node.js if there's any changes to the file
Hot reload external js file in node.js if there's any changes to the file
Is it possible to hot reload external js files in node.js based on its
timestamp?
I know node.js caches module after first time load from here:
http://nodejs.org/docs/latest/api/modules.html#modules_caching
Modules are cached after the first time they are loaded. This means (among
other things) that every call to require('foo') will get exactly the same
object returned, if it would resolve to the same file.
And I also know if I need to reload it I can do like this:
// first time load
var foo = require('./foo');
foo.bar()
...
// in case need to reload
delete require.cache[require;.resolve('./foo')]
foo = require('./foo')
foo.bar();
But I wonder if there's any native support in node.js that it watches the
file and reload it if there's any changes. Or I need to do it by myself?
pseudo code like
// during reload
if (timestamp for last loaded < file modified time)
reload the file as above and return
else
return cached required file
P.S. I am aware of supervisor and nodemon and don't want to restart server
for reloading modules.
Is it possible to hot reload external js files in node.js based on its
timestamp?
I know node.js caches module after first time load from here:
http://nodejs.org/docs/latest/api/modules.html#modules_caching
Modules are cached after the first time they are loaded. This means (among
other things) that every call to require('foo') will get exactly the same
object returned, if it would resolve to the same file.
And I also know if I need to reload it I can do like this:
// first time load
var foo = require('./foo');
foo.bar()
...
// in case need to reload
delete require.cache[require;.resolve('./foo')]
foo = require('./foo')
foo.bar();
But I wonder if there's any native support in node.js that it watches the
file and reload it if there's any changes. Or I need to do it by myself?
pseudo code like
// during reload
if (timestamp for last loaded < file modified time)
reload the file as above and return
else
return cached required file
P.S. I am aware of supervisor and nodemon and don't want to restart server
for reloading modules.
Start another node application using node.js?
Start another node application using node.js?
I have two separate node applications. I'd like one of them to be able to
start the other one at some point in the code. How would I go about doing
this?
I have two separate node applications. I'd like one of them to be able to
start the other one at some point in the code. How would I go about doing
this?
Adding together timedeta's in Python
Adding together timedeta's in Python
So I have this list:
[datetime.timedelta(0, 1800), datetime.timedelta(0, 1800),
datetime.timedelta(0, 1800), datetime.timedelta(0, 1800)]
Collectively that is 2:00 hours, I'm trying to add those up to get 2:00
time delta. Which then in turn needs to be turned into a string of 2.0
Hours. Respectively 1:30 Hours would be 1.5 Hours as the final countdown.
So I have this list:
[datetime.timedelta(0, 1800), datetime.timedelta(0, 1800),
datetime.timedelta(0, 1800), datetime.timedelta(0, 1800)]
Collectively that is 2:00 hours, I'm trying to add those up to get 2:00
time delta. Which then in turn needs to be turned into a string of 2.0
Hours. Respectively 1:30 Hours would be 1.5 Hours as the final countdown.
nodejs express 3 framework session destroying issue
nodejs express 3 framework session destroying issue
I'm using nodejs with Express 3 framework and I have an issue with
deleting one specific session, here is the code I'm using :
app.js
var express = require('express');
................
................
app.use(express.cookieParser());
app.use(express.session({secret : 'asxcfrgth'}));
app.use(app.router);
app.get('/User', function(req, res){
req.session.login = "Invalid username";
req.session.password= "Invalid password";
console.log(req.session.login);
console.log(req.session.password);
req.session.destroy();
});
req.session.destroy will delete all my sessions so is there a way to only
destroy the first session and leave the second one? I want to avoid using
this :
req.session.login ="";
to empty the session variable, Thanks.
I'm using nodejs with Express 3 framework and I have an issue with
deleting one specific session, here is the code I'm using :
app.js
var express = require('express');
................
................
app.use(express.cookieParser());
app.use(express.session({secret : 'asxcfrgth'}));
app.use(app.router);
app.get('/User', function(req, res){
req.session.login = "Invalid username";
req.session.password= "Invalid password";
console.log(req.session.login);
console.log(req.session.password);
req.session.destroy();
});
req.session.destroy will delete all my sessions so is there a way to only
destroy the first session and leave the second one? I want to avoid using
this :
req.session.login ="";
to empty the session variable, Thanks.
Sunday, 15 September 2013
How to keep double quotes from being sanitized in a jQuery ajax request?
How to keep double quotes from being sanitized in a jQuery ajax request?
What I essentially need to do is pass something along the lines of this
through an ajax request:
http://www.somesite.com/?q="something here"
The problem is that when the request is sent, the "s become %22 which
doesn't work for what I'm trying to do.
What I essentially need to do is pass something along the lines of this
through an ajax request:
http://www.somesite.com/?q="something here"
The problem is that when the request is sent, the "s become %22 which
doesn't work for what I'm trying to do.
Will this while loop end when the if statement inside is met
Will this while loop end when the if statement inside is met
I have this block of function that searches through my email column for
matches. After a match has been found, will this While loop continue to
search for other matches or will it end if the if statement inside it is
met?
function find_similar_email ($email) {
global $con;
// select db
mysql_select_db('practice', $con);
// select a column to search from
$emailList = mysql_query("SELECT email FROM users", $con);
// search for similar matches
while ($emailListResult = mysql_fetch_array($emailList)) {
if ($email == $emailListResult['email']) {
return TRUE;
}
}
}
I have this block of function that searches through my email column for
matches. After a match has been found, will this While loop continue to
search for other matches or will it end if the if statement inside it is
met?
function find_similar_email ($email) {
global $con;
// select db
mysql_select_db('practice', $con);
// select a column to search from
$emailList = mysql_query("SELECT email FROM users", $con);
// search for similar matches
while ($emailListResult = mysql_fetch_array($emailList)) {
if ($email == $emailListResult['email']) {
return TRUE;
}
}
}
Grails webflow - Swapping Webflows in the same session
Grails webflow - Swapping Webflows in the same session
I have a Grails application with two webflows:
One for Purchasing
Another for getting in Contact with us
The issue:
It can happen that a user has a number of steps taken in a purchase wizard
(via a webflow), he/she then decides they have a question and try to
contact us (also via a webflow). So the user clicks on the 'contact-us'
link on our navigation menu but they get brought back to the last step
they were on in the purchase flow. Personally I assume it's got to do with
the 'execution' key in the session which every link gets postfixed with
i.e.
...../contact_us/index?execution=e1s1
The solution I would like:
I would like (in the above case), if the user decides himself to swap from
the 'purchase flow' to the 'contact-us flow' that the 'purchase flow' gets
invalidated/removed and the user begins from scratch in the 'contact-us
flow'.
Grails version 2.2.3 Webflow plugin: 2.0.8.1
The best solution I could come up with (without doing something too ugly)
was to create a filter that intercepts when a link has been clicked to
start a new flow and attempts to remove the other one. However, in this
example it surprisingly fails to find the flow in the flow repository
(nullpointer).
FlowExecutionLock flowExecutionLock = null;
SessionBindingConversationManager conversationManager =
applicationContext.getBean('conversationManager');
DefaultFlowExecutionRepository flowExecutionRepository =
applicationContext.getBean("flowExecutionRepository");
try {
// executionKey is something like 'e1s1'
FlowExecutionKey flowExecutionKey =
flowExecutionRepository.parseFlowExecutionKey(executionKey);
flowExecutionLock = flowExecutionRepository.getLock(flowExecutionKey);
flowExecutionLock.lock();
FlowExecution execution =
flowExecutionRepository.getFlowExecution(flowExecutionKey);
flowExecutionRepository.removeFlowExecution(execution);
} catch (FlowExecutionRepositoryException e) {
log.warn("Could not find flow in repository with id ${executionKey} "
+ e.getMessage());
} catch (NullPointerException e) {
log.warn("Could not find flow in repository with id ${executionKey} "
+ e.getMessage());
} finally {
if (flowExecutionLock != null) {
flowExecutionLock.unlock();
}
}
Has anybody got any ideas how I could do this. Swapping between two flows
(where one is incomplete) in a session should be possible right? I'd like
a clean solution to this rather than tweaking the flows themselves.
I have a Grails application with two webflows:
One for Purchasing
Another for getting in Contact with us
The issue:
It can happen that a user has a number of steps taken in a purchase wizard
(via a webflow), he/she then decides they have a question and try to
contact us (also via a webflow). So the user clicks on the 'contact-us'
link on our navigation menu but they get brought back to the last step
they were on in the purchase flow. Personally I assume it's got to do with
the 'execution' key in the session which every link gets postfixed with
i.e.
...../contact_us/index?execution=e1s1
The solution I would like:
I would like (in the above case), if the user decides himself to swap from
the 'purchase flow' to the 'contact-us flow' that the 'purchase flow' gets
invalidated/removed and the user begins from scratch in the 'contact-us
flow'.
Grails version 2.2.3 Webflow plugin: 2.0.8.1
The best solution I could come up with (without doing something too ugly)
was to create a filter that intercepts when a link has been clicked to
start a new flow and attempts to remove the other one. However, in this
example it surprisingly fails to find the flow in the flow repository
(nullpointer).
FlowExecutionLock flowExecutionLock = null;
SessionBindingConversationManager conversationManager =
applicationContext.getBean('conversationManager');
DefaultFlowExecutionRepository flowExecutionRepository =
applicationContext.getBean("flowExecutionRepository");
try {
// executionKey is something like 'e1s1'
FlowExecutionKey flowExecutionKey =
flowExecutionRepository.parseFlowExecutionKey(executionKey);
flowExecutionLock = flowExecutionRepository.getLock(flowExecutionKey);
flowExecutionLock.lock();
FlowExecution execution =
flowExecutionRepository.getFlowExecution(flowExecutionKey);
flowExecutionRepository.removeFlowExecution(execution);
} catch (FlowExecutionRepositoryException e) {
log.warn("Could not find flow in repository with id ${executionKey} "
+ e.getMessage());
} catch (NullPointerException e) {
log.warn("Could not find flow in repository with id ${executionKey} "
+ e.getMessage());
} finally {
if (flowExecutionLock != null) {
flowExecutionLock.unlock();
}
}
Has anybody got any ideas how I could do this. Swapping between two flows
(where one is incomplete) in a session should be possible right? I'd like
a clean solution to this rather than tweaking the flows themselves.
Net::SSH does not seem to connect to remote host
Net::SSH does not seem to connect to remote host
Net::SSH.start('remotehost', 'ava') do |ssh|
puts `hostname`
end
It prints the name of current hostname rather than remote hostname. What
is wrong?
Net::SSH.start('remotehost', 'ava') do |ssh|
puts `hostname`
end
It prints the name of current hostname rather than remote hostname. What
is wrong?
How to call the existing object in python
How to call the existing object in python
I have this kind of code.
class typeOne(self):
....
def run():
# I want to call the funct() from typeTwo
class typeTwo(self):
...
def funct():
...
class typePlayer(self):
...
tT = typeTwo()
...
tT.funct()
.....
I want to reference the typeTwo class from typeOne class that has been
called in the typePlayer.
I tried this one.
class typeOne:
....
mytT = typeTwo()
def run():
mytT.funct()
but it creates new typeTwo() class, I just only want to call the existing
typeTwo() class and not to create one.
does anyone has an idea about this?
I have this kind of code.
class typeOne(self):
....
def run():
# I want to call the funct() from typeTwo
class typeTwo(self):
...
def funct():
...
class typePlayer(self):
...
tT = typeTwo()
...
tT.funct()
.....
I want to reference the typeTwo class from typeOne class that has been
called in the typePlayer.
I tried this one.
class typeOne:
....
mytT = typeTwo()
def run():
mytT.funct()
but it creates new typeTwo() class, I just only want to call the existing
typeTwo() class and not to create one.
does anyone has an idea about this?
Using NSKeyedArchiver/Unarchiver in custom getter/setter methods
Using NSKeyedArchiver/Unarchiver in custom getter/setter methods
I'm trying to use a NSKeyedArchiver/NSKeyedUnarchiver to store data for a
class's property in a file in order to persist the state of the property
between launches of the app.
I have the property declared in MyClass.h like so:
@property (nonatomic, weak) NSDictionary *myDictionary;
and I've created custom getter and setter methods in MyClass.m to make
sure the NSDictionary is written to disk:
-(NSDictionary *)myDictionary {
NSDictionary *dictionary;
NSString *path = [self pathToDataStore];
if (![[NSFileManager defaultManager] fileExistsAtPath:path]) {
dictionary = [NSDictionary dictionary];
} else {
NSData *archivedData = [NSData dataWithContentsOfFile:path];
dictionary = [NSKeyedUnarchiver
unarchiveObjectWithData:archivedData];
}
return dictionary;
}
-(void)setMyDictionary:(NSDictionary *)dictionary {
NSString *path = [self pathToDataStore];
NSDictionary *rootObject = [NSDictionary
dictionaryWithDictionary:dictionary];
[NSKeyedArchiver archiveRootObject:rootObject toFile:path];
self.myDictionary = dictionary;
}
This is causing an infinite loop of calls to [self setMyDictionary], so
clearly I'm doing something wrong.
Anybody have any advice on this? Where am I going wrong? Thanks!
I'm trying to use a NSKeyedArchiver/NSKeyedUnarchiver to store data for a
class's property in a file in order to persist the state of the property
between launches of the app.
I have the property declared in MyClass.h like so:
@property (nonatomic, weak) NSDictionary *myDictionary;
and I've created custom getter and setter methods in MyClass.m to make
sure the NSDictionary is written to disk:
-(NSDictionary *)myDictionary {
NSDictionary *dictionary;
NSString *path = [self pathToDataStore];
if (![[NSFileManager defaultManager] fileExistsAtPath:path]) {
dictionary = [NSDictionary dictionary];
} else {
NSData *archivedData = [NSData dataWithContentsOfFile:path];
dictionary = [NSKeyedUnarchiver
unarchiveObjectWithData:archivedData];
}
return dictionary;
}
-(void)setMyDictionary:(NSDictionary *)dictionary {
NSString *path = [self pathToDataStore];
NSDictionary *rootObject = [NSDictionary
dictionaryWithDictionary:dictionary];
[NSKeyedArchiver archiveRootObject:rootObject toFile:path];
self.myDictionary = dictionary;
}
This is causing an infinite loop of calls to [self setMyDictionary], so
clearly I'm doing something wrong.
Anybody have any advice on this? Where am I going wrong? Thanks!
DatagramPacket on MulticastSocket
DatagramPacket on MulticastSocket
Im trying to Send out a DatagramPacket on a MulticastSocket. This bit is
working but when i try and get the info out of the header its not working.
while(true){
byte[] packet = new byte[1500];
DatagramPacket packetR = new DatagramPacket(packet, packet.length);
socketM.receive(packetR);
ByteBuffer data = ByteBuffer.wrap(packetR.getData());
byte[] senderAddress = new byte[100];
byte[] senderCommand =new byte[100];
data.get(senderAddress,0,4);
InetAddress senderIP = InetAddress.getByAddress(senderAddress);
data.position(4);
data.get(senderCommand,0,1);
String command = (char)senderCommand[0]+"";
System.out.print(senderIP+": "+ command+"\n");
}
This works but i just get all of it printed out
while(true){
byte[] packet = new byte[100];
DatagramPacket packetR = new DatagramPacket(packet, packet.length);
socketM.receive(packetR);
InetAddress ip = packetR.getAddress();
String meg = new String(packetR.getData());
System.out.print(ip+": "+ meg+"\n");
}
Can anyone see why this would not work thanks.
Im trying to Send out a DatagramPacket on a MulticastSocket. This bit is
working but when i try and get the info out of the header its not working.
while(true){
byte[] packet = new byte[1500];
DatagramPacket packetR = new DatagramPacket(packet, packet.length);
socketM.receive(packetR);
ByteBuffer data = ByteBuffer.wrap(packetR.getData());
byte[] senderAddress = new byte[100];
byte[] senderCommand =new byte[100];
data.get(senderAddress,0,4);
InetAddress senderIP = InetAddress.getByAddress(senderAddress);
data.position(4);
data.get(senderCommand,0,1);
String command = (char)senderCommand[0]+"";
System.out.print(senderIP+": "+ command+"\n");
}
This works but i just get all of it printed out
while(true){
byte[] packet = new byte[100];
DatagramPacket packetR = new DatagramPacket(packet, packet.length);
socketM.receive(packetR);
InetAddress ip = packetR.getAddress();
String meg = new String(packetR.getData());
System.out.print(ip+": "+ meg+"\n");
}
Can anyone see why this would not work thanks.
Saturday, 14 September 2013
How to dynamicaly change data in dropdown on chnage of text box Jquery
How to dynamicaly change data in dropdown on chnage of text box Jquery
I have a text box and dropdown. Text box contains the province name and
the dropdown contains the the cities. I want to chnage the province of the
text box and dynamically change the dropdown related to the text in the
textbox. I am using codeigniter framework. My view is as follows and I get
the data from the database. I think there is a problem with the onchange
or that kind of event of the text box (this code worked for change event
for another dropdown. But it is not working for the taxt box- so the other
logic is ok but I cant figure out the event of the textbox. What is the
right event for the text box ? My code
<script> .........................<script>
$(document).ready(function(){
$('#provincial').on('input',function()
{
var id_provincia = $('#provincial').val();
$.ajax(
{
type: "POST",
dataType: "json", // I ADDED THIS LINE
url:"tenda/get_comuni/"+id_provincia,
success: function(comuni)
{
$('#comuni').empty();
$.each(comuni,function(id_comune, nome_comune)
{
var opt = $('<option />');
opt.val(id_comune);
opt.text(nome_comune);
$('#comuni').append(opt);
});
}
});
});
});
</script>
</head>
provincia: comune:
I have a text box and dropdown. Text box contains the province name and
the dropdown contains the the cities. I want to chnage the province of the
text box and dynamically change the dropdown related to the text in the
textbox. I am using codeigniter framework. My view is as follows and I get
the data from the database. I think there is a problem with the onchange
or that kind of event of the text box (this code worked for change event
for another dropdown. But it is not working for the taxt box- so the other
logic is ok but I cant figure out the event of the textbox. What is the
right event for the text box ? My code
<script> .........................<script>
$(document).ready(function(){
$('#provincial').on('input',function()
{
var id_provincia = $('#provincial').val();
$.ajax(
{
type: "POST",
dataType: "json", // I ADDED THIS LINE
url:"tenda/get_comuni/"+id_provincia,
success: function(comuni)
{
$('#comuni').empty();
$.each(comuni,function(id_comune, nome_comune)
{
var opt = $('<option />');
opt.val(id_comune);
opt.text(nome_comune);
$('#comuni').append(opt);
});
}
});
});
});
</script>
</head>
provincia: comune:
What does the "Just" syntax mean in Haskell?
What does the "Just" syntax mean in Haskell?
I have scoured the internet for an actual explanation of what this keyword
does. Every Haskell tutorial that I have looked at just starts using it
randomly and never explains what it does (and I've looked at many).
Here's a basic piece of code from Real World Haskell that uses Just. I
understand what the code does, but I don't understand what the purpose or
function of "Just" is.
lend amount balance = let reserve = 100
newBalance = balance - amount
in if balance < reserve
then Nothing
else Just newBalance
From what I have observed, it is related to "Maybe" typing, but that's
pretty much all I have managed to learn.
A good explanation of what Just means would be very much appreciated.
I have scoured the internet for an actual explanation of what this keyword
does. Every Haskell tutorial that I have looked at just starts using it
randomly and never explains what it does (and I've looked at many).
Here's a basic piece of code from Real World Haskell that uses Just. I
understand what the code does, but I don't understand what the purpose or
function of "Just" is.
lend amount balance = let reserve = 100
newBalance = balance - amount
in if balance < reserve
then Nothing
else Just newBalance
From what I have observed, it is related to "Maybe" typing, but that's
pretty much all I have managed to learn.
A good explanation of what Just means would be very much appreciated.
sqlalchemy foreign key relationship attributes
sqlalchemy foreign key relationship attributes
I have a User table and a Friend table. The Friend table holds two foreign
keys both to my User table as well as a status field. I am trying to be
able to call attributes from my User table on a Friend object. For
example, I would love to be able to do something like, friend.name, or
friend.email.
class User(Base):
""" Holds user info """
__tablename__ = 'user'
id = Column(Integer, primary_key=True)
name = Column(String(25), unique=True)
email = Column(String(50), unique=True)
password = Column(String(25))
admin = Column(Boolean)
# relationships
friends = relationship('Friend', backref='Friend.friend_id',
primaryjoin='User.id==Friend.user_id', lazy='dynamic')
class Friend(Base):
__tablename__ = 'friend'
user_id = Column(Integer, ForeignKey(User.id), primary_key=True)
friend_id = Column(Integer, ForeignKey(User.id), primary_key=True)
request_status = Column(Boolean)
When I get friend objects all I have is the 2 user_ids and i want to
display all properties of each user so I can use that information in
forms, etc. I am not to sqlalchemy - still trying to learn more advanced
features. This is just a snippet from a larger Flask project and this
feature is going to be for 'friend' requests, etc. I've tried to look up
association objects, etc, but I am having a hard with it.
Any help would be greatly appreciated.
I have a User table and a Friend table. The Friend table holds two foreign
keys both to my User table as well as a status field. I am trying to be
able to call attributes from my User table on a Friend object. For
example, I would love to be able to do something like, friend.name, or
friend.email.
class User(Base):
""" Holds user info """
__tablename__ = 'user'
id = Column(Integer, primary_key=True)
name = Column(String(25), unique=True)
email = Column(String(50), unique=True)
password = Column(String(25))
admin = Column(Boolean)
# relationships
friends = relationship('Friend', backref='Friend.friend_id',
primaryjoin='User.id==Friend.user_id', lazy='dynamic')
class Friend(Base):
__tablename__ = 'friend'
user_id = Column(Integer, ForeignKey(User.id), primary_key=True)
friend_id = Column(Integer, ForeignKey(User.id), primary_key=True)
request_status = Column(Boolean)
When I get friend objects all I have is the 2 user_ids and i want to
display all properties of each user so I can use that information in
forms, etc. I am not to sqlalchemy - still trying to learn more advanced
features. This is just a snippet from a larger Flask project and this
feature is going to be for 'friend' requests, etc. I've tried to look up
association objects, etc, but I am having a hard with it.
Any help would be greatly appreciated.
Compute value entered in textbox and place in another textbox?
Compute value entered in textbox and place in another textbox?
I have a form with two text boxes. I want to enter a number on one box,
press the Convert link, and have it compute the number in the first box to
Celsius and place it in the second text box. So far it isn't working and I
feel like there's something small I'm missing... What can I do?
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<style type="text/css">
body
{
background-color: white;
}
h2
{
position: absolute;
left:200px;
top:5px;
color: cadetblue;
}
p
{
text-align: center;
font-family: times new roman;
color: black;
}
</style>
<script>
function f2cCalc(input)
{
var fbox = document.getElementById(input);
var cbox = document.getElementById(cinput);
var f = parseInt(fbox.value);
var cel = Math.round(5/9*(f-32));
document.getElementById(cbox).value=cel;
}
function changeText(inId, txt)
{
var t = document.getElementById(inId);
if(t!=null)
{
t.innerHTML=txt;
}
}
</script>
</head>
<body>
<form method="get" action="">
<h2>Temp calculator</h2>
<br />
<br />
<br/>
<br/>
<br/>
F<input id="finput" type="number" STYLE="background-color:
cadetblue; color: green;" value="0"/>
C<input id="cinput" type="number" STYLE="background-color:
cadetblue; color: green;" value="0"/>
<a href="javascript:f2cCalc(finput)">Convert</a>
</form>
</body>
</html>
enter code here
I have a form with two text boxes. I want to enter a number on one box,
press the Convert link, and have it compute the number in the first box to
Celsius and place it in the second text box. So far it isn't working and I
feel like there's something small I'm missing... What can I do?
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<style type="text/css">
body
{
background-color: white;
}
h2
{
position: absolute;
left:200px;
top:5px;
color: cadetblue;
}
p
{
text-align: center;
font-family: times new roman;
color: black;
}
</style>
<script>
function f2cCalc(input)
{
var fbox = document.getElementById(input);
var cbox = document.getElementById(cinput);
var f = parseInt(fbox.value);
var cel = Math.round(5/9*(f-32));
document.getElementById(cbox).value=cel;
}
function changeText(inId, txt)
{
var t = document.getElementById(inId);
if(t!=null)
{
t.innerHTML=txt;
}
}
</script>
</head>
<body>
<form method="get" action="">
<h2>Temp calculator</h2>
<br />
<br />
<br/>
<br/>
<br/>
F<input id="finput" type="number" STYLE="background-color:
cadetblue; color: green;" value="0"/>
C<input id="cinput" type="number" STYLE="background-color:
cadetblue; color: green;" value="0"/>
<a href="javascript:f2cCalc(finput)">Convert</a>
</form>
</body>
</html>
enter code here
Connecting to mySQL Database with Java
Connecting to mySQL Database with Java
In my program I am trying to connect to a mySQL database. This program is
written in Java.
I am trying to connect to my database with this code here (? is a place
holder b/c I dont know what does there.)
Connection conn = DriverManager.getConnection("jdbc:sqlite:*?*");
I need someone to help me replace the ? to connect to my database. I know
the IP (Just call it ..* for security reasons, the port which is 3306 and
the database is called devicede_Test).
Please help me replace the ? with the correct string with the info above,
thanks!
In my program I am trying to connect to a mySQL database. This program is
written in Java.
I am trying to connect to my database with this code here (? is a place
holder b/c I dont know what does there.)
Connection conn = DriverManager.getConnection("jdbc:sqlite:*?*");
I need someone to help me replace the ? to connect to my database. I know
the IP (Just call it ..* for security reasons, the port which is 3306 and
the database is called devicede_Test).
Please help me replace the ? with the correct string with the info above,
thanks!
MySQL : Multiple counts in one query
MySQL : Multiple counts in one query
I have a table of products. Every product has a company and a worker of
that company that produces it.
Something like this:
product | company | worker
--------------------------
1 2 John
2 2 Mike
3 2 Jim
4 3 Mark
5 3 Fred
6 2 John
etc...
Is it possible to run one query by company, and count all products by
specific worker that works for selected company.
For example:
SELECT (count how many products each employed worker made) WHERE company = 2;
RESULT :
John:2
Mike:1
Jim:1
I have a table of products. Every product has a company and a worker of
that company that produces it.
Something like this:
product | company | worker
--------------------------
1 2 John
2 2 Mike
3 2 Jim
4 3 Mark
5 3 Fred
6 2 John
etc...
Is it possible to run one query by company, and count all products by
specific worker that works for selected company.
For example:
SELECT (count how many products each employed worker made) WHERE company = 2;
RESULT :
John:2
Mike:1
Jim:1
How to display a name after successful remote validation?
How to display a name after successful remote validation?
My business web application will have a lot of input controls where the
user is expected to enter some kind of code (Country, Zip, Employee ID,
etc.).
I'm using RemoteAttribute to validate code entries against my database to
ensure that users entered the correct code.
The thing is, my standard feature should be to display a name of entered
code if the remote validation is successful or error if the validation is
not successful.
I'm not sure how to do this.
The obvious answer is to send Name property along with true value in Json
object which jquery unobtrusive validation requires. The cshtml could look
something like this:
@Html.LabelFor(m => m.Country)
@Html.EditorFor(m => m.Country, new { data-codename-label="lbnCountry" })
<label ID="lbnCountry"></label>
I'm not sure how to implement such an idea though. Any help is appreciated.
My business web application will have a lot of input controls where the
user is expected to enter some kind of code (Country, Zip, Employee ID,
etc.).
I'm using RemoteAttribute to validate code entries against my database to
ensure that users entered the correct code.
The thing is, my standard feature should be to display a name of entered
code if the remote validation is successful or error if the validation is
not successful.
I'm not sure how to do this.
The obvious answer is to send Name property along with true value in Json
object which jquery unobtrusive validation requires. The cshtml could look
something like this:
@Html.LabelFor(m => m.Country)
@Html.EditorFor(m => m.Country, new { data-codename-label="lbnCountry" })
<label ID="lbnCountry"></label>
I'm not sure how to implement such an idea though. Any help is appreciated.
Friday, 13 September 2013
Django 1.5.1 login_required decorator not catching unauthenticated users
Django 1.5.1 login_required decorator not catching unauthenticated users
I have a very typical view/login_required decorator implementation, and
it's been reported to me that sometimes as often as twice a day, the QA
team will run across this error:
ERROR: AttributeError at /plan/reviewplan/1702/ 'WSGIRequest' object has no
attribute 'user' Request Method: GET Request URL:
http://<ip>/plan/reviewplan/1702/ Django Version: 1.5.1
Traceback: File
"/usr/lib/pymodules/python2.6/django/core/handlers/base.py" in
get_response 187.
response = middleware_method(request, response)
File
"/usr/local/lib/python2.6/dist-packages/debug_toolbar/panels/template.py"
in process_response 118. pformat(k(self.request))) for k in
get_standard_processors()
File "/opt/ion/iondb/rundb/context_processors.py" in
base_context_processor 25.
if request.user: Exception Type: AttributeError at /plan/reviewplan/1702/
Exception Value: 'WSGIRequest' object has no attribute 'user'
I checked and the view does in fact have a login_required decorator. It's
also been reported on other views which are decorated with login_required
as well.
The return on the views is:
return render_to_response("template.html", context_instance=ctx,
mimetype="text/html")
FYI: The ctx instance is stored in the session, and often updated between
view calls. I inherited this design and I can't do anything about it. The
function that handles this is:
def _create_context_from_session(request, next_step_name):
ctxd = request.session['saved_plan']
ctxd['helper'] = request.session['plan_step_helper']
ctxd['step'] = None
if next_step_name in ctxd['helper'].steps:
ctxd['step'] = ctxd['helper'].steps[next_step_name]
context = RequestContext(request, ctxd)
return context
I have a very typical view/login_required decorator implementation, and
it's been reported to me that sometimes as often as twice a day, the QA
team will run across this error:
ERROR: AttributeError at /plan/reviewplan/1702/ 'WSGIRequest' object has no
attribute 'user' Request Method: GET Request URL:
http://<ip>/plan/reviewplan/1702/ Django Version: 1.5.1
Traceback: File
"/usr/lib/pymodules/python2.6/django/core/handlers/base.py" in
get_response 187.
response = middleware_method(request, response)
File
"/usr/local/lib/python2.6/dist-packages/debug_toolbar/panels/template.py"
in process_response 118. pformat(k(self.request))) for k in
get_standard_processors()
File "/opt/ion/iondb/rundb/context_processors.py" in
base_context_processor 25.
if request.user: Exception Type: AttributeError at /plan/reviewplan/1702/
Exception Value: 'WSGIRequest' object has no attribute 'user'
I checked and the view does in fact have a login_required decorator. It's
also been reported on other views which are decorated with login_required
as well.
The return on the views is:
return render_to_response("template.html", context_instance=ctx,
mimetype="text/html")
FYI: The ctx instance is stored in the session, and often updated between
view calls. I inherited this design and I can't do anything about it. The
function that handles this is:
def _create_context_from_session(request, next_step_name):
ctxd = request.session['saved_plan']
ctxd['helper'] = request.session['plan_step_helper']
ctxd['step'] = None
if next_step_name in ctxd['helper'].steps:
ctxd['step'] = ctxd['helper'].steps[next_step_name]
context = RequestContext(request, ctxd)
return context
How to get string in .NET from legacy StrPtr
How to get string in .NET from legacy StrPtr
At work we have a lot of legacy VB6 code. I am implementing custom
messaging between the old VB6 code and a new VB.NET project. I would like
to send the name property of a VB6 control and the name length via the
SendMessage api call in VB6 and assemble the string in the .NET project.
The code in VB6 looks like this:
SendMessage hwnd, WM_CONTROLNAME, StrPtr(sControlName),
CLng(Len(sControlName))
So I'm sending a custom windows message WM_CONTROLNAME to the hwnd of the
.NET form, with a wParam StrPtr of the string and a lParam with the length
of the string.
In the .NET project I have a message handler that calls a function GetText
to reassemble the string from the pointer and string length passed in the
message params:
Protected OverRides Sub WndProc(ByRef m as message)
If m.msg = WM_CONTROLNAME Then
p_sControlName = GetText(m.wParam, m.lParam)
Else
Mybase.WndProc(m)
End If
End Sub
This all works properly up to the point that GetText is supposed to return
the original string. I've tried to fill a StringBuilder with the
GetWindowText API call using the StrPtr and and length to no success. I've
also tried CopyMemory but that doesn't seem to be correct either. What is
the best way to take this pointer and string length and turn it into a
string in my GetText method? Thanks in advance.
At work we have a lot of legacy VB6 code. I am implementing custom
messaging between the old VB6 code and a new VB.NET project. I would like
to send the name property of a VB6 control and the name length via the
SendMessage api call in VB6 and assemble the string in the .NET project.
The code in VB6 looks like this:
SendMessage hwnd, WM_CONTROLNAME, StrPtr(sControlName),
CLng(Len(sControlName))
So I'm sending a custom windows message WM_CONTROLNAME to the hwnd of the
.NET form, with a wParam StrPtr of the string and a lParam with the length
of the string.
In the .NET project I have a message handler that calls a function GetText
to reassemble the string from the pointer and string length passed in the
message params:
Protected OverRides Sub WndProc(ByRef m as message)
If m.msg = WM_CONTROLNAME Then
p_sControlName = GetText(m.wParam, m.lParam)
Else
Mybase.WndProc(m)
End If
End Sub
This all works properly up to the point that GetText is supposed to return
the original string. I've tried to fill a StringBuilder with the
GetWindowText API call using the StrPtr and and length to no success. I've
also tried CopyMemory but that doesn't seem to be correct either. What is
the best way to take this pointer and string length and turn it into a
string in my GetText method? Thanks in advance.
How to make radio buttons horizontal
How to make radio buttons horizontal
I'm trying to figure out how to make my radio buttons align horizontally.
I've tried searching the internet but you can't find everything on the
internet so now I'm here. I'm open to using Javascript and JQuery.
Here's my JSFiddle: http://jsfiddle.net/547fx/1/
Here's the Javascript:
function tryToMakeLink() {
//get all selected radios
var q1 = document.querySelector('input[name="q1"]:checked');
//make sure the user has selected all 3
if (q1 == null) {
document.getElementById("linkDiv").innerHTML = "<input type=button
disabled=disabled value=Next>";
} else {
//now we know we have 3 radios, so get their values
q1 = q1.value;
//now check the values to display a different link for the desired
configuration
if (q1 == "AT&T") {
document.getElementById("linkDiv").innerHTML = "<input type=button
value=Next
onclick=\"window.location.href='http://google.com/';\">att 8gb
black</input>";
} else if (q1 == "Other") {
document.getElementById("linkDiv").innerHTML = "<input type=button
value=Next
onclick=\"window.location.href='http://yahoo.com/';\">other 8b
white</input>";
} else if (q1 == "Unlocked") {
document.getElementById("linkDiv").innerHTML = "<input type=button
value=Next
onclick=\"window.location.href='http://wepriceit.webs.com/';\">red</input>";
}
}
}
I'm trying to figure out how to make my radio buttons align horizontally.
I've tried searching the internet but you can't find everything on the
internet so now I'm here. I'm open to using Javascript and JQuery.
Here's my JSFiddle: http://jsfiddle.net/547fx/1/
Here's the Javascript:
function tryToMakeLink() {
//get all selected radios
var q1 = document.querySelector('input[name="q1"]:checked');
//make sure the user has selected all 3
if (q1 == null) {
document.getElementById("linkDiv").innerHTML = "<input type=button
disabled=disabled value=Next>";
} else {
//now we know we have 3 radios, so get their values
q1 = q1.value;
//now check the values to display a different link for the desired
configuration
if (q1 == "AT&T") {
document.getElementById("linkDiv").innerHTML = "<input type=button
value=Next
onclick=\"window.location.href='http://google.com/';\">att 8gb
black</input>";
} else if (q1 == "Other") {
document.getElementById("linkDiv").innerHTML = "<input type=button
value=Next
onclick=\"window.location.href='http://yahoo.com/';\">other 8b
white</input>";
} else if (q1 == "Unlocked") {
document.getElementById("linkDiv").innerHTML = "<input type=button
value=Next
onclick=\"window.location.href='http://wepriceit.webs.com/';\">red</input>";
}
}
}
Change Tab Bar Tint Color iOS 7
Change Tab Bar Tint Color iOS 7
Does anyone know of a way to change the tint of a Tab Bar in iOS 7 from
the default white with blue icons to another color tint with different
color buttons?
Does anyone know of a way to change the tint of a Tab Bar in iOS 7 from
the default white with blue icons to another color tint with different
color buttons?
Sending daily emails with report attached from CSV file
Sending daily emails with report attached from CSV file
I am wanting to either find a program something that will email a csv file
daily or find free software that will do it for me. I have been googling
how to do it, but only get APEX. It doesn't look like APEX is free or cant
find a work environment it will work in. I admit I am not the most
knowledgeable programmer, but I try. I already have a csv file that I want
to be sent over email on a daily basis. Any ideas?
I am wanting to either find a program something that will email a csv file
daily or find free software that will do it for me. I have been googling
how to do it, but only get APEX. It doesn't look like APEX is free or cant
find a work environment it will work in. I admit I am not the most
knowledgeable programmer, but I try. I already have a csv file that I want
to be sent over email on a daily basis. Any ideas?
Sendgrid adding to mail list not working
Sendgrid adding to mail list not working
I am using the following code for adding emails to a list in sendgrid. But
it is returning inserted :0 response
$request_url = "https://sendgrid.com/api/newsletter/lists/email/add.json";
$data = array("email"=>"testemail@test.com");
$params = array(
'api_user' => $sengrid_user,
'api_key' => $sendgrid_pass,
'list'=>"TestAlwin",
'data' =>json_encode($data)
);
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $request_url);
curl_setopt ($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_VERBOSE, true);
$resp = curl_exec($ch);
curl_close($ch);
This is returning inserted :0 response. It should insert the mailid to the
list I have specified.
I am using the following as reference :
curl -d
'api_user=your_sendgrid_username&api_key=your_sendgrid_password&list=my_list&data[]={"email":"address1@domain.com","name":"contactName1"}&data[]={"email":"address2@domain.com","name":"contactName2"}'
https://sendgrid.com/api/newsletter/lists/email/add.json
This is actually given in their api here :
http://sendgrid.com/docs/API_Reference/Marketing_Emails_API/emails.html
and I am adding the curl vebrose here :
* About to connect() to sendgrid.com port 80 (#0)
* Trying 1.1.1.1... * connected
* Connected to sendgrid.com (1.1.1.1) port 80 (#0)
> POST /api/newsletter/lists/email/add.json?list=TestAlwin HTTP/1.1
Host: sendgrid.com
Accept: */*
Content-Length: 395
Expect: 100-continue
Content-Type: multipart/form-data;
boundary=----------------------------4435bfc2eb00
< HTTP/1.1 100 Continue
< HTTP/1.1 200 OK
< Server: nginx
< Date: Fri, 13 Sep 2013 07:04:42 GMT
< Content-Type: text/html
< Transfer-Encoding: chunked
< Connection: keep-alive
< Vary: Accept-Encoding
<
* Connection #0 to host sendgrid.com left intact
* Closing connection #0
These 1.1.1.1 is just a test IP that I have added here instead of the
actual one.
I am using the following code for adding emails to a list in sendgrid. But
it is returning inserted :0 response
$request_url = "https://sendgrid.com/api/newsletter/lists/email/add.json";
$data = array("email"=>"testemail@test.com");
$params = array(
'api_user' => $sengrid_user,
'api_key' => $sendgrid_pass,
'list'=>"TestAlwin",
'data' =>json_encode($data)
);
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $request_url);
curl_setopt ($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_VERBOSE, true);
$resp = curl_exec($ch);
curl_close($ch);
This is returning inserted :0 response. It should insert the mailid to the
list I have specified.
I am using the following as reference :
curl -d
'api_user=your_sendgrid_username&api_key=your_sendgrid_password&list=my_list&data[]={"email":"address1@domain.com","name":"contactName1"}&data[]={"email":"address2@domain.com","name":"contactName2"}'
https://sendgrid.com/api/newsletter/lists/email/add.json
This is actually given in their api here :
http://sendgrid.com/docs/API_Reference/Marketing_Emails_API/emails.html
and I am adding the curl vebrose here :
* About to connect() to sendgrid.com port 80 (#0)
* Trying 1.1.1.1... * connected
* Connected to sendgrid.com (1.1.1.1) port 80 (#0)
> POST /api/newsletter/lists/email/add.json?list=TestAlwin HTTP/1.1
Host: sendgrid.com
Accept: */*
Content-Length: 395
Expect: 100-continue
Content-Type: multipart/form-data;
boundary=----------------------------4435bfc2eb00
< HTTP/1.1 100 Continue
< HTTP/1.1 200 OK
< Server: nginx
< Date: Fri, 13 Sep 2013 07:04:42 GMT
< Content-Type: text/html
< Transfer-Encoding: chunked
< Connection: keep-alive
< Vary: Accept-Encoding
<
* Connection #0 to host sendgrid.com left intact
* Closing connection #0
These 1.1.1.1 is just a test IP that I have added here instead of the
actual one.
Thursday, 12 September 2013
Rails logger formatting - insert method name calling logger method
Rails logger formatting - insert method name calling logger method
I want to insert name of the method calling the logger methods into my log
files. Not the whole stack trace, but the class, method and/or line number
would be great.
In any method, one can use caller to get an array of strings, each of
which contains the file, line number and method name. I've come up with a
pretty awful kludge using regexes and Enumerable#find to try to return the
first non-logger stack frame. I guess it works, but if the locations of
the logging Ruby files change in a different version or Rails, or I name
my files something to do with logs, it will break. Same with if I take a
given index from the top of the stack (I did this at first, then
refactored one thing and naturally it gave me the wrong frame).
Note that I'm not looking to just log the controller or action, as those
can be retrieved easily. Mostly this is for stuff in the lib/ directory.
Isn't there an easy way to do this? I don't want to have to pass in
__method__ every time I make a logging statement.
I want to insert name of the method calling the logger methods into my log
files. Not the whole stack trace, but the class, method and/or line number
would be great.
In any method, one can use caller to get an array of strings, each of
which contains the file, line number and method name. I've come up with a
pretty awful kludge using regexes and Enumerable#find to try to return the
first non-logger stack frame. I guess it works, but if the locations of
the logging Ruby files change in a different version or Rails, or I name
my files something to do with logs, it will break. Same with if I take a
given index from the top of the stack (I did this at first, then
refactored one thing and naturally it gave me the wrong frame).
Note that I'm not looking to just log the controller or action, as those
can be retrieved easily. Mostly this is for stuff in the lib/ directory.
Isn't there an easy way to do this? I don't want to have to pass in
__method__ every time I make a logging statement.
Paste code in html editor
Paste code in html editor
I need a tool where I can paste code and view it on a web page. I tried
TinyMCE 4.x. It works fine, but I found one problem: Indentation is not
kept when I paste code from Visual Studio. I googled, but I cant find a
solution to that, I tried fckeditor a couple of months ago. I has a syntax
highlighter, but if I recall correctly, it had the same problem with
indentation.
I need the tool to help me with three things: Write plain text Paste code
mainly from Visual Studio Upload image
Most of the google hits are from 2009-2010, so what do I use 2013? Should
I abandon the 'famous' editors and go for something in this 4 year old
article:
http://www.1stwebdesigner.com/css/16-free-javascript-code-syntax-highlighters-for-better-programming/
Im building this with asp.net 4.5
Or maybe just sum it up with one question: How did you get this kind of
requirement up & running?
Thanks
I need a tool where I can paste code and view it on a web page. I tried
TinyMCE 4.x. It works fine, but I found one problem: Indentation is not
kept when I paste code from Visual Studio. I googled, but I cant find a
solution to that, I tried fckeditor a couple of months ago. I has a syntax
highlighter, but if I recall correctly, it had the same problem with
indentation.
I need the tool to help me with three things: Write plain text Paste code
mainly from Visual Studio Upload image
Most of the google hits are from 2009-2010, so what do I use 2013? Should
I abandon the 'famous' editors and go for something in this 4 year old
article:
http://www.1stwebdesigner.com/css/16-free-javascript-code-syntax-highlighters-for-better-programming/
Im building this with asp.net 4.5
Or maybe just sum it up with one question: How did you get this kind of
requirement up & running?
Thanks
Cannot get field to show in inspectpr box
Cannot get field to show in inspectpr box
So im supposed to create a credit card class where if i want to create an
object, i have to enter the account number( which the credit card number
and it is a long. for example: 1234123123123L) and the expiry date( which
is a String. for example "09/2013") in the parameters. Once i create the
object, the inspect box should show the account number, expiry date,
expiry month, expiry year and its validity. For now, im just concerned
about the expiry month. i have the code which extracts the month from the
date. but i cant seem to get the month to show in the inspector box; so
when i click inspect on the object, it shows the account number and expiry
date, but for the month it says zero.
how do i get the expiry month to show in the inspector box?
import java.io.*;
import java.util.Calendar;
/**
* A credit card issued by a recognized financial institution.
*
* @author Janarthanan Manoharan
* @version 2013-09-10
*/
public class CreditCard
{
// instance fields
private long accountNumber;
private String expiryDate;
private int expiryMonth;
private int expiryYear;
private boolean isValid;
/**
* Constructs a simple credit card.
*
* @param number the account number
* @param expiryDate the expiry date in the form MM/YYYY where MM is a
2-digit month
* and YYYY is a 4-digit year
*/
public CreditCard(long number, String expiryDate)
{
accountNumber = number;
this.expiryMonth = expiryMonth;
this.expiryDate = expiryDate;
// expiryYear = expiryYear;
// isValid = false;
}// end of constructor CreditCard(long number, String expiryDate)
public void monthExtract()
{
// convert "int" month to "string" month.
// String monthAsString = String.valueOf(expiryMonth);
//Extract the month from the date.
String monthAsString = expiryDate.substring(0, 2);
System.out.println(monthAsString);
// convert "string" month to "int" month.
int expiryMonth = Integer.parseInt(monthAsString);
System.out.println(expiryMonth);
// the S.O.P is to make sure that the code is actually working.
}
public void main(String [] args)
{
CreditCard credit1 = new CreditCard(5588456789672L, "09/2013");
System.out.println(credit1);
}
/**
* Returns this card's account number.
*
* @return the account number of this card
*/
public long getAccount()
{
return accountNumber;
}// end of method long getAccount()
/**
* Returns this card's expiry month.
*
* @return the 2-digit month this card expires
*/
public int getExpiryMonth()
{
return expiryMonth;
}// end of method int getExpiryMonth()
/**
* Returns this card's expiry year.
*
* @return the 4-digit year this card expires
*/
public int getExpiryYear()
{
return expiryYear;
}// end of method int getExpiryYear()
/**
* Returns true if this card is valid, else false.
*
* @return true if this card is valid, else false
*/
public boolean isValid()
{
return isValid;
}// end of method boolean isValid()
/**
* Returns a string representation of this credit card.
*
* @return a string representing this credit card
*/
public String toString()
{
return "["
+ "Account Number: " + accountNumber
+ "\n Expiry Date: " + expiryDate
+ "\n Exipry Month: " + expiryMonth
+ "]";
}// end of method0. String toString()
}// end of class CreditCard
So im supposed to create a credit card class where if i want to create an
object, i have to enter the account number( which the credit card number
and it is a long. for example: 1234123123123L) and the expiry date( which
is a String. for example "09/2013") in the parameters. Once i create the
object, the inspect box should show the account number, expiry date,
expiry month, expiry year and its validity. For now, im just concerned
about the expiry month. i have the code which extracts the month from the
date. but i cant seem to get the month to show in the inspector box; so
when i click inspect on the object, it shows the account number and expiry
date, but for the month it says zero.
how do i get the expiry month to show in the inspector box?
import java.io.*;
import java.util.Calendar;
/**
* A credit card issued by a recognized financial institution.
*
* @author Janarthanan Manoharan
* @version 2013-09-10
*/
public class CreditCard
{
// instance fields
private long accountNumber;
private String expiryDate;
private int expiryMonth;
private int expiryYear;
private boolean isValid;
/**
* Constructs a simple credit card.
*
* @param number the account number
* @param expiryDate the expiry date in the form MM/YYYY where MM is a
2-digit month
* and YYYY is a 4-digit year
*/
public CreditCard(long number, String expiryDate)
{
accountNumber = number;
this.expiryMonth = expiryMonth;
this.expiryDate = expiryDate;
// expiryYear = expiryYear;
// isValid = false;
}// end of constructor CreditCard(long number, String expiryDate)
public void monthExtract()
{
// convert "int" month to "string" month.
// String monthAsString = String.valueOf(expiryMonth);
//Extract the month from the date.
String monthAsString = expiryDate.substring(0, 2);
System.out.println(monthAsString);
// convert "string" month to "int" month.
int expiryMonth = Integer.parseInt(monthAsString);
System.out.println(expiryMonth);
// the S.O.P is to make sure that the code is actually working.
}
public void main(String [] args)
{
CreditCard credit1 = new CreditCard(5588456789672L, "09/2013");
System.out.println(credit1);
}
/**
* Returns this card's account number.
*
* @return the account number of this card
*/
public long getAccount()
{
return accountNumber;
}// end of method long getAccount()
/**
* Returns this card's expiry month.
*
* @return the 2-digit month this card expires
*/
public int getExpiryMonth()
{
return expiryMonth;
}// end of method int getExpiryMonth()
/**
* Returns this card's expiry year.
*
* @return the 4-digit year this card expires
*/
public int getExpiryYear()
{
return expiryYear;
}// end of method int getExpiryYear()
/**
* Returns true if this card is valid, else false.
*
* @return true if this card is valid, else false
*/
public boolean isValid()
{
return isValid;
}// end of method boolean isValid()
/**
* Returns a string representation of this credit card.
*
* @return a string representing this credit card
*/
public String toString()
{
return "["
+ "Account Number: " + accountNumber
+ "\n Expiry Date: " + expiryDate
+ "\n Exipry Month: " + expiryMonth
+ "]";
}// end of method0. String toString()
}// end of class CreditCard
searching for non english word in a file python
searching for non english word in a file python
I am trying to solve "simple" problem in python (2.7). suppose that i have
two files:
key.txt - which have a key to search for. content.txt - which has a web
content (html file)
both files saved in utf-8. content.txt is mixed file, which means it
contains non english characters (web html file)
i am trying to check if the key in key.txt file found in the content or
not. tried comparing the files as binary (bytes) didn't work, also tried
decoding didn't work.
i would also appreciate any help on how can i search for regex which is
mixed (my pattern built from english and non-english characters)
I am trying to solve "simple" problem in python (2.7). suppose that i have
two files:
key.txt - which have a key to search for. content.txt - which has a web
content (html file)
both files saved in utf-8. content.txt is mixed file, which means it
contains non english characters (web html file)
i am trying to check if the key in key.txt file found in the content or
not. tried comparing the files as binary (bytes) didn't work, also tried
decoding didn't work.
i would also appreciate any help on how can i search for regex which is
mixed (my pattern built from english and non-english characters)
When I terminate the google-app-engine's HelloWorld project from PyDev, the python.exe isn't terminated
When I terminate the google-app-engine's HelloWorld project from PyDev,
the python.exe isn't terminated
The issue is like this:
I created a Google-App-Engine's HelloWorld demo supplied by PyDev in
Eclipse, and then I just run the demo project, I browse the localhost:8080
and it succeeds.
But then I stop the project and start it again (or just restart it)
through the buttons, the browser couldn't show me a page from
localhost:8080, the browser keeps asking for the response and couldn't get
it.
I've googled it for about 5 hours. And finally, I found where the issue
lay on. First, when the helloworld project start, 2 python.exe process
will be added into the taskmgr. When you terminate the project from the
PyDev, there is no error sign there, but only 1 python.exe process was
terminated and the other one still remains even if you close the Eclipse.
So these python.exe still have the control of the port 8080, and the new
instance of python.exe created by the relaunch action couldn't use the
port 8080. So, the browser couldn't get a response back. If you keep doing
relaunch the project, the number of python.exe in the tasklist may become
10+. I've tried use the Windows cmd to start the project and 2 process
start when the start of the project and 2 process terminated when the
terminate of the process.
Changing the port 8080 which the project use to others couldn't solve the
issue. If you start and stop by using the Google's client of
Google-App-Engine. It just works well, there is no extra python.exe
process remain in the tasklist.
By the way, I've tried to update those software to the newest version for
now and reinstall them. But the issue still exists.
I've tried to use the pythonw.exe instead of python.exe as the
interpreter, the issue still exists.
Here is some environment data below:
OS: Win7x64 SP1
Eclipse: 4.3
PyDev: 2.8.2
Google-App-Engine: 1.8.4
Python: 2.7.5 x86
According to those details I mentioned above, I could believe that the
issue comes from the PyDev but I can't find the solution or the way to
submit the issue to the PyDev project team.
the python.exe isn't terminated
The issue is like this:
I created a Google-App-Engine's HelloWorld demo supplied by PyDev in
Eclipse, and then I just run the demo project, I browse the localhost:8080
and it succeeds.
But then I stop the project and start it again (or just restart it)
through the buttons, the browser couldn't show me a page from
localhost:8080, the browser keeps asking for the response and couldn't get
it.
I've googled it for about 5 hours. And finally, I found where the issue
lay on. First, when the helloworld project start, 2 python.exe process
will be added into the taskmgr. When you terminate the project from the
PyDev, there is no error sign there, but only 1 python.exe process was
terminated and the other one still remains even if you close the Eclipse.
So these python.exe still have the control of the port 8080, and the new
instance of python.exe created by the relaunch action couldn't use the
port 8080. So, the browser couldn't get a response back. If you keep doing
relaunch the project, the number of python.exe in the tasklist may become
10+. I've tried use the Windows cmd to start the project and 2 process
start when the start of the project and 2 process terminated when the
terminate of the process.
Changing the port 8080 which the project use to others couldn't solve the
issue. If you start and stop by using the Google's client of
Google-App-Engine. It just works well, there is no extra python.exe
process remain in the tasklist.
By the way, I've tried to update those software to the newest version for
now and reinstall them. But the issue still exists.
I've tried to use the pythonw.exe instead of python.exe as the
interpreter, the issue still exists.
Here is some environment data below:
OS: Win7x64 SP1
Eclipse: 4.3
PyDev: 2.8.2
Google-App-Engine: 1.8.4
Python: 2.7.5 x86
According to those details I mentioned above, I could believe that the
issue comes from the PyDev but I can't find the solution or the way to
submit the issue to the PyDev project team.
Layout on the right side
Layout on the right side
I am working on my first app, and I created spinner using this tutorial:
http://www.androidbegin.com/tutorial/actionbarsherlock-custom-menu-list-navigation-fragments/
... everything is just fine, but how to set right align to that spinner?
Is it even possible? I want to change align using XML, but if only
solution is java code, then it is okay.
I have tried so many times, and always with fail. Somebody have said that
if you create list navigation with custom adapter and views, you can set
right align, but how?
In nav_list_item.xml instead of LinearLayout, I have tried RelativeLayout
with some gravity properties:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="center_vertical|right"
android:layout_gravity="center_vertical|right"
android:orientation="vertical" >
<TextView
android:id="@+id/title"
style="?attr/spinnerItemStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="end"
android:gravity="right|center_horizontal"
android:paddingLeft="0dp"
android:singleLine="true" />
</RelativeLayout>
... unfortunately without success.
I am working on my first app, and I created spinner using this tutorial:
http://www.androidbegin.com/tutorial/actionbarsherlock-custom-menu-list-navigation-fragments/
... everything is just fine, but how to set right align to that spinner?
Is it even possible? I want to change align using XML, but if only
solution is java code, then it is okay.
I have tried so many times, and always with fail. Somebody have said that
if you create list navigation with custom adapter and views, you can set
right align, but how?
In nav_list_item.xml instead of LinearLayout, I have tried RelativeLayout
with some gravity properties:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="center_vertical|right"
android:layout_gravity="center_vertical|right"
android:orientation="vertical" >
<TextView
android:id="@+id/title"
style="?attr/spinnerItemStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="end"
android:gravity="right|center_horizontal"
android:paddingLeft="0dp"
android:singleLine="true" />
</RelativeLayout>
... unfortunately without success.
Devise - how to require password if changing password
Devise - how to require password if changing password
I have a Rails 3 app and I want to show 4 fields:
current password current password confirm new password new password confirm
as well as a bunch of other fields for the user, and I only want to
require the user to enter their current password if they enter a new
password. However, I cannot find how to do this in Devise. What are the
attributes of Devise to let me do this?
I have a Rails 3 app and I want to show 4 fields:
current password current password confirm new password new password confirm
as well as a bunch of other fields for the user, and I only want to
require the user to enter their current password if they enter a new
password. However, I cannot find how to do this in Devise. What are the
attributes of Devise to let me do this?
Android Developer Console not allowing to edit developer name
Android Developer Console not allowing to edit developer name
I have recently uploaded an app to play store. I need to to change the
Developer Name for that app, but all the fields under Developer Profile
are made uneditable.
How can i change the Developer name?
I have recently uploaded an app to play store. I need to to change the
Developer Name for that app, but all the fields under Developer Profile
are made uneditable.
How can i change the Developer name?
Wednesday, 11 September 2013
Mini-pages and image urls
Mini-pages and image urls
I've recently started to use mini-pages for my client-side routing and all
has been going well. However, once my url route gets 2 or more levels deep
the image urls get messed up.
For example if I am at my root location at say, test.com/
The image url correctly is displayed as test.com/image.png
When the url is test.com/test,
the image url correctly is displayed as test.com/image.png
However, when the url is 2 levels deep such as test.com/test/viewall,
the image url is incorrectly displayed as test.com/test/image.png
The last example causes my images not to be displayed on the 2 levels or
deeper pages. How do I address this issue?
I've recently started to use mini-pages for my client-side routing and all
has been going well. However, once my url route gets 2 or more levels deep
the image urls get messed up.
For example if I am at my root location at say, test.com/
The image url correctly is displayed as test.com/image.png
When the url is test.com/test,
the image url correctly is displayed as test.com/image.png
However, when the url is 2 levels deep such as test.com/test/viewall,
the image url is incorrectly displayed as test.com/test/image.png
The last example causes my images not to be displayed on the 2 levels or
deeper pages. How do I address this issue?
#EANF#
#EANF#
I have a dataGridView and one column is checkboxes. If I toggle the state
of the checkbox as soon as the focus moves away it returns to the previous
state.
I've have researched a variety of "fixes" but still haven't solved it.
Simplified code:
public partial class correspondence_list : Form
{
public struct letter
{
public Int16 entity_id {get; set;}
public DateTime eventdate { get; set; }
public String text { get; set; }
public String mediatype { get; set; }
public String objectType { get; set; }
public String filename { get; set; }
public Boolean selected { get; set; }
}
private void correspondence_list_Load(object sender, EventArgs e)
{
letters = VisionSearch.doQuery("SELECT ...");
BindingList<letter> lettersList = new BindingList<letter>();
while (letters.EOF == false)
{
lettersList.Add(new letter { entity_id =
Convert.ToInt16(letters.Fields["entity_id"].Value),
eventdate =
Convert.ToDateTime(letters.Fields["eventdate"].Value),
text = letters.Fields["text"].Value.ToString(), mediatype
= letters.Fields["lettertype"].Value.ToString(),
objectType =
letters.Fields["objecttype"].Value.ToString(), filename =
letters.Fields["filename"].Value.ToString(), selected =
true });
letters.MoveNext();
}
BindingSource bs = new BindingSource();
bs.DataSource = lettersList;
dataGridView2.DataSource = bs;
}
private void dataGridView2_CurrentCellDirtyStateChanged(object
sender, EventArgs e)
{
if (dataGridView2.IsCurrentCellDirty)
{
dataGridView2.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
}
Any ideas why this doesn't work?
I have a dataGridView and one column is checkboxes. If I toggle the state
of the checkbox as soon as the focus moves away it returns to the previous
state.
I've have researched a variety of "fixes" but still haven't solved it.
Simplified code:
public partial class correspondence_list : Form
{
public struct letter
{
public Int16 entity_id {get; set;}
public DateTime eventdate { get; set; }
public String text { get; set; }
public String mediatype { get; set; }
public String objectType { get; set; }
public String filename { get; set; }
public Boolean selected { get; set; }
}
private void correspondence_list_Load(object sender, EventArgs e)
{
letters = VisionSearch.doQuery("SELECT ...");
BindingList<letter> lettersList = new BindingList<letter>();
while (letters.EOF == false)
{
lettersList.Add(new letter { entity_id =
Convert.ToInt16(letters.Fields["entity_id"].Value),
eventdate =
Convert.ToDateTime(letters.Fields["eventdate"].Value),
text = letters.Fields["text"].Value.ToString(), mediatype
= letters.Fields["lettertype"].Value.ToString(),
objectType =
letters.Fields["objecttype"].Value.ToString(), filename =
letters.Fields["filename"].Value.ToString(), selected =
true });
letters.MoveNext();
}
BindingSource bs = new BindingSource();
bs.DataSource = lettersList;
dataGridView2.DataSource = bs;
}
private void dataGridView2_CurrentCellDirtyStateChanged(object
sender, EventArgs e)
{
if (dataGridView2.IsCurrentCellDirty)
{
dataGridView2.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
}
Any ideas why this doesn't work?
how to access the json array in following format
how to access the json array in following format
i am trying to accessthe json data from server, i have accessed the first
json array from file but i dont know how to access the another json array
from that file. any help would be appreciated. my url of json file is as
follows String jsonurl" = "http:// 66.7.207.5
/homebites/list_business_category.php?b_id=18";"
i have accessed json array "business" as follows,
json_object_main = json_parser.getJSONObjectFromUrl(jsonurl
+ res_id);
Log.i("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", json_object_main + "");
if (json_object_main != null) {
try {
JSONArray json_array_header = json_object_main
.getJSONArray("business");
JSONArray j=json_object_main.getJSONArray("business_cat");
//JSONArray
json_cat=json_parser.getJsonArayFromUrl(jsonurl+res_id);
now i want to access json array "business_cat"
how can i?
i am trying to accessthe json data from server, i have accessed the first
json array from file but i dont know how to access the another json array
from that file. any help would be appreciated. my url of json file is as
follows String jsonurl" = "http:// 66.7.207.5
/homebites/list_business_category.php?b_id=18";"
i have accessed json array "business" as follows,
json_object_main = json_parser.getJSONObjectFromUrl(jsonurl
+ res_id);
Log.i("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", json_object_main + "");
if (json_object_main != null) {
try {
JSONArray json_array_header = json_object_main
.getJSONArray("business");
JSONArray j=json_object_main.getJSONArray("business_cat");
//JSONArray
json_cat=json_parser.getJsonArayFromUrl(jsonurl+res_id);
now i want to access json array "business_cat"
how can i?
Action mapping in struts
Action mapping in struts
I found in a struts project this action mapping: /jsp/test.jsp And in
MyClass there is no method name ="add" but there is a method "onAdd" I
wanna know if struts know the name of the method name in this case or its
an error ? because I found this in much actionmapping in this project;
Thanks for your help;
I found in a struts project this action mapping: /jsp/test.jsp And in
MyClass there is no method name ="add" but there is a method "onAdd" I
wanna know if struts know the name of the method name in this case or its
an error ? because I found this in much actionmapping in this project;
Thanks for your help;
Rspec any_instance.stub raises undefined method `any_instance_recorder_for' for nil:NilClass exception
Rspec any_instance.stub raises undefined method
`any_instance_recorder_for' for nil:NilClass exception
Here is the class that I'm testing contained in Foo.rb:
class Foo
def bar
return 2
end
end
Here is the my test contained in Foo_spec.rb:
require "./Foo.rb"
describe "Foo" do
before(:all) do
puts "#{Foo == nil}"
Foo.any_instance.stub(:bar).and_return(1)
end
it "should pass this" do
f = Foo.new
f.bar.should eq 1
end
end
I am getting the following output:
false
F
Failures:
1) Foo Should pass this
Failure/Error: Foo.any_instance.stub(:bar).and_return(1)
NoMethodError:
undefined method `any_instance_recorder_for' for nil:NilClass
# ./Foo_spec.rb:6:in `block (2 levels) in <top (required)>'
Finished in 0 seconds
1 example, 1 failure
Failed examples:
rspec ./Foo_spec.rb:9 # Foo Should pass this
I've consulted the doc and the example given is passing on my machine (so
it isn't a problem with the rspec code), but it isn't giving me any
information on what I might be doing wrong. The error message is also
quite confusing as it's telling me not to call .any_instance on a
nil:NilClass, but as I proved with my output, Foo isn't nil. How am I
supposed to call .any_instance.stub on my custom object?
`any_instance_recorder_for' for nil:NilClass exception
Here is the class that I'm testing contained in Foo.rb:
class Foo
def bar
return 2
end
end
Here is the my test contained in Foo_spec.rb:
require "./Foo.rb"
describe "Foo" do
before(:all) do
puts "#{Foo == nil}"
Foo.any_instance.stub(:bar).and_return(1)
end
it "should pass this" do
f = Foo.new
f.bar.should eq 1
end
end
I am getting the following output:
false
F
Failures:
1) Foo Should pass this
Failure/Error: Foo.any_instance.stub(:bar).and_return(1)
NoMethodError:
undefined method `any_instance_recorder_for' for nil:NilClass
# ./Foo_spec.rb:6:in `block (2 levels) in <top (required)>'
Finished in 0 seconds
1 example, 1 failure
Failed examples:
rspec ./Foo_spec.rb:9 # Foo Should pass this
I've consulted the doc and the example given is passing on my machine (so
it isn't a problem with the rspec code), but it isn't giving me any
information on what I might be doing wrong. The error message is also
quite confusing as it's telling me not to call .any_instance on a
nil:NilClass, but as I proved with my output, Foo isn't nil. How am I
supposed to call .any_instance.stub on my custom object?
HipHop-PHP just-in-time compilation?
HipHop-PHP just-in-time compilation?
Does HiphHop-PHP compile the code on each request or it has a cache or it
just compiles the code and then on each edit you need to re-compile it?
Does HiphHop-PHP compile the code on each request or it has a cache or it
just compiles the code and then on each edit you need to re-compile it?
Tuesday, 10 September 2013
Rectangle output on the screen?
Rectangle output on the screen?
The user will input two co ordinates. We have to change them to opposite
co ordinates and we should output a rectangle on the screen. Can we do it
in C++ ??
The user will input two co ordinates. We have to change them to opposite
co ordinates and we should output a rectangle on the screen. Can we do it
in C++ ??
PHP - how to refresh pdo? it's catching old mysql column name?
PHP - how to refresh pdo? it's catching old mysql column name?
I'm using PDO to access mysql database in PHP.
If I rename a column in MySQL table, PDO continues to use the old column
name in result sets, breaking my code. How to tell PDO to refresh column
names or whatever that's causing this weird cache.
I'm using PDO to access mysql database in PHP.
If I rename a column in MySQL table, PDO continues to use the old column
name in result sets, breaking my code. How to tell PDO to refresh column
names or whatever that's causing this weird cache.
Unicode characters not rendering with PIL ImageFont
Unicode characters not rendering with PIL ImageFont
I'm trying to write tiff images using box drawing characters, but all of
the characters in question show up as:
The box draw characters (e.g. "©°©¤©´©¦©¸©¼¨b¨T¨e¨h¨k¨\¨_") were pasted
directly into the source code, and they show up correctly when saved to a
text file, but I don't understand why they're not showing up on the image.
Here is an example of the code I'm using to draw the image:
# coding=utf-8
text = "©°©¤©´©¦©¸©¼¨b¨T¨e¨h¨k¨\¨_"
from PIL import Image, ImageDraw, ImageFont, TiffImagePlugin
img = Image.new("1",(1200,1600),1)
font = ImageFont.truetype("cour.ttf",14,encoding="unic")
draw = ImageDraw.Draw(img)
draw.text((40,0), text, font=font, fill=0)
img.save("imagefile.tif","TIFF")
I'm using python version 2.7.2 on Windows 7.
I'm trying to write tiff images using box drawing characters, but all of
the characters in question show up as:
The box draw characters (e.g. "©°©¤©´©¦©¸©¼¨b¨T¨e¨h¨k¨\¨_") were pasted
directly into the source code, and they show up correctly when saved to a
text file, but I don't understand why they're not showing up on the image.
Here is an example of the code I'm using to draw the image:
# coding=utf-8
text = "©°©¤©´©¦©¸©¼¨b¨T¨e¨h¨k¨\¨_"
from PIL import Image, ImageDraw, ImageFont, TiffImagePlugin
img = Image.new("1",(1200,1600),1)
font = ImageFont.truetype("cour.ttf",14,encoding="unic")
draw = ImageDraw.Draw(img)
draw.text((40,0), text, font=font, fill=0)
img.save("imagefile.tif","TIFF")
I'm using python version 2.7.2 on Windows 7.
Pygame: os.path.join() broke
Pygame: os.path.join() broke
After updating SDL framework on Mac OSX 10.8.4 to fix fullscreen issues on
the mac my images no longer load. Mostly just look at the top part of the
function.
def load_image(name, colorkey=None):
fullname = os.path.join('images',name)
try:
image = pygame.image.load(fullname) # Tries loading image
except pygame.error, message: # If image load fails
print "Cannot load image: ", fullname# return error to console
raise SystemExit, message
image = image.convert_alpha()
if colorkey is not None:
if colorkey is -1:
colorkey = image.get_at((0,0))
image.set_colorkey(colorkey, RLEACCEL)#new alpha value
return image, image.get_rect()
This worked before the update but no longer does. Tried searching around
and even updating again to no avail. I also tried...
fullname = os.path.join(os.sep, 'images',name)
...and then one image works then the second one does not. All folders and
image names were tripled checked. I even changed the names and folders
around still with no luck. Any other ideas?
After updating SDL framework on Mac OSX 10.8.4 to fix fullscreen issues on
the mac my images no longer load. Mostly just look at the top part of the
function.
def load_image(name, colorkey=None):
fullname = os.path.join('images',name)
try:
image = pygame.image.load(fullname) # Tries loading image
except pygame.error, message: # If image load fails
print "Cannot load image: ", fullname# return error to console
raise SystemExit, message
image = image.convert_alpha()
if colorkey is not None:
if colorkey is -1:
colorkey = image.get_at((0,0))
image.set_colorkey(colorkey, RLEACCEL)#new alpha value
return image, image.get_rect()
This worked before the update but no longer does. Tried searching around
and even updating again to no avail. I also tried...
fullname = os.path.join(os.sep, 'images',name)
...and then one image works then the second one does not. All folders and
image names were tripled checked. I even changed the names and folders
around still with no luck. Any other ideas?
Controlling a remote computer by IP address
Controlling a remote computer by IP address
I have an IP address that belongs to someone's computer.
How can I control his computer using the IP that I have? What are the
programs or commands that I should know to do that, or where should I
start my search? The computer's operating system is Windows, and this is
for a legal matter.
I have an IP address that belongs to someone's computer.
How can I control his computer using the IP that I have? What are the
programs or commands that I should know to do that, or where should I
start my search? The computer's operating system is Windows, and this is
for a legal matter.
I want to develop a website in hindi [on hold]
I want to develop a website in hindi [on hold]
I want to implement a Hindi in our website without using HTML entities.
How can i do it? I am using php.
Thanks in advance!
I want to implement a Hindi in our website without using HTML entities.
How can i do it? I am using php.
Thanks in advance!
How do I add images to an Xamarin iOS project and make them available in Interface Builder?
How do I add images to an Xamarin iOS project and make them available in
Interface Builder?
I am working in Xamarin to build an iOS iPad app. I have created a folder
called Resources in the project root e.g. ProjectName/Resources. Within
here is a subfolder ProjectName/Resources/Images. I have added 2 images
into the Images folder.
Then in Interface Builder/xcode, I have added a UIImageView to my xib file
and gone to the Image drop down in the attributes inspector. There are no
images available to select.
Maybe I haveto add them via xcode instead? If so what are the correct
steps and file structures to use?
What is the correct way to work with images and make them available for
selection in Interface Builder?
Interface Builder?
I am working in Xamarin to build an iOS iPad app. I have created a folder
called Resources in the project root e.g. ProjectName/Resources. Within
here is a subfolder ProjectName/Resources/Images. I have added 2 images
into the Images folder.
Then in Interface Builder/xcode, I have added a UIImageView to my xib file
and gone to the Image drop down in the attributes inspector. There are no
images available to select.
Maybe I haveto add them via xcode instead? If so what are the correct
steps and file structures to use?
What is the correct way to work with images and make them available for
selection in Interface Builder?
what is the difference between $object::$variable and $object->variable
what is the difference between $object::$variable and $object->variable
what is the difference between $object::$variable and $object->variable
both of them can be used to achieve the same but creates difference when
the class member-variable is static as follows-
$object::$variable :- This syntax allows the static variable to be
achieved through the object
But
$object->variable :- This syntax does not allow the static variable to be
achieved through the object.
What is the semantic difference between the two?
what is the difference between $object::$variable and $object->variable
both of them can be used to achieve the same but creates difference when
the class member-variable is static as follows-
$object::$variable :- This syntax allows the static variable to be
achieved through the object
But
$object->variable :- This syntax does not allow the static variable to be
achieved through the object.
What is the semantic difference between the two?
Monday, 9 September 2013
how can i change data of a file which is present in that package?(in java, how to get outputStream of that file?)
how can i change data of a file which is present in that package?(in java,
how to get outputStream of that file?)
i've used ResorceLoder class to get input stream but how can i get
outputStream, is this possible to modify data which is in that package?(i
need to change the image files which are present in that package using
java class which is present in the same jar file)
how to get outputStream of that file?)
i've used ResorceLoder class to get input stream but how can i get
outputStream, is this possible to modify data which is in that package?(i
need to change the image files which are present in that package using
java class which is present in the same jar file)
Handle two variables one database entry
Handle two variables one database entry
I have a row for user like so
id username owns
I'm going to make a form to designate a few details such as what a user
owns...
For example they could own a bike,truck,car ect. What would be the best
way to approach this without creating a new column for each possession? or
is creating a new column for each possession the way to go?
There is no set number of possessions.
I have a row for user like so
id username owns
I'm going to make a form to designate a few details such as what a user
owns...
For example they could own a bike,truck,car ect. What would be the best
way to approach this without creating a new column for each possession? or
is creating a new column for each possession the way to go?
There is no set number of possessions.
application_helper.rb not refreshing after restart server Rails
application_helper.rb not refreshing after restart server Rails
sorry if this is a fool question
I have an app on rails using i18n its fine, until i try to modify the
application_helper.rb there is a part that stands:
def language_css(language)
case language
when 'en'
return raw '<link rel="stylesheet" type="text/css"
href="/assets/stylesheets/en.css">'
when 'es-MX'
return raw '<link rel="stylesheet" type="text/css"
href="/assets/stylesheets/es.css">'
when 'fr'
return raw '<link rel="stylesheet" type="text/css"
href="/assets/stylesheets/fr.css">'
when 'jp'
return raw '<link rel="stylesheet" type="text/css"
href="/assets/stylesheets/jp.css">'
when 'ch'
return raw '<link rel="stylesheet" type="text/css"
href="/assets/stylesheets/ch.css">'
when 'ar'
return raw '<link rel="stylesheet" type="text/css"
href="/assets/stylesheets/ar.css">'
default
return raw '<link rel="stylesheet" type="text/css"
href="/assets/stylesheets/es.css">'
end
end
I tried to change default "es.css" for "en.css" but i did it , and i see
no changes the es.css file is still the default css file.. not en.css
So i even tried like Ctrl + C and Rails S, several times, no luck
I found an advanced question on Stackoverflow for developing plugins, wich
teach you how to set a refresh of this file always, but this is to
advance, and i just need to refresh this Once!!
Thanks
sorry if this is a fool question
I have an app on rails using i18n its fine, until i try to modify the
application_helper.rb there is a part that stands:
def language_css(language)
case language
when 'en'
return raw '<link rel="stylesheet" type="text/css"
href="/assets/stylesheets/en.css">'
when 'es-MX'
return raw '<link rel="stylesheet" type="text/css"
href="/assets/stylesheets/es.css">'
when 'fr'
return raw '<link rel="stylesheet" type="text/css"
href="/assets/stylesheets/fr.css">'
when 'jp'
return raw '<link rel="stylesheet" type="text/css"
href="/assets/stylesheets/jp.css">'
when 'ch'
return raw '<link rel="stylesheet" type="text/css"
href="/assets/stylesheets/ch.css">'
when 'ar'
return raw '<link rel="stylesheet" type="text/css"
href="/assets/stylesheets/ar.css">'
default
return raw '<link rel="stylesheet" type="text/css"
href="/assets/stylesheets/es.css">'
end
end
I tried to change default "es.css" for "en.css" but i did it , and i see
no changes the es.css file is still the default css file.. not en.css
So i even tried like Ctrl + C and Rails S, several times, no luck
I found an advanced question on Stackoverflow for developing plugins, wich
teach you how to set a refresh of this file always, but this is to
advance, and i just need to refresh this Once!!
Thanks
Subscribe to:
Comments (Atom)