Is the statement about convergence true?
If for any positive integer $m,n$ there is $0 \leq x_{m+n} \leq x_m x_n$
Does $\left\{\sqrt[n]{x_{n}}\right\}$ converge?
Monday, 30 September 2013
How to achieve portability with sed -i (in-place editing)=?iso-8859-1?Q?=3F_=96_unix.stackexchange.com?=
How to achieve portability with sed -i (in-place editing)? –
unix.stackexchange.com
I'm writing shell scripts for my server, which is a shared hosting running
FreeBSD. I also want to be able to test them locally, on my PC running
Linux. Hence, I'm trying to write them in a portable …
unix.stackexchange.com
I'm writing shell scripts for my server, which is a shared hosting running
FreeBSD. I also want to be able to test them locally, on my PC running
Linux. Hence, I'm trying to write them in a portable …
Horizontal scrolling website content
Horizontal scrolling website content
My objective is to make a website for my portfolio. I have a div for the
menu that wanted to be on top of another div that works as a container for
all of my images. The images have to fill 100% height of the browser. The
problem is, that I wanted my website to scroll horizontally and when I
start to add content, as soon as the width goes over the 100% of the
browser window the new image goes under the first image making it scroll
horizontally. What can I do to correct this? Here's my code:
<style>
<!--
body, html {height: 100%;}
#main {
width: 100%;
height: 100%;
background-color:#000;
position: absolute;
top: 0px;
left: 0px;
z-index: 1;
}
#menu {
width: 200px;
height: 500px;
background-color:#fff;
position: absolute;
top: 10px;
left: 10px;
overflow: scroll;
z-index: 2;
}
#img {
height:100%;
float: left;
overflow: scroll;
}
-->
</style>
My objective is to make a website for my portfolio. I have a div for the
menu that wanted to be on top of another div that works as a container for
all of my images. The images have to fill 100% height of the browser. The
problem is, that I wanted my website to scroll horizontally and when I
start to add content, as soon as the width goes over the 100% of the
browser window the new image goes under the first image making it scroll
horizontally. What can I do to correct this? Here's my code:
<style>
<!--
body, html {height: 100%;}
#main {
width: 100%;
height: 100%;
background-color:#000;
position: absolute;
top: 0px;
left: 0px;
z-index: 1;
}
#menu {
width: 200px;
height: 500px;
background-color:#fff;
position: absolute;
top: 10px;
left: 10px;
overflow: scroll;
z-index: 2;
}
#img {
height:100%;
float: left;
overflow: scroll;
}
-->
</style>
Custom Bash prompt is overwriting itself
Custom Bash prompt is overwriting itself
I'm using custom bash prompt to show git branch.
Everything is in /etc/bash/bashrc:
function formattedGitBranch {
_branch="$(git branch 2>/dev/null | sed -e "/^\s/d" -e "s/^\*\s//")"
test -n "$_branch" && echo -e "\e[0;91m($_branch)" # color before
test -n "$_branch" && echo -e "\e[0;91m($_branch)\e[m" # stop color after
test -n "$_branch" && echo -e "($_branch)" # without color
}
BGreen="\[\033[01;32m\]"
# color is set before function call
PS1=$BGreen'\u@\h\[\033[01;34m\] \w \[\033[0;91m\]$(formattedGitBranch)
\[\033[01;34m\]\$\[\033[00m\] '
# color is set inside function
PS1=$BGreen'\u@\h\[\033[01;34m\] \w $(formattedGitBranch)
\[\033[01;34m\]\$\[\033[00m\] '
Problem is that when I set color for $_branch in the function, my prompt
will be overwrited when EOL is reached:
I solved the problem by setting the colour only in PS1, but still I would
like to know why it is overwriting my prompt in the first case. Is echo -e
involved in this problem somehow?
I'm using custom bash prompt to show git branch.
Everything is in /etc/bash/bashrc:
function formattedGitBranch {
_branch="$(git branch 2>/dev/null | sed -e "/^\s/d" -e "s/^\*\s//")"
test -n "$_branch" && echo -e "\e[0;91m($_branch)" # color before
test -n "$_branch" && echo -e "\e[0;91m($_branch)\e[m" # stop color after
test -n "$_branch" && echo -e "($_branch)" # without color
}
BGreen="\[\033[01;32m\]"
# color is set before function call
PS1=$BGreen'\u@\h\[\033[01;34m\] \w \[\033[0;91m\]$(formattedGitBranch)
\[\033[01;34m\]\$\[\033[00m\] '
# color is set inside function
PS1=$BGreen'\u@\h\[\033[01;34m\] \w $(formattedGitBranch)
\[\033[01;34m\]\$\[\033[00m\] '
Problem is that when I set color for $_branch in the function, my prompt
will be overwrited when EOL is reached:
I solved the problem by setting the colour only in PS1, but still I would
like to know why it is overwriting my prompt in the first case. Is echo -e
involved in this problem somehow?
Sunday, 29 September 2013
Is there an optimization similar to loop unroll for functional programming?
Is there an optimization similar to loop unroll for functional programming?
Disclaimer: I know little about ghc compiling pipeline, but I hope to
learn some more about it with this post, for example, if comparing
imperative vs functional is relevant to code compilation.
As you know, loop unrolling reduces the number of iterations over a loop
by duplicating the code inside it. This improves performance since it
reduces the number of jumps (and penalities associated with it) and AFAIR,
creates bigger blocks of code, leaving room for better Register renaming
optimization.
I was wondering, could there be an equivalent to Loop Unrolling for
functional programming? Could we 'unroll' a function, open/expand it's
definition, to first reduce the number of calls to said function and/or
creating bigger chunks of code -- then leaving room for more code rewrite
optimizations (like register renaming, or some FP equivalent)?
Something that would 'unroll' or 'expand' a function definition, using for
example function evaluation (maybe mixed with some tactic) in order to
have a trade-off between space vs time.
An example of what I had in mind:
map1 _ [] = []
map1 f (x:xs) = (f x): map f xs
Would unroll to
map2 _ [] = []
map2 f (x:x1:xs) = (f x):(f x1):map2 f xs
map2 f (x:xs) = (f x): map2 f xs
Once more:
map4 _ [] = []
map4 f (x:x1:x2:x3:xs) = (f x):(f x1):(f x2):(f x3):map4 f xs
map4 f (x:x1:x2:xs) = (f x):(f x1):(f x2):map4 f xs
map4 f (x:x1:xs) = (f x):(f x1):map4 f xs
map4 f (x:xs) = (f x): map4 f xs
Two things are at play: multiple cases of map4 (and consequent tests on
list) could degrade performance, or the reduced number of calls of map4
would improve performance. Maybe this could reduce some constant overhead
created by lazy evaluation?
Well that doesn't seems to hard to code a test for, so after putting
criterion to roll this out, this is what I've got:
ImgUr album
Problem size 5*10^6
map 105.4 ms
map2 93.34 ms
map4 89.79 ms
Problem size 1*10^7
map 216.3 ms
map2 186.8 ms
map4 180.1 ms
Problem size 5*10^7
map 1050 ms
map2 913.7 ms
map4 899.8 ms
Well, it seems that unrolling had some effect^1! map4 appears to be 16%
faster.
Time for the questions then:
Have this been discussed before? Is something like that already implemented?
Is it really the reduced number of evaluations of map4 that improves speed?
Can this be automated?
Could I evaluate by chunks? ie.: if (f x) is fully evaluated, fully
evalute everything up to (f x4).
Any other form this sort of unrolling come at play?
How inflation on the function size could this lead to?
Any short-commings on why this is not a good idea?
1: I`ve also unrolled fib, since this sort of optimization would also
happen in that form, but the performance gain is cheating a (very) bad
algorithm.
2: I'm a haskell intermediate
Disclaimer: I know little about ghc compiling pipeline, but I hope to
learn some more about it with this post, for example, if comparing
imperative vs functional is relevant to code compilation.
As you know, loop unrolling reduces the number of iterations over a loop
by duplicating the code inside it. This improves performance since it
reduces the number of jumps (and penalities associated with it) and AFAIR,
creates bigger blocks of code, leaving room for better Register renaming
optimization.
I was wondering, could there be an equivalent to Loop Unrolling for
functional programming? Could we 'unroll' a function, open/expand it's
definition, to first reduce the number of calls to said function and/or
creating bigger chunks of code -- then leaving room for more code rewrite
optimizations (like register renaming, or some FP equivalent)?
Something that would 'unroll' or 'expand' a function definition, using for
example function evaluation (maybe mixed with some tactic) in order to
have a trade-off between space vs time.
An example of what I had in mind:
map1 _ [] = []
map1 f (x:xs) = (f x): map f xs
Would unroll to
map2 _ [] = []
map2 f (x:x1:xs) = (f x):(f x1):map2 f xs
map2 f (x:xs) = (f x): map2 f xs
Once more:
map4 _ [] = []
map4 f (x:x1:x2:x3:xs) = (f x):(f x1):(f x2):(f x3):map4 f xs
map4 f (x:x1:x2:xs) = (f x):(f x1):(f x2):map4 f xs
map4 f (x:x1:xs) = (f x):(f x1):map4 f xs
map4 f (x:xs) = (f x): map4 f xs
Two things are at play: multiple cases of map4 (and consequent tests on
list) could degrade performance, or the reduced number of calls of map4
would improve performance. Maybe this could reduce some constant overhead
created by lazy evaluation?
Well that doesn't seems to hard to code a test for, so after putting
criterion to roll this out, this is what I've got:
ImgUr album
Problem size 5*10^6
map 105.4 ms
map2 93.34 ms
map4 89.79 ms
Problem size 1*10^7
map 216.3 ms
map2 186.8 ms
map4 180.1 ms
Problem size 5*10^7
map 1050 ms
map2 913.7 ms
map4 899.8 ms
Well, it seems that unrolling had some effect^1! map4 appears to be 16%
faster.
Time for the questions then:
Have this been discussed before? Is something like that already implemented?
Is it really the reduced number of evaluations of map4 that improves speed?
Can this be automated?
Could I evaluate by chunks? ie.: if (f x) is fully evaluated, fully
evalute everything up to (f x4).
Any other form this sort of unrolling come at play?
How inflation on the function size could this lead to?
Any short-commings on why this is not a good idea?
1: I`ve also unrolled fib, since this sort of optimization would also
happen in that form, but the performance gain is cheating a (very) bad
algorithm.
2: I'm a haskell intermediate
Building an application ontop of an IDE
Building an application ontop of an IDE
Is it possible to have an application that can be built on top of an IDE?
So i would like to edit some of the code in my application on the IDE and
this can be saved to reflect a new change on the code programmed for the
application. So i click on an area to change a text editor like IDLE (for
python) pops up or an ide, the code for that application is generated or
can be created from scratch to illustrate a new change in my application.
This would save me having to write my own complier for my application.
Thanks for suggestions.
Is it possible to have an application that can be built on top of an IDE?
So i would like to edit some of the code in my application on the IDE and
this can be saved to reflect a new change on the code programmed for the
application. So i click on an area to change a text editor like IDLE (for
python) pops up or an ide, the code for that application is generated or
can be created from scratch to illustrate a new change in my application.
This would save me having to write my own complier for my application.
Thanks for suggestions.
Difference between else if and if (Java)
Difference between else if and if (Java)
I was wondering if there's any difference between these two codes:
Code 1:
if(isSleepy()){
sleep(1);
} else if (isBored()){
dance();
dance();
} else {
walkRight(50);
walkLeft(50);
if(isHungry()){
eat();
}
}
Code 2:
if(isSleepy()){
sleep(1);
}
if (isBored()){
dance();
dance();
}
walkRight(50);
walkLeft(50);
if(isHungry()){
eat();
}
I've replaced the if-elseif-if chain with if only. Does that affect the
conditionnal process ?
I was wondering if there's any difference between these two codes:
Code 1:
if(isSleepy()){
sleep(1);
} else if (isBored()){
dance();
dance();
} else {
walkRight(50);
walkLeft(50);
if(isHungry()){
eat();
}
}
Code 2:
if(isSleepy()){
sleep(1);
}
if (isBored()){
dance();
dance();
}
walkRight(50);
walkLeft(50);
if(isHungry()){
eat();
}
I've replaced the if-elseif-if chain with if only. Does that affect the
conditionnal process ?
Saturday, 28 September 2013
Optimal Open Graph image size for linking to my podcast
Optimal Open Graph image size for linking to my podcast
I often link to my podcast on Facebook and when I post the link I want our
podcast logo to show as the link picture.
Through much trial and error and using the Facebook debugging tool, I
eventually got all the Open Graph tags set and set my Open Graph image.
Here's my problem:
iTunes wants a 1400x1400 image. However, if I use that image, then when I
post the link on Facebook, the link picture appears as a larger
rectangular banner above the link and only displays part of the (square)
picture.
If I instead use a 300x300 Open Graph image, it looks great on Facebook,
but does not meet the iTunes standard of needing to be 1400x1400.
Is there any solution to this? Any way to somehow make Facebook and iTunes
use separate images or have FB resize my image and display it properly?
I often link to my podcast on Facebook and when I post the link I want our
podcast logo to show as the link picture.
Through much trial and error and using the Facebook debugging tool, I
eventually got all the Open Graph tags set and set my Open Graph image.
Here's my problem:
iTunes wants a 1400x1400 image. However, if I use that image, then when I
post the link on Facebook, the link picture appears as a larger
rectangular banner above the link and only displays part of the (square)
picture.
If I instead use a 300x300 Open Graph image, it looks great on Facebook,
but does not meet the iTunes standard of needing to be 1400x1400.
Is there any solution to this? Any way to somehow make Facebook and iTunes
use separate images or have FB resize my image and display it properly?
Methods don't know about outside variables?
Methods don't know about outside variables?
Say I'm writing a division algorithm script:
def current_trace
puts "Counter: #{counter}; r: #{r}; q: #{q}"
end
r = a
q = 0
counter = 0
while r >= d
current_trace
r = r - d
q = q + 1
counter += 1
end
current_trace
I expected that calling current_trace would output the value of counter, r
and q. But instead I get:
in current_trace': undefined local variable or methodcounter' for
main:Object (NameError)
What's the problem here?
How should I write a method that will output the values of some variables
named counter, r, and q, at any given point (preferably without passing
arguments to the method)?
Say I'm writing a division algorithm script:
def current_trace
puts "Counter: #{counter}; r: #{r}; q: #{q}"
end
r = a
q = 0
counter = 0
while r >= d
current_trace
r = r - d
q = q + 1
counter += 1
end
current_trace
I expected that calling current_trace would output the value of counter, r
and q. But instead I get:
in current_trace': undefined local variable or methodcounter' for
main:Object (NameError)
What's the problem here?
How should I write a method that will output the values of some variables
named counter, r, and q, at any given point (preferably without passing
arguments to the method)?
input button is not sending info, it is not doing nothing
input button is not sending info, it is not doing nothing
When I press the submit button, nothing happens.
HTML:
<from action="php/reglog.php" method="POST" name="register">
<span>register</span><br>
<label>login :<input type="text" name="login" maxlength="20"
placeholder="login" autofocus></label><br>
<label>password :<input type="password" name="password" maxlength="12"
placeholder="password"></label><br>
<input type="submit" value="register"><br>
<a href="login.html">or login</a>
</from>
PHP:
<?php
$result = mail("test@test.com","User","Mail recived with this info:
\nLOGIN: $_POST[login] \nPASSWORD: $_POST[password]");
if ($result) {
echo "<p>Message Sent successeful!</p>";
}
else{
echo "<p>Error occured while sending</p>";
}
?>
When I press the submit button, nothing happens.
HTML:
<from action="php/reglog.php" method="POST" name="register">
<span>register</span><br>
<label>login :<input type="text" name="login" maxlength="20"
placeholder="login" autofocus></label><br>
<label>password :<input type="password" name="password" maxlength="12"
placeholder="password"></label><br>
<input type="submit" value="register"><br>
<a href="login.html">or login</a>
</from>
PHP:
<?php
$result = mail("test@test.com","User","Mail recived with this info:
\nLOGIN: $_POST[login] \nPASSWORD: $_POST[password]");
if ($result) {
echo "<p>Message Sent successeful!</p>";
}
else{
echo "<p>Error occured while sending</p>";
}
?>
How to read a big file list from a textfile to form a query
How to read a big file list from a textfile to form a query
I have this query which I have to run multiple times in excel and i need
to change the filelists in it.
select * from files
where
filename in ('filename1','filename2')
so I have a TEMP in my query filename in TEMP and I want to loop and get
the result for all filelists. My onlyproblem is reading .txt into the TEMP
and executing the query once for all filenames in the txt file. i know how
to read files line by line so that didn't help.
my text files which I want to read the lists from are like
filename1 filename2 . . . . filename15000
yes some big numbers.
I have this query which I have to run multiple times in excel and i need
to change the filelists in it.
select * from files
where
filename in ('filename1','filename2')
so I have a TEMP in my query filename in TEMP and I want to loop and get
the result for all filelists. My onlyproblem is reading .txt into the TEMP
and executing the query once for all filenames in the txt file. i know how
to read files line by line so that didn't help.
my text files which I want to read the lists from are like
filename1 filename2 . . . . filename15000
yes some big numbers.
Friday, 27 September 2013
How to point to the expected char array after passing char* into a function in C?
How to point to the expected char array after passing char* into a
function in C?
Why I can not change the content the char* points to?
For example:
int main(int argc, char * argv[]) {
char *a = NULL; // now a = NULL
b(a);
// but now a points to NULL again! Why?
}
void b(char *argv[], char* c) {
// now a is passed in
c = *argv[3];
// now a actually points to the start of char array pointed to by argv[3]
}
From the output, I see the *a is passed to the function. Then inside the
function b, it actually pointed to the expected char[ ]. But when returned
from b, a became NULL again. Why? And how can a points to expected content
after return from b? Thank you!
function in C?
Why I can not change the content the char* points to?
For example:
int main(int argc, char * argv[]) {
char *a = NULL; // now a = NULL
b(a);
// but now a points to NULL again! Why?
}
void b(char *argv[], char* c) {
// now a is passed in
c = *argv[3];
// now a actually points to the start of char array pointed to by argv[3]
}
From the output, I see the *a is passed to the function. Then inside the
function b, it actually pointed to the expected char[ ]. But when returned
from b, a became NULL again. Why? And how can a points to expected content
after return from b? Thank you!
Rails and Backbone.js: confused on how to setup portion of app
Rails and Backbone.js: confused on how to setup portion of app
In my app, a user can login and navigate to a page where they can check
off tasks that they have completed.
View:
<div class="container">
<div class="row">
<div class="span12">
<table class="table table-hovered">
<tr>
<td></td>
<td>Resources</td>
<td>Deadline</td>
</tr>
<% @tasks.each do |task| %>
<tr id="<%= task.id %>" class="<%=
current_user.completed_tasks.include?(task) ? 'grey-row' : ''
%>">
<td class="span8">
<%= form_for find_or_create_association_for_task(task,
current_user), remote: true do |f| %>
<%= f.check_box :complete %> <%= task.item %>
<% end %>
</td>
<td>
<ul>
<% task.resources.each do |r| %>
<li><%= link_to_if r.link.present?, r.name, r.link,
target: "_blank" %></li>
<% end unless task.resources.blank? %>
</ul>
</td>
<td><%= task.deadline %></td>
</tr>
<% end %>
</table>
</div>
</div>
</div>
Find or create association for task helper method:
module TasksHelper
def find_or_create_association_for_task(task, athlete)
@task = AthleteTask.where(athlete_id: athlete, task_id: task.id).first
@task ||= athlete.athlete_tasks.create(task_id: task.id)
end
end
Athlete Model:
has_many :tasks, through: :athlete_tasks
has_many :athlete_tasks
Task Model:
has_many :athletes, through: :athlete_tasks
has_many :athlete_tasks
An Athlete accesses this page by logging in and navigating to /athlete/tasks
When an athlete checks off a task as 'complete', a remote call is fired
off to the Athlete::TasksController
class Athlete::TasksController < ApplicationController
before_filter :authenticate_user!
authorize_resource
respond_to :html, :json
def index
@tasks = Task.where(classification: current_user.classification)
respond_with @tasks
end
def update
@task = current_user.athlete_tasks.find(params[:id])
@task.update_attributes(params[:athlete_task])
end
end
I think my confusion is coming from how to properly load in the tasks that
should be loaded into the view. Any help would be greatly appreciated!!
In my app, a user can login and navigate to a page where they can check
off tasks that they have completed.
View:
<div class="container">
<div class="row">
<div class="span12">
<table class="table table-hovered">
<tr>
<td></td>
<td>Resources</td>
<td>Deadline</td>
</tr>
<% @tasks.each do |task| %>
<tr id="<%= task.id %>" class="<%=
current_user.completed_tasks.include?(task) ? 'grey-row' : ''
%>">
<td class="span8">
<%= form_for find_or_create_association_for_task(task,
current_user), remote: true do |f| %>
<%= f.check_box :complete %> <%= task.item %>
<% end %>
</td>
<td>
<ul>
<% task.resources.each do |r| %>
<li><%= link_to_if r.link.present?, r.name, r.link,
target: "_blank" %></li>
<% end unless task.resources.blank? %>
</ul>
</td>
<td><%= task.deadline %></td>
</tr>
<% end %>
</table>
</div>
</div>
</div>
Find or create association for task helper method:
module TasksHelper
def find_or_create_association_for_task(task, athlete)
@task = AthleteTask.where(athlete_id: athlete, task_id: task.id).first
@task ||= athlete.athlete_tasks.create(task_id: task.id)
end
end
Athlete Model:
has_many :tasks, through: :athlete_tasks
has_many :athlete_tasks
Task Model:
has_many :athletes, through: :athlete_tasks
has_many :athlete_tasks
An Athlete accesses this page by logging in and navigating to /athlete/tasks
When an athlete checks off a task as 'complete', a remote call is fired
off to the Athlete::TasksController
class Athlete::TasksController < ApplicationController
before_filter :authenticate_user!
authorize_resource
respond_to :html, :json
def index
@tasks = Task.where(classification: current_user.classification)
respond_with @tasks
end
def update
@task = current_user.athlete_tasks.find(params[:id])
@task.update_attributes(params[:athlete_task])
end
end
I think my confusion is coming from how to properly load in the tasks that
should be loaded into the view. Any help would be greatly appreciated!!
How can I update my PHP 5.3.3 to PHP 5.3.8 Linux Centos
How can I update my PHP 5.3.3 to PHP 5.3.8 Linux Centos
I want to update my php 5.3.3 to php 5.3.8, I already downloaded
PHP5.3.8.tar.gzip.
My PHP 5.3.3 located in /usr/bin/php. When I try to install
PHP5.3.8.tar.gzip and do this command:
./configure
make
make install
It installed in different location /usr/local/bin/php.
So now I have 2 php 5.3.3 and php 5.3.8. So I try to install it again and
run this
./configure -prefix=/usr/bin/php
make
make install
This time an error occurred:
Installing PHP SAPI module: cgi
mkdir: cannot create directory `/usr/bin/php': File exists
mkdir: cannot create directory `/usr/bin/php/bin': Not a directory
make: [install-sapi] Error 1 (ignored)
Installing PHP CGI binary: /usr/bin/php/bin/
cp: accessing `/usr/bin/php/bin/#INST@29239#': Not a directory
make: *** [install-sapi] Error 1
Please help me, I want to delete the php5.3.8 I installed in
/usr/local/bin/php and update the /usr/bin/php to php5.3.8. I need
php5.3.8 version only.
Thanks.
I want to update my php 5.3.3 to php 5.3.8, I already downloaded
PHP5.3.8.tar.gzip.
My PHP 5.3.3 located in /usr/bin/php. When I try to install
PHP5.3.8.tar.gzip and do this command:
./configure
make
make install
It installed in different location /usr/local/bin/php.
So now I have 2 php 5.3.3 and php 5.3.8. So I try to install it again and
run this
./configure -prefix=/usr/bin/php
make
make install
This time an error occurred:
Installing PHP SAPI module: cgi
mkdir: cannot create directory `/usr/bin/php': File exists
mkdir: cannot create directory `/usr/bin/php/bin': Not a directory
make: [install-sapi] Error 1 (ignored)
Installing PHP CGI binary: /usr/bin/php/bin/
cp: accessing `/usr/bin/php/bin/#INST@29239#': Not a directory
make: *** [install-sapi] Error 1
Please help me, I want to delete the php5.3.8 I installed in
/usr/local/bin/php and update the /usr/bin/php to php5.3.8. I need
php5.3.8 version only.
Thanks.
Backbone.js How to retrieve a model in a nested collection?
Backbone.js How to retrieve a model in a nested collection?
I have a PizzaType model that has a nested collection of Pizzas. The
Pizzas Collection is listed based on the Pizza Type. I would like to be
able to click on a pizza in the pizzas collection and display its
attributes.
What would be the best way to set the url params dynamically? The url does
not need a route to navigate to for bookmarking and sharing, just to
retrieve the specific resource.
I have it so that if someone wants to view the pizza type the url is
pizza_type/:id :id is the id belonging to the Pizza Type (parent model)
I currently have it so if a pizza is clicked on in the Pizzas Collection
(that belongs to the Pizza Type Model), the path to the pizza resource is
not followed; just a region on the page is updated. The url path is needed
so jQuery can get the resource to update that region. The url to the pizza
is pizza_types/:pizza_type_id/pizzas/:id Here, the :id is the id belonging
to the Pizza Model, and the :pizza_type_id is the foreign key that members
of the Pizzas Collection share to group them into the collection, that
belong to the Pizzas Type Model.
When I click on the pizza (id = 3), I get "NetworkError: 404 Not Found -
http://localhost:3000/pizza_types/3/pizzas"
Here is the Model and Collection Code:
@Pizzeria.module "Entities", (Entities, App, Backbone, Marionette, $, _) ->
class Entities.PizzaType extends Backbone.Model
urlRoot: "pizza_types/"
# creates the nested collection
initialize: ->
@pizzas = new Entities.PizzasCollection
@pizzas.url = @urlRoot + @id + '/pizzas'
@pizzas.fetch
reset: true
parse: (response) ->
response
class Entities.PizzaTypesCollection extends Backbone.Collection
model: Entities.PizzaType
url: 'pizza_types'
parse: (response) ->
response
# Is there a way to pass in a :pizza_type_id and :id params to pass to
the url() so
# that the specific pizza model can be retrieved from the collection?
class Entities.Pizza extends Backbone.Model
url: -> "pizza_types/" + 2 + "/pizzas/" + 4 # <-- Hard coded works,
but how to set the params dynamically?
parse: (data) ->
data
class Entities.PizzasCollection extends Backbone.Collection
model: Entities.Pizza
url: 'pizzas'
parse: (data) ->
data
Any suggestions? Is this the proper way, I tried to do this as well:
class Entities.Pizza extends Backbone.Model
urlRoot: -> "pizza_types"
# I thought I could pass these params in and fetch the correct
pizza model, but not working.
fetch
pizza_type_id: pizza_type_id
id: id
reset: true
parse: (data) ->
data
PizzaType Attributes with example data:
PizzaType: {
id: 2,
name: "Gourmet",
pizzas: [
0: {
id: 4,
pizza_type_id: 2
name: "gourmet pizza 1"
},
1: {
id: 5,
pizza_type_id: 2,
name: "gourmet pizza 2"
}
]
I have a PizzaType model that has a nested collection of Pizzas. The
Pizzas Collection is listed based on the Pizza Type. I would like to be
able to click on a pizza in the pizzas collection and display its
attributes.
What would be the best way to set the url params dynamically? The url does
not need a route to navigate to for bookmarking and sharing, just to
retrieve the specific resource.
I have it so that if someone wants to view the pizza type the url is
pizza_type/:id :id is the id belonging to the Pizza Type (parent model)
I currently have it so if a pizza is clicked on in the Pizzas Collection
(that belongs to the Pizza Type Model), the path to the pizza resource is
not followed; just a region on the page is updated. The url path is needed
so jQuery can get the resource to update that region. The url to the pizza
is pizza_types/:pizza_type_id/pizzas/:id Here, the :id is the id belonging
to the Pizza Model, and the :pizza_type_id is the foreign key that members
of the Pizzas Collection share to group them into the collection, that
belong to the Pizzas Type Model.
When I click on the pizza (id = 3), I get "NetworkError: 404 Not Found -
http://localhost:3000/pizza_types/3/pizzas"
Here is the Model and Collection Code:
@Pizzeria.module "Entities", (Entities, App, Backbone, Marionette, $, _) ->
class Entities.PizzaType extends Backbone.Model
urlRoot: "pizza_types/"
# creates the nested collection
initialize: ->
@pizzas = new Entities.PizzasCollection
@pizzas.url = @urlRoot + @id + '/pizzas'
@pizzas.fetch
reset: true
parse: (response) ->
response
class Entities.PizzaTypesCollection extends Backbone.Collection
model: Entities.PizzaType
url: 'pizza_types'
parse: (response) ->
response
# Is there a way to pass in a :pizza_type_id and :id params to pass to
the url() so
# that the specific pizza model can be retrieved from the collection?
class Entities.Pizza extends Backbone.Model
url: -> "pizza_types/" + 2 + "/pizzas/" + 4 # <-- Hard coded works,
but how to set the params dynamically?
parse: (data) ->
data
class Entities.PizzasCollection extends Backbone.Collection
model: Entities.Pizza
url: 'pizzas'
parse: (data) ->
data
Any suggestions? Is this the proper way, I tried to do this as well:
class Entities.Pizza extends Backbone.Model
urlRoot: -> "pizza_types"
# I thought I could pass these params in and fetch the correct
pizza model, but not working.
fetch
pizza_type_id: pizza_type_id
id: id
reset: true
parse: (data) ->
data
PizzaType Attributes with example data:
PizzaType: {
id: 2,
name: "Gourmet",
pizzas: [
0: {
id: 4,
pizza_type_id: 2
name: "gourmet pizza 1"
},
1: {
id: 5,
pizza_type_id: 2,
name: "gourmet pizza 2"
}
]
dealing with extra columns in Excel files - C#
dealing with extra columns in Excel files - C#
In my application I need to read an excel file and display the
headers(title) in a tabular format. This works fine so far. But for some
excel files it shows(excel file has 20 columns) some extra
columns(column21, column22 etc). Not sure why its showing these extra
columns when I checked the excel file it has only 20 columns and 21 or 22
columns are completely empty. Not sure why my its displaying these extra
columns. When I tried to debug the code "myReader.FieldCount" was showing
22 columns. I tried to programmatically remove those columns which are
empty. But it raised someother issues with the row data. For some rows its
shows only 18 or 15 columns as there is missing data for some columns. Is
there a better way of dealing with excel. Here is my code
@@@@@@@@@@@@@
if (sourceFile.ToUpper().IndexOf(".XLSX") >= 0) // excel 2007 or
later file
strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="
+ sourceFile + ";Extended Properties=\"Excel
12.0;HDR=No;\"";
else // previous excel versions
strConn = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source="
+ sourceFile + ";Extended Properties=\"Excel
8.0;HDR=No;\"";
OleDbConnection conn = null;
StreamWriter wrtr = null;
OleDbCommand cmd = null;
OleDbDataReader myReader = null;
try
{
conn = new OleDbConnection(strConn);
conn.Open();
cmd = new OleDbCommand("SELECT * FROM [" + worksheetName +
"]", conn);
cmd.CommandType = CommandType.Text;
myReader = cmd.ExecuteReader();
wrtr = new StreamWriter(targetFile);
while (myReader.Read())
{
List<string> builder = new List<string>();
for (int y = 0; y < myReader.FieldCount; y++)
{
if(!string.IsNullOrEmpty(myReader[y].ToString()))
builder.Add("\"" + myReader[y].ToString() +
"\"");
}
wrtr.WriteLine(string.Join(",", builder));
}
In my application I need to read an excel file and display the
headers(title) in a tabular format. This works fine so far. But for some
excel files it shows(excel file has 20 columns) some extra
columns(column21, column22 etc). Not sure why its showing these extra
columns when I checked the excel file it has only 20 columns and 21 or 22
columns are completely empty. Not sure why my its displaying these extra
columns. When I tried to debug the code "myReader.FieldCount" was showing
22 columns. I tried to programmatically remove those columns which are
empty. But it raised someother issues with the row data. For some rows its
shows only 18 or 15 columns as there is missing data for some columns. Is
there a better way of dealing with excel. Here is my code
@@@@@@@@@@@@@
if (sourceFile.ToUpper().IndexOf(".XLSX") >= 0) // excel 2007 or
later file
strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="
+ sourceFile + ";Extended Properties=\"Excel
12.0;HDR=No;\"";
else // previous excel versions
strConn = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source="
+ sourceFile + ";Extended Properties=\"Excel
8.0;HDR=No;\"";
OleDbConnection conn = null;
StreamWriter wrtr = null;
OleDbCommand cmd = null;
OleDbDataReader myReader = null;
try
{
conn = new OleDbConnection(strConn);
conn.Open();
cmd = new OleDbCommand("SELECT * FROM [" + worksheetName +
"]", conn);
cmd.CommandType = CommandType.Text;
myReader = cmd.ExecuteReader();
wrtr = new StreamWriter(targetFile);
while (myReader.Read())
{
List<string> builder = new List<string>();
for (int y = 0; y < myReader.FieldCount; y++)
{
if(!string.IsNullOrEmpty(myReader[y].ToString()))
builder.Add("\"" + myReader[y].ToString() +
"\"");
}
wrtr.WriteLine(string.Join(",", builder));
}
Predefined attributes/constants in xsd enumeration
Predefined attributes/constants in xsd enumeration
I have the following xml:
<animals>
<animal name="Pongo" animalType="Dog" />
<animal name="Marie" animalType="Cat" />
<animal name="Skippy" animalType="Kangaroo" />
</animals>
I know it is possible to restrict the type of animals using an enum like
this:
<xs:simpleType name="animalType">
<xs:restriction base="xs:string">
<xs:enumeration value="Cat" />
<xs:enumeration value="Dog" />
<xs:enumeration value="Kangaroo" />
</xs:restriction>
</xs:simpleType>
What I whould like is to know automatically, based on the animalType
value, how many shoes does the animal need, after the xml parsing.
And, when a new animal type is being added, to add also the number of
walking legs for that animal.
For instance, it would be great to be possible to define something like
<xs:simpleType name="animalType">
<xs:restriction base="xs:string">
<xs:enumeration value="Cat" nbOfShoes="4" />
<xs:enumeration value="Dog" nbOfShoes="4" />
<xs:enumeration value="Kangaroo" nbOfShoes="2" />
</xs:restriction>
</xs:simpleType>
Is it possible to achieve this using xsd, or I have to implement the
numberOfShoes logic after the xml is being parsed?
Thank you.
I have the following xml:
<animals>
<animal name="Pongo" animalType="Dog" />
<animal name="Marie" animalType="Cat" />
<animal name="Skippy" animalType="Kangaroo" />
</animals>
I know it is possible to restrict the type of animals using an enum like
this:
<xs:simpleType name="animalType">
<xs:restriction base="xs:string">
<xs:enumeration value="Cat" />
<xs:enumeration value="Dog" />
<xs:enumeration value="Kangaroo" />
</xs:restriction>
</xs:simpleType>
What I whould like is to know automatically, based on the animalType
value, how many shoes does the animal need, after the xml parsing.
And, when a new animal type is being added, to add also the number of
walking legs for that animal.
For instance, it would be great to be possible to define something like
<xs:simpleType name="animalType">
<xs:restriction base="xs:string">
<xs:enumeration value="Cat" nbOfShoes="4" />
<xs:enumeration value="Dog" nbOfShoes="4" />
<xs:enumeration value="Kangaroo" nbOfShoes="2" />
</xs:restriction>
</xs:simpleType>
Is it possible to achieve this using xsd, or I have to implement the
numberOfShoes logic after the xml is being parsed?
Thank you.
Thursday, 26 September 2013
My facebook comment plugin is working fine on Local host but not on our company dedicated server . Why?
My facebook comment plugin is working fine on Local host but not on our
company dedicated server . Why?
I have used facebook comment plugin in my website. On localhost I have
tested it it works fine. We can comment using our facebook id. But
Tommorow i just copied the same code that i have been using on localhost
to .aspx page and published it to our company dedicated server. Now the
facebook comment box is rendering on required location , people can log
into using facebook id but when to click "comment button " nothing
happens. Comment is not posting to our .aspx page . In order to confirm
that are comments going to facebook i use
http://graph.facebook.com/comments?ids="my url". But it is showing empty.
So question is why does i am not able to post comments when using Comapany
dedicated server? Thanks. regards.
company dedicated server . Why?
I have used facebook comment plugin in my website. On localhost I have
tested it it works fine. We can comment using our facebook id. But
Tommorow i just copied the same code that i have been using on localhost
to .aspx page and published it to our company dedicated server. Now the
facebook comment box is rendering on required location , people can log
into using facebook id but when to click "comment button " nothing
happens. Comment is not posting to our .aspx page . In order to confirm
that are comments going to facebook i use
http://graph.facebook.com/comments?ids="my url". But it is showing empty.
So question is why does i am not able to post comments when using Comapany
dedicated server? Thanks. regards.
Wednesday, 25 September 2013
which event of Page I can access the value of hiddenfield initialize in documet. ready function inasp.net
which event of Page I can access the value of hiddenfield initialize in
documet. ready function inasp.net
I set some hidden filed value in document.ready function In which event of
page life cycle I cant access the value of that hidden filed here is Code
$("document").ready(function () {
StatdIds = $("input[id$=hdnSelectedStateIDs]").val();
$("input[id$=hdnSupplierID]").val($("input[id$=hdnSupplierID]").val());
$("input[id$=hdnShippinRateID]").val($("input[id$=hdnShippingId]").val());
$("body").click(function (e) {
if (e.target.id != 'dvNewPostSettings-ddlFilter') {
$("#dvNewPostSettings-dvSearchFilterActions").hide();
}
});
});
and Page Code is
Protected Sub Page_Load(ByVal sender As Object, ByVal e As
System.EventArgs) Handles Me.Load
Dim supplierID As Integer = hdnSupplierID.Value
Dim ShippingRateID As Integer = hdnShippinRateID.Value
End Sub
Thank You
documet. ready function inasp.net
I set some hidden filed value in document.ready function In which event of
page life cycle I cant access the value of that hidden filed here is Code
$("document").ready(function () {
StatdIds = $("input[id$=hdnSelectedStateIDs]").val();
$("input[id$=hdnSupplierID]").val($("input[id$=hdnSupplierID]").val());
$("input[id$=hdnShippinRateID]").val($("input[id$=hdnShippingId]").val());
$("body").click(function (e) {
if (e.target.id != 'dvNewPostSettings-ddlFilter') {
$("#dvNewPostSettings-dvSearchFilterActions").hide();
}
});
});
and Page Code is
Protected Sub Page_Load(ByVal sender As Object, ByVal e As
System.EventArgs) Handles Me.Load
Dim supplierID As Integer = hdnSupplierID.Value
Dim ShippingRateID As Integer = hdnShippinRateID.Value
End Sub
Thank You
Thursday, 19 September 2013
Multiple synchronized CKEditor instances on the same page?
Multiple synchronized CKEditor instances on the same page?
I'm working on a document-editing application using CKEditor, where the
user can open multiple documents side-by-side in a pair of editor
instances.
Most of the time, the user will be editing two different documents, but
it's also possible that the two editor instances might contain different
views of the same document. That makes things tricky, since I'd like to
changes in one editor instance to be immediately reflected in the other
instance.
Without hacking the CKEditor core, is something like that possible?
If not, would it be possible to write a plugin that would provide that
kind of functionality?
What about if I was willing to get into the core code and hack around a
bit? How difficult would it be?
I'm working on a document-editing application using CKEditor, where the
user can open multiple documents side-by-side in a pair of editor
instances.
Most of the time, the user will be editing two different documents, but
it's also possible that the two editor instances might contain different
views of the same document. That makes things tricky, since I'd like to
changes in one editor instance to be immediately reflected in the other
instance.
Without hacking the CKEditor core, is something like that possible?
If not, would it be possible to write a plugin that would provide that
kind of functionality?
What about if I was willing to get into the core code and hack around a
bit? How difficult would it be?
Issue with Array assignment
Issue with Array assignment
I am having an issue with outputting an array. When I just output each
element without a for loop, the program runs fine. When I try to output
with a for loop, the program crashes the first time I set an element in
the array. I have marked the line where the program crashes when I
uncomment out the for loop. My sort seems to work fine and the program is
crashing way before that, so I'm pretty sure that isn't the issue. Any
ideas why the 2nd for loop would crash the program at the specified line?
int main()
{
int* Array;
int j = 5;
for(int i=0; i<5; i++)
{
Array[i] = j; //Crashes here with 2nd for loop uncommented
cout << Array[i] << endl;
j--;
}
Array = insertion_sort(Array);
cout << Array[0] << endl;
cout << Array[1] << endl;
cout << Array[2] << endl;
cout << Array[3] << endl;
cout << Array[4] << endl;
/*for(int k=0; k <5; k++)
{
cout << Array[k] << endl;
}*/
}
I am having an issue with outputting an array. When I just output each
element without a for loop, the program runs fine. When I try to output
with a for loop, the program crashes the first time I set an element in
the array. I have marked the line where the program crashes when I
uncomment out the for loop. My sort seems to work fine and the program is
crashing way before that, so I'm pretty sure that isn't the issue. Any
ideas why the 2nd for loop would crash the program at the specified line?
int main()
{
int* Array;
int j = 5;
for(int i=0; i<5; i++)
{
Array[i] = j; //Crashes here with 2nd for loop uncommented
cout << Array[i] << endl;
j--;
}
Array = insertion_sort(Array);
cout << Array[0] << endl;
cout << Array[1] << endl;
cout << Array[2] << endl;
cout << Array[3] << endl;
cout << Array[4] << endl;
/*for(int k=0; k <5; k++)
{
cout << Array[k] << endl;
}*/
}
regularExpressionWithPattern help. I have found a how decipher expression
regularExpressionWithPattern help. I have found a how decipher expression
I have hard time trying to decipher this expression:
[[NSRegularExpression
regularExpressionWithPattern:@"^([^:]+?):([^:]+?):([^:]+?):(.*)$"
options:NSRegularExpressionCaseInsensitive error:nil]
Any of you can help me to figure out what exactly is doing?
I'll really appreciate your help.
I have hard time trying to decipher this expression:
[[NSRegularExpression
regularExpressionWithPattern:@"^([^:]+?):([^:]+?):([^:]+?):(.*)$"
options:NSRegularExpressionCaseInsensitive error:nil]
Any of you can help me to figure out what exactly is doing?
I'll really appreciate your help.
how to save togglebutton state using shared preferences
how to save togglebutton state using shared preferences
how to let this toggle button state to be saved and used in all my
activities using shared preferences
toggle.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (toggle.isChecked()) {
textview.setTextColor(Color.WHITE);
linear.setBackgroundColor(Color.BLACK);
textview.setShadowLayer(0, 2, 2, Color.WHITE);
} else {
textview.setTextColor(Color.BLACK);
linear.setBackgroundColor(Color.WHITE);
textview.setShadowLayer(0, 2, 2, Color.BLACK);
}
}
});
any help??
how to let this toggle button state to be saved and used in all my
activities using shared preferences
toggle.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (toggle.isChecked()) {
textview.setTextColor(Color.WHITE);
linear.setBackgroundColor(Color.BLACK);
textview.setShadowLayer(0, 2, 2, Color.WHITE);
} else {
textview.setTextColor(Color.BLACK);
linear.setBackgroundColor(Color.WHITE);
textview.setShadowLayer(0, 2, 2, Color.BLACK);
}
}
});
any help??
How do I use MicropostsHelper to wrap posts when they are feed.items? Hartl Ruby On Rails Tutorial
How do I use MicropostsHelper to wrap posts when they are feed.items?
Hartl Ruby On Rails Tutorial
Following the instructions in Hartl's RoR Tutorial Listing 10.47 I made a
MicropostsHelper file to wrap Microposts with very long words.
It works just fine on the user page where Microposts are called with
<%= wrap(micropost.content) %>
But when I try to invoke it on the front page where microposts are called
with
<%= wrap(feed_item.content) %>
it does not work.
I thought perhaps I needed to make an identicle feed_itemHelper but that
didn't work at all. I assume what I need to do is let the
feed_item.content know that it can use the helper but I can't see how to
do that.
Microposts Helper
module MicropostsHelper
def wrap(content)
sanitize(raw(content.split.map{ |s| wrap_long_string(s) }.join(' ')))
end
private
def wrap_long_string(text, max_width = 30)
zero_width_space = "​"
regex = /.{1,#{max_width}}/
(text.length < max_width) ? text :
text.scan(regex).join(zero_width_space)
end
end
Hartl Ruby On Rails Tutorial
Following the instructions in Hartl's RoR Tutorial Listing 10.47 I made a
MicropostsHelper file to wrap Microposts with very long words.
It works just fine on the user page where Microposts are called with
<%= wrap(micropost.content) %>
But when I try to invoke it on the front page where microposts are called
with
<%= wrap(feed_item.content) %>
it does not work.
I thought perhaps I needed to make an identicle feed_itemHelper but that
didn't work at all. I assume what I need to do is let the
feed_item.content know that it can use the helper but I can't see how to
do that.
Microposts Helper
module MicropostsHelper
def wrap(content)
sanitize(raw(content.split.map{ |s| wrap_long_string(s) }.join(' ')))
end
private
def wrap_long_string(text, max_width = 30)
zero_width_space = "​"
regex = /.{1,#{max_width}}/
(text.length < max_width) ? text :
text.scan(regex).join(zero_width_space)
end
end
How can I convert a python string to an attribute or symbol for assignment?
How can I convert a python string to an attribute or symbol for assignment?
So basically, I'm attempting to mock by cheating with eval(). But it
doesn't seem to be syntactically viable. Curious if there is any other
way? (I'm well aware of mocking libraries for python, please don't suggest
that, although any 1-5 line techniques they use, to solve this, would be
awesome!)
>>> import os
>>> def func(*args, **kwargs):
... print "Who knows?"
...
>>> to_assign = 'os.getcwd'
>>> os.getcwd
<built-in function getcwd>
>>> eval('os.getcwd')
<built-in function getcwd>
>>> os.getcwd = func
>>> os.getcwd()
Who knows?
>>> eval('os.getcwd') = func
File "<stdin>", line 1
SyntaxError: can't assign to function call
As illustrated above, os.getcwd and eval('os.getcwd') should evaluate to
the same thing, but I can't get the assignment to happen if the eval is on
the destination side of the statement.
Also, I cannot use exec because I'm using this in a nested function with
closures.
A solution for Python 2 is preferable, but also would be good to know a
solution for Python 3 if one exists.
Thanks, Chenz
So basically, I'm attempting to mock by cheating with eval(). But it
doesn't seem to be syntactically viable. Curious if there is any other
way? (I'm well aware of mocking libraries for python, please don't suggest
that, although any 1-5 line techniques they use, to solve this, would be
awesome!)
>>> import os
>>> def func(*args, **kwargs):
... print "Who knows?"
...
>>> to_assign = 'os.getcwd'
>>> os.getcwd
<built-in function getcwd>
>>> eval('os.getcwd')
<built-in function getcwd>
>>> os.getcwd = func
>>> os.getcwd()
Who knows?
>>> eval('os.getcwd') = func
File "<stdin>", line 1
SyntaxError: can't assign to function call
As illustrated above, os.getcwd and eval('os.getcwd') should evaluate to
the same thing, but I can't get the assignment to happen if the eval is on
the destination side of the statement.
Also, I cannot use exec because I'm using this in a nested function with
closures.
A solution for Python 2 is preferable, but also would be good to know a
solution for Python 3 if one exists.
Thanks, Chenz
how to load activator in intellij with sbt plugin
how to load activator in intellij with sbt plugin
I'm pretty novice on sbt. I looked at activator project
now i see it uses sbt and there are sbt and scala files under project
directory. but i was sure there would also be like a main sbt (like main
pom) in main directory where i can open it in intellij with sbt plugin and
it would open all projects in the IDE.
can anyone please let me know how to open this project in intellij with
all its dependencies most probably with intellij sbt plugin because it
uses sbt (i mean like in maven would bring all sub dependencies)
I'm pretty novice on sbt. I looked at activator project
now i see it uses sbt and there are sbt and scala files under project
directory. but i was sure there would also be like a main sbt (like main
pom) in main directory where i can open it in intellij with sbt plugin and
it would open all projects in the IDE.
can anyone please let me know how to open this project in intellij with
all its dependencies most probably with intellij sbt plugin because it
uses sbt (i mean like in maven would bring all sub dependencies)
Wednesday, 18 September 2013
XMPP framework XEP-0136 implementation in iOS client
XMPP framework XEP-0136 implementation in iOS client
I am working on the iOS chat client application. Now I want to store the
chat history in the device and server, I looked in the google and found
that I can do it with the XEP-0136 extension. I looked into it but didn't
got any idea about how to implement. If anyone has used or have any link
to tutorial which can help me than please share it.
Thanks in Advance
I am working on the iOS chat client application. Now I want to store the
chat history in the device and server, I looked in the google and found
that I can do it with the XEP-0136 extension. I looked into it but didn't
got any idea about how to implement. If anyone has used or have any link
to tutorial which can help me than please share it.
Thanks in Advance
Linking multiple TraceSource events with CorrelationManager
Linking multiple TraceSource events with CorrelationManager
I am developing a web service in C# with .NET WebAPI and I would like to
log multiple events for every request, into Windows event log. Since the
service runs in a multithreaded model and will receive hundreds or
requests per second, I need to be able to group log entries by requests,
so that I can see all the entries for a failed request for example.
The plan is to generate a unique Id (Guid) for every request and log event
with a severity level (Verbose/Information/Error/Warning/Critical)
including the Id in every log entry, so that I can group the events.
After trying with NLog, I started looking into
System.Diagnostics.TraceSource in combination with
System.Diagnostics.Trace.CorrelationManager.ActivityId, following articles
found online, many here on SO. Logging works but I'm stuck on two
problems.
My web.config:
<system.diagnostics>
<sources>
<source name="My.App" switchValue="Verbose, ActivityTracing">
<listeners>
<add name="eventlogListener" />
</listeners>
</source>
</sources>
<sharedListeners>
<add name="eventlogListener"
type="System.Diagnostics.EventLogTraceListener"
initializeData="MyAppCategory" />
</sharedListeners>
</system.diagnostics>
Problem 1
If I use TraceTransfer I can specify the ActivityId (which is
automatically appended to the message) but I cannot specify the event
level (e.g. TraceEventType.Error)
If I use TraceEvent I can specify the level but not the ActivityId, and
the Activity Id does not appear anywhere
Is there a way to have both level and activity id in a log event ?
Problem 2
I would like to see the ActivityId in the "Correlation Id" column of the
event viewer, so that I can group events. I've seen some applications
storing a Guid there, but I haven't found any documentation on how to
achieve the same in C#/.NET. I noticed that TraceEvent accepts a object[]
args parameter, for which I have not found any example though.
Could anyone point me to some docs or provide a working example ?
Thank you
I am developing a web service in C# with .NET WebAPI and I would like to
log multiple events for every request, into Windows event log. Since the
service runs in a multithreaded model and will receive hundreds or
requests per second, I need to be able to group log entries by requests,
so that I can see all the entries for a failed request for example.
The plan is to generate a unique Id (Guid) for every request and log event
with a severity level (Verbose/Information/Error/Warning/Critical)
including the Id in every log entry, so that I can group the events.
After trying with NLog, I started looking into
System.Diagnostics.TraceSource in combination with
System.Diagnostics.Trace.CorrelationManager.ActivityId, following articles
found online, many here on SO. Logging works but I'm stuck on two
problems.
My web.config:
<system.diagnostics>
<sources>
<source name="My.App" switchValue="Verbose, ActivityTracing">
<listeners>
<add name="eventlogListener" />
</listeners>
</source>
</sources>
<sharedListeners>
<add name="eventlogListener"
type="System.Diagnostics.EventLogTraceListener"
initializeData="MyAppCategory" />
</sharedListeners>
</system.diagnostics>
Problem 1
If I use TraceTransfer I can specify the ActivityId (which is
automatically appended to the message) but I cannot specify the event
level (e.g. TraceEventType.Error)
If I use TraceEvent I can specify the level but not the ActivityId, and
the Activity Id does not appear anywhere
Is there a way to have both level and activity id in a log event ?
Problem 2
I would like to see the ActivityId in the "Correlation Id" column of the
event viewer, so that I can group events. I've seen some applications
storing a Guid there, but I haven't found any documentation on how to
achieve the same in C#/.NET. I noticed that TraceEvent accepts a object[]
args parameter, for which I have not found any example though.
Could anyone point me to some docs or provide a working example ?
Thank you
3D to 2D? simplest way?
3D to 2D? simplest way?
I have question: how to simple "convert" 3D to 2D? I actualy play with
microcontrollers(AVR) and some time ago connect LCD from old phone. I want
to render some simples(cube), i have formulas to rotate, move, etc... BUT
i cant display it all cos cant covert 3D(wich action happens in RAM) to 2D
simple points on screen wich i connect with line. ive tryed some ways i
found on internet: x'=-z*sin(a)+x*cos(a)
y'=-(z*cos(a)+x*sin(a))*sin(b)+y*Cos(b) or some like that, but it ot seems
to work.
P.S. Dont tell me some like: Google is your friend, etc.
I have question: how to simple "convert" 3D to 2D? I actualy play with
microcontrollers(AVR) and some time ago connect LCD from old phone. I want
to render some simples(cube), i have formulas to rotate, move, etc... BUT
i cant display it all cos cant covert 3D(wich action happens in RAM) to 2D
simple points on screen wich i connect with line. ive tryed some ways i
found on internet: x'=-z*sin(a)+x*cos(a)
y'=-(z*cos(a)+x*sin(a))*sin(b)+y*Cos(b) or some like that, but it ot seems
to work.
P.S. Dont tell me some like: Google is your friend, etc.
Haskel type declaration, function and tuple as arguments
Haskel type declaration, function and tuple as arguments
I'm doing a haskell assignment for school. I want to make a function
called MapTuple, wich maps a function with a tuple as its arguments for an
array of tuple. Im declaring it on the following way:
MapTuple :: [(a,b)] -> (a -> b) -> [b]
the way i want to use the function is as follows.
MapTuple :: [(Int, String)] -> (Int -> String) -> [String]
problem however is that I get the following error when compiling:
Invalid type signature: MapTuple :: ([(a, b)]) -> (a -> b) -> [b] Should
be of form ::
What am I doing wrong?
Thanks a lot for helping me in advance!
I'm doing a haskell assignment for school. I want to make a function
called MapTuple, wich maps a function with a tuple as its arguments for an
array of tuple. Im declaring it on the following way:
MapTuple :: [(a,b)] -> (a -> b) -> [b]
the way i want to use the function is as follows.
MapTuple :: [(Int, String)] -> (Int -> String) -> [String]
problem however is that I get the following error when compiling:
Invalid type signature: MapTuple :: ([(a, b)]) -> (a -> b) -> [b] Should
be of form ::
What am I doing wrong?
Thanks a lot for helping me in advance!
How to use Chrome content scripts to automate web page interaction and nested navigations
How to use Chrome content scripts to automate web page interaction and
nested navigations
I am trying to control chrome from my C# application.
I am looking to establish a fairly simplistic API between my C#
application and Chrome.
- Navigate to url
- Find HTML element based on some criteria (typically to be done via jQuery)
- Click on the selected element
- Repeat as needed
My C# program will manage multiple Chrome instances doing this kind of work.
The solution that I am trying to implement is to use Chrome extension
'content' scripts
Here's my current Manifest.json:
{
"name": "ScraperAPI",
"manifest_version": 2,
"version": "0.0.1",
"content_scripts": [
{
"matches": [ "<all_urls>" ],
"js": [ "AutomationApi.js"],
"run_at" : "document_start",
"all_frames" : false
}
],
"permissions": [ "tabs", "http://*/*", "storage" ]
"web_accessible_resources": [ "jQuery.min.v.2.0.3.map" ]
}
The content script uses a WebSocket to communicate with my C# application
So far, the WebSocket works very well for communicating API requests (such
as 'navigate') and responses (such as 'document ready').
My extension listens to document ready and opens up a WebSocket to my C#
program. - This works
My issues are:
[1] How to get the content script to launch automatically when Chrome
comes up? It appears that until I manually enter a URL at the navigateion
bar, my extension is not loaded
How can the content script recognize that it is running for the first time
in the chrome instance?
[2] How to maintain general state for the content script across page loads.
In particular, the C# program uses the content script to navigate to a
URL, find a particular HTML element, click on it, and after 'document
ready' it then wants to continue browsing and further clicking on the
page.
Unfortunately (for me), each time a page is loaded, Chrome loads a new
instance of the content script.
==> I don't know how to have the script determine whether it is running
for the first time or not.
On the first time through it has to open a WebSocket to the C#. On
subsequent loads in the same tab
I want it to recognize that the WebSocket connection exists and
continue using it.
I tried to create a 'window.myApi' object to save data, but each page
seems to get a new window object.
I was going to try to use 'local storage' but that is shared between
all local instances of all the scripts
and a fresh instance of the content script does not know whether it is
running for first time or not.
By the way, when my content script opens a WebSocket to the C#, the C#
responds with a unique id (GUID) so
all further communications use this unique id in the messages.
It would be great if a content script can tell if it has been assigned
a unique id by the C# program.
Is there an 'uber' window for the entire Chrome instance that I can
latch onto?
Should I be using a different approach (not using content scripts) to
automate Chrome sessions?
Is there an approach to saving state that I missed?
Any help would be greatly appreciated.
-Many thanks in advance Davud
nested navigations
I am trying to control chrome from my C# application.
I am looking to establish a fairly simplistic API between my C#
application and Chrome.
- Navigate to url
- Find HTML element based on some criteria (typically to be done via jQuery)
- Click on the selected element
- Repeat as needed
My C# program will manage multiple Chrome instances doing this kind of work.
The solution that I am trying to implement is to use Chrome extension
'content' scripts
Here's my current Manifest.json:
{
"name": "ScraperAPI",
"manifest_version": 2,
"version": "0.0.1",
"content_scripts": [
{
"matches": [ "<all_urls>" ],
"js": [ "AutomationApi.js"],
"run_at" : "document_start",
"all_frames" : false
}
],
"permissions": [ "tabs", "http://*/*", "storage" ]
"web_accessible_resources": [ "jQuery.min.v.2.0.3.map" ]
}
The content script uses a WebSocket to communicate with my C# application
So far, the WebSocket works very well for communicating API requests (such
as 'navigate') and responses (such as 'document ready').
My extension listens to document ready and opens up a WebSocket to my C#
program. - This works
My issues are:
[1] How to get the content script to launch automatically when Chrome
comes up? It appears that until I manually enter a URL at the navigateion
bar, my extension is not loaded
How can the content script recognize that it is running for the first time
in the chrome instance?
[2] How to maintain general state for the content script across page loads.
In particular, the C# program uses the content script to navigate to a
URL, find a particular HTML element, click on it, and after 'document
ready' it then wants to continue browsing and further clicking on the
page.
Unfortunately (for me), each time a page is loaded, Chrome loads a new
instance of the content script.
==> I don't know how to have the script determine whether it is running
for the first time or not.
On the first time through it has to open a WebSocket to the C#. On
subsequent loads in the same tab
I want it to recognize that the WebSocket connection exists and
continue using it.
I tried to create a 'window.myApi' object to save data, but each page
seems to get a new window object.
I was going to try to use 'local storage' but that is shared between
all local instances of all the scripts
and a fresh instance of the content script does not know whether it is
running for first time or not.
By the way, when my content script opens a WebSocket to the C#, the C#
responds with a unique id (GUID) so
all further communications use this unique id in the messages.
It would be great if a content script can tell if it has been assigned
a unique id by the C# program.
Is there an 'uber' window for the entire Chrome instance that I can
latch onto?
Should I be using a different approach (not using content scripts) to
automate Chrome sessions?
Is there an approach to saving state that I missed?
Any help would be greatly appreciated.
-Many thanks in advance Davud
how to resolve optional url path using ng-resource
how to resolve optional url path using ng-resource
There are restful APIs, for instance:
/players - to get list for all players
/players{/playerName} - to get info for specific player
and I already have a function using ng-resource like:
function Play() {
return $resource('/players');
}
Can I reuse this function for specific player like:
function Play(name) {
return $resource('/players/:name', {
name: name
});
}
so I want to...
send request for /players if I didn't pass name parameter.
send request for /players/someone if I passed name parameter with someone
Otherwise, I have to write another function for specific play?
There are restful APIs, for instance:
/players - to get list for all players
/players{/playerName} - to get info for specific player
and I already have a function using ng-resource like:
function Play() {
return $resource('/players');
}
Can I reuse this function for specific player like:
function Play(name) {
return $resource('/players/:name', {
name: name
});
}
so I want to...
send request for /players if I didn't pass name parameter.
send request for /players/someone if I passed name parameter with someone
Otherwise, I have to write another function for specific play?
Equivalent to Image GD in Javascript?
Equivalent to Image GD in Javascript?
I come from a staunch PHP background and use image gd library for heavy
image manipulation.
Is there any library in JS which is somewhat equivalent to this ? like
I can write text above canvas image Format that text Merge a smaller image
above a background image
and some features like that.
Sorry I'm not a a graphics guy, so really don't know the terms to use.
I come from a staunch PHP background and use image gd library for heavy
image manipulation.
Is there any library in JS which is somewhat equivalent to this ? like
I can write text above canvas image Format that text Merge a smaller image
above a background image
and some features like that.
Sorry I'm not a a graphics guy, so really don't know the terms to use.
Tuesday, 17 September 2013
Modify height/width of drop target area of WPF
Modify height/width of drop target area of WPF
I've been researching on this but can't find an answer. Is is possible to
change the height and width of the drop target area of WPF? tia
can't post an image yet due to insufficient reputation. Check it here
I've been researching on this but can't find an answer. Is is possible to
change the height and width of the drop target area of WPF? tia
can't post an image yet due to insufficient reputation. Check it here
Extracting semi-structured user generated content from web pages using Python
Extracting semi-structured user generated content from web pages using Python
I am working on a project for which I need to extract chords played over
song lyrics. The goal is to find what part of lyrics are played under
which chord. I'm using web pages containing guitar chords from
ultimate-guitar.com (I chose this site because it seems to have largest
collection of transcribed songs)
The typical structure of web page is:
For example:
http://tabs.ultimate-guitar.com/p/poets_of_the_fall/carnival_of_rust_crd.htm
Snippet:
As you can see, the chords are written on line before lyrics and the
relative position from left margin decides which chord is played over
which words. The page source for the above song looks like:
My strategy to accomplish the task:
1) Find the above relevant portion (ignore ads, indexes on web page) of
web page using beautiful soup
2) Read this portion line by line.
3) Use <span> tag to identify which lines contain chords.
4) Assume the next line following line having <span> tags is going to
contain lyrics
5) Find out relative position of each chord, store it and compare it to
position of words in line below to find out which chords are played over
what chords.
6) Store this data in a dictionary with chord name as key and value would
be list of phrases played over this key chord.
The above implementation works fine in some cases, but since there's no
specific structure defined, it fails miserably whenever the assumed
structure of page is not followed.
For example, (Source:
http://tabs.ultimate-guitar.com/k/kate_voegele/all_i_see_crd.htm)
Here there are unexpected '\<\pre><\i></i>' tags before and now my key is
stored as "<\pre><\i></i>D" instead of just "D". (Apologies, I had to
insert extra "\" here else tags weren't visible.)
And there are many such errors in my parsed data because of this
unexpected variation in structure of page. Any ideas on how these kind of
cases could be handled or is there a better way to accomplish this task?
I am working on a project for which I need to extract chords played over
song lyrics. The goal is to find what part of lyrics are played under
which chord. I'm using web pages containing guitar chords from
ultimate-guitar.com (I chose this site because it seems to have largest
collection of transcribed songs)
The typical structure of web page is:
For example:
http://tabs.ultimate-guitar.com/p/poets_of_the_fall/carnival_of_rust_crd.htm
Snippet:
As you can see, the chords are written on line before lyrics and the
relative position from left margin decides which chord is played over
which words. The page source for the above song looks like:
My strategy to accomplish the task:
1) Find the above relevant portion (ignore ads, indexes on web page) of
web page using beautiful soup
2) Read this portion line by line.
3) Use <span> tag to identify which lines contain chords.
4) Assume the next line following line having <span> tags is going to
contain lyrics
5) Find out relative position of each chord, store it and compare it to
position of words in line below to find out which chords are played over
what chords.
6) Store this data in a dictionary with chord name as key and value would
be list of phrases played over this key chord.
The above implementation works fine in some cases, but since there's no
specific structure defined, it fails miserably whenever the assumed
structure of page is not followed.
For example, (Source:
http://tabs.ultimate-guitar.com/k/kate_voegele/all_i_see_crd.htm)
Here there are unexpected '\<\pre><\i></i>' tags before and now my key is
stored as "<\pre><\i></i>D" instead of just "D". (Apologies, I had to
insert extra "\" here else tags weren't visible.)
And there are many such errors in my parsed data because of this
unexpected variation in structure of page. Any ideas on how these kind of
cases could be handled or is there a better way to accomplish this task?
Steal username and password from cookies
Steal username and password from cookies
Hello I have a website that people can connect with it from a login area
made with php + some cookies functions . The problem is one of my enemies
always login with my admin username and password and modify my website . I
want to know how hackers could steal ur username and password of admins
from cookies . Please help me Your answer will help alot of other victims
of this hack like me and here is my code that I use into my website.
switch($method){
case 'login';
$user_name =
addslashes(trim($_POST['user_name']));
$user_pass =
addslashes(md5($_POST['user_pass']));
if(isset($user_name) and isset($user_pass)
and $user_name != '' and $user_pass != ''){
if(is_in_db($user_name) > 0){
if(check_pass($user_name,$user_pass)){
setcookie('user_name_cookie',$user_name,time(. )+(60*60*24*30));
setcookie('user_pass_cookie',$user_pass,time()+. (60*60*24*30));
}
}
}
break;
Hello I have a website that people can connect with it from a login area
made with php + some cookies functions . The problem is one of my enemies
always login with my admin username and password and modify my website . I
want to know how hackers could steal ur username and password of admins
from cookies . Please help me Your answer will help alot of other victims
of this hack like me and here is my code that I use into my website.
switch($method){
case 'login';
$user_name =
addslashes(trim($_POST['user_name']));
$user_pass =
addslashes(md5($_POST['user_pass']));
if(isset($user_name) and isset($user_pass)
and $user_name != '' and $user_pass != ''){
if(is_in_db($user_name) > 0){
if(check_pass($user_name,$user_pass)){
setcookie('user_name_cookie',$user_name,time(. )+(60*60*24*30));
setcookie('user_pass_cookie',$user_pass,time()+. (60*60*24*30));
}
}
}
break;
Error compiling source code at Java
Error compiling source code at Java
I have this code:
package org.test;
import org.test.utils.Logger;
public class Test
{
public static void main(String[] args)
{
}
}
At file:
/var/www/test/src/org/test/Test.java
And this other file:
package org.test.utils;
public class Loger
{
private static Logger currentLogger = null;
@SuppressWarnings("unused")
private static Logger getInstance()
{
if (currentLogger == null)
{
Logger.currentLogger = new Logger();
}
return Logger.currentLogger;
}
public static void write(String message) {
// TODO You must implement this method
}
}
At file:
/var/www/test/src/org/test/utils/Logger.java
But when I compile it from sublime, it says:
Compiling Java sourcecode...
Test.java:3: error: package org.test.utils does not exist
import org.test.utils.Logger;
^
1 error
Compiling error, no .class file created
[Finished in 0.8s]
I'm using this manual:
http://binarydaydreams.wordpress.com/2012/08/08/compiling-java-with-sublimetext2-on-ubuntu/
I'm newbbie at Java... What am I doing wrong?
I have this code:
package org.test;
import org.test.utils.Logger;
public class Test
{
public static void main(String[] args)
{
}
}
At file:
/var/www/test/src/org/test/Test.java
And this other file:
package org.test.utils;
public class Loger
{
private static Logger currentLogger = null;
@SuppressWarnings("unused")
private static Logger getInstance()
{
if (currentLogger == null)
{
Logger.currentLogger = new Logger();
}
return Logger.currentLogger;
}
public static void write(String message) {
// TODO You must implement this method
}
}
At file:
/var/www/test/src/org/test/utils/Logger.java
But when I compile it from sublime, it says:
Compiling Java sourcecode...
Test.java:3: error: package org.test.utils does not exist
import org.test.utils.Logger;
^
1 error
Compiling error, no .class file created
[Finished in 0.8s]
I'm using this manual:
http://binarydaydreams.wordpress.com/2012/08/08/compiling-java-with-sublimetext2-on-ubuntu/
I'm newbbie at Java... What am I doing wrong?
Contact page redirect issue
Contact page redirect issue
For some reason my contact page won't relocate to thanks.html. It just
stays at the contact page and the contact form disappears.
<?php
if (empty($_POST) === false) {
$errors = array();
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
if (empty($name) === true || empty($email) === true || empty($message) ===
true) {
$errors[] = 'Name, email, and message are required.';
} else {
if (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
$errors[] = 'Please enter a valad email address.';
}
}
if (empty($errors) === true) {
mail('joe@mydomain.com', 'Contact Form' ,'$message', 'From: ' . $email);
header('Location: thanks.html');
exit();
}
}
?>
Here is my code from the form as well.
<?php
if (empty($errors) === false) {
echo '<ul>';
foreach($errors as $error) {
echo '<li>', $error, '</li>';
}
echo '<ul>';
}
?>
</div>
<div id="content">
<form action="" method="post">
<p>
<label for="name">Name:</label><br />
<input type="text" name="name" id="name" <?php if (isset($_POST['name'])
=== true) { echo 'value="',
strip_tags($_POST['name']), '"'; } ?> />
</p>
<p>
<label for="email">Email:</label><br />
<input type="text" name="email" id="email" <?php if
(isset($_POST['email']) === true) { echo 'value="',
strip_tags($_POST['email']), '"'; } ?>/>
</p>
<p>
<label for="message">Message:</label><br />
<textarea name="message" id="message"><?php if (isset($_POST['message'])
=== true) { echo strip_tags($_POST['message']), ''; } ?></textarea>
</p>
<p>
<input type="submit" />
</p>
</form>
</div>
Anyone have a quick fix for this? It's driving me crazy. I've been trying
different variations of these lines in the code above but nothing is
working...
if (empty($errors) === true) {
mail('joe@mydomain.com', 'Contact Form' ,'$message', 'From: ' . $email);
header('Location: thanks.html');
exit();
For some reason my contact page won't relocate to thanks.html. It just
stays at the contact page and the contact form disappears.
<?php
if (empty($_POST) === false) {
$errors = array();
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
if (empty($name) === true || empty($email) === true || empty($message) ===
true) {
$errors[] = 'Name, email, and message are required.';
} else {
if (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
$errors[] = 'Please enter a valad email address.';
}
}
if (empty($errors) === true) {
mail('joe@mydomain.com', 'Contact Form' ,'$message', 'From: ' . $email);
header('Location: thanks.html');
exit();
}
}
?>
Here is my code from the form as well.
<?php
if (empty($errors) === false) {
echo '<ul>';
foreach($errors as $error) {
echo '<li>', $error, '</li>';
}
echo '<ul>';
}
?>
</div>
<div id="content">
<form action="" method="post">
<p>
<label for="name">Name:</label><br />
<input type="text" name="name" id="name" <?php if (isset($_POST['name'])
=== true) { echo 'value="',
strip_tags($_POST['name']), '"'; } ?> />
</p>
<p>
<label for="email">Email:</label><br />
<input type="text" name="email" id="email" <?php if
(isset($_POST['email']) === true) { echo 'value="',
strip_tags($_POST['email']), '"'; } ?>/>
</p>
<p>
<label for="message">Message:</label><br />
<textarea name="message" id="message"><?php if (isset($_POST['message'])
=== true) { echo strip_tags($_POST['message']), ''; } ?></textarea>
</p>
<p>
<input type="submit" />
</p>
</form>
</div>
Anyone have a quick fix for this? It's driving me crazy. I've been trying
different variations of these lines in the code above but nothing is
working...
if (empty($errors) === true) {
mail('joe@mydomain.com', 'Contact Form' ,'$message', 'From: ' . $email);
header('Location: thanks.html');
exit();
Error in converting NSArray to JSON
Error in converting NSArray to JSON
I have NSArray with NSDictionaries inside. I need to post JSON. So I tried
to make post request with NSURLConnection, but I'm given an error (bad
url). I convert NSArray such direction:
NSData *dishesData = [NSJSONSerialization dataWithJSONObject:dishes
options:NSJSONWritingPrettyPrinted error:&error];
NSString *dishesString = [[NSString alloc] initWithData:dishesData
encoding:NSUTF8StringEncoding];
Then paste it to NSString with request.
NSString *requestString = [NSString
stringWithFormat:@"%@%@=%@&%@=%@&%@=%@&%@=%@&%@=%@&%@=%@&%@=%@",
SERVER_ADDRESS, ACTION, ORDER_ACTION, ORDER_NAME, name, ORDER_EMAIL,
email, ORDER_PHONE, phone, ORDER_DELIVERY, delivery, ORDER_ADDRESS,
address, ORDER_DISHES, dishesString];
Then I log 1st time:
2013-09-17 20:01:13.926 Eda.by[3088:c07]
http://eda.by/api.php?act=order&name=Òèìóð&email=bernikowich@testemail2.com&phone=+375296802009&delivery=1&address=Òåñòîâûé
àäðåñ!&dish=[
{
"count" : 2,
"id" : 86
}
]
If I'll try to post this I'll get error "bad url". Thats why I try to
encode this by:
requestString = [requestString
stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
After that I get such logs:
http://eda.by/api.php?act=order&name=%D0%A2%D0%B8%D0%BC%D1%83%D1%80&email=bernikowich@testemail2.com&phone=+375296802009&delivery=1&address=%D0%A2%D0%B5%D1%81%D1%82%D0%BE%D0%B2%D1%8B%D0%B9%20%D0%B0%D0%B4%D1%80%D0%B5%D1%81!&dish=%5B%0A%20%20%7B%0A%20%20%20%20%22count%22%20:%202,%0A%20%20%20%20%22id%22%20:%2086%0A%20%20%7D%0A%5D
It sends well, but data are wrong and won't work.
I have NSArray with NSDictionaries inside. I need to post JSON. So I tried
to make post request with NSURLConnection, but I'm given an error (bad
url). I convert NSArray such direction:
NSData *dishesData = [NSJSONSerialization dataWithJSONObject:dishes
options:NSJSONWritingPrettyPrinted error:&error];
NSString *dishesString = [[NSString alloc] initWithData:dishesData
encoding:NSUTF8StringEncoding];
Then paste it to NSString with request.
NSString *requestString = [NSString
stringWithFormat:@"%@%@=%@&%@=%@&%@=%@&%@=%@&%@=%@&%@=%@&%@=%@",
SERVER_ADDRESS, ACTION, ORDER_ACTION, ORDER_NAME, name, ORDER_EMAIL,
email, ORDER_PHONE, phone, ORDER_DELIVERY, delivery, ORDER_ADDRESS,
address, ORDER_DISHES, dishesString];
Then I log 1st time:
2013-09-17 20:01:13.926 Eda.by[3088:c07]
http://eda.by/api.php?act=order&name=Òèìóð&email=bernikowich@testemail2.com&phone=+375296802009&delivery=1&address=Òåñòîâûé
àäðåñ!&dish=[
{
"count" : 2,
"id" : 86
}
]
If I'll try to post this I'll get error "bad url". Thats why I try to
encode this by:
requestString = [requestString
stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
After that I get such logs:
http://eda.by/api.php?act=order&name=%D0%A2%D0%B8%D0%BC%D1%83%D1%80&email=bernikowich@testemail2.com&phone=+375296802009&delivery=1&address=%D0%A2%D0%B5%D1%81%D1%82%D0%BE%D0%B2%D1%8B%D0%B9%20%D0%B0%D0%B4%D1%80%D0%B5%D1%81!&dish=%5B%0A%20%20%7B%0A%20%20%20%20%22count%22%20:%202,%0A%20%20%20%20%22id%22%20:%2086%0A%20%20%7D%0A%5D
It sends well, but data are wrong and won't work.
Sunday, 15 September 2013
Spring how to inject a bean for a Handler of xsocket?
Spring how to inject a bean for a Handler of xsocket?
I use xsocket to implement a socket server, and the handler of xsocket
need inject an bean to do something. But, the reference aliway be NULL, I
had logged the setter method, the setter method had been excused and the
bean is not null in the log.
public class SocketServerHandler implements IDataHandler, IConnectHandler,
IIdleTimeoutHandler, IConnectionTimeoutHandler, IDisconnectHandler,
ApplicationContextAware {
private APIInvokeServer apiInvokeServer;
@Override
public boolean onData(INonBlockingConnection connection) throws
IOException, BufferUnderflowException,ClosedChannelException,
MaxReadSizeExceededException {
// read from connection
String message = parseMessage(connection);
final APIInvokeRequest invokeRequest;
invokeRequest = apiInvokeServer.createInvokeRequest(trace);
balabala...
}
public void setApiInvokeServer(APIInvokeServer apiInvokeServer) {
OceanLog.system.error("--------setApiInvokeServer--------" +
apiInvokeServer);
this.apiInvokeServer = apiInvokeServer;
}
}
and spring xml file:
<bean id="socketServerHandler"
class="com.alibaba.ocean.listener.socket.SocketServerHandler">
<property name="apiInvokeServer" ref="apiInvokeServer"/>
</bean>
The log white:
--------setApiInvokeServer--------com.alibaba.openapi.invoke.server.DefaultAPIInvokeServer@468a169f
thus, setter method has been called, but why when I debug the code,
apiInvokeServer is NULL???
I use xsocket to implement a socket server, and the handler of xsocket
need inject an bean to do something. But, the reference aliway be NULL, I
had logged the setter method, the setter method had been excused and the
bean is not null in the log.
public class SocketServerHandler implements IDataHandler, IConnectHandler,
IIdleTimeoutHandler, IConnectionTimeoutHandler, IDisconnectHandler,
ApplicationContextAware {
private APIInvokeServer apiInvokeServer;
@Override
public boolean onData(INonBlockingConnection connection) throws
IOException, BufferUnderflowException,ClosedChannelException,
MaxReadSizeExceededException {
// read from connection
String message = parseMessage(connection);
final APIInvokeRequest invokeRequest;
invokeRequest = apiInvokeServer.createInvokeRequest(trace);
balabala...
}
public void setApiInvokeServer(APIInvokeServer apiInvokeServer) {
OceanLog.system.error("--------setApiInvokeServer--------" +
apiInvokeServer);
this.apiInvokeServer = apiInvokeServer;
}
}
and spring xml file:
<bean id="socketServerHandler"
class="com.alibaba.ocean.listener.socket.SocketServerHandler">
<property name="apiInvokeServer" ref="apiInvokeServer"/>
</bean>
The log white:
--------setApiInvokeServer--------com.alibaba.openapi.invoke.server.DefaultAPIInvokeServer@468a169f
thus, setter method has been called, but why when I debug the code,
apiInvokeServer is NULL???
Intermittent "too many open files" when including/requiring PHP scripts
Intermittent "too many open files" when including/requiring PHP scripts
On my development box (thank goodness it's not happening in
production—that I know of—yet), as I'm working on a PHP site, I get this
occasional error:
Warning: require_once(filename.php): failed to open stream: Too many open
files in path/functions.php on line 502
Fatal error: require_once(): Failed opening required 'filename.php'
(include_path='my_include_path') in path/functions.php on line 502
Line 502 of functions.php is my "autoload" function, so I don't have to
manually "require_once" files of classes I'm using:
function autoload($className)
{
require_once $className . ".php"; // <-- Line 502
}
By an "occasional" error, I mean that it'll work fine for about a day of
development, then when I first see this, I can refresh the page and it'll
be okay again, then refreshing gives me the same error. This happens just
a few times before it starts to show it every time. And sometimes the name
of the file it's requiring (I have a script split out into several PHP
files) is different... it's not always the first or last or middle files
that it bombs on.
Restarting php-fpm seems to solve the symptoms, but not the problem in the
long run.
I'm running PHP 5.5.3 on my Mac (OS X 10.8) with nginx 1.4.2 via php-fpm.
Running lsof | grep php-fpm | wc -l tells me that php-fpm has 824 files
open. When I examined the actual output, I saw that, along with some .so
and .dylib files, the vast majority of lines were like this:
php-fpm 4093 myuser 69u unix 0x45bc1a64810eb32b 0t0 ->(none)
The segment "69u" and the 0x45bc1a6481... number are different on each
row. What could this mean? Is this the problem? (ulimit is "unlimited")
Incidentally, though perhaps un-related, there's also one or two of these:
php-fpm 4093 myuser 8u IPv4 0x45bc1a646b0f97b3 0t0 TCP
192.168.1.2:59611->rest.nexmo.com:https (CLOSE_WAIT)
(I have some pages which use HttpRequest (PECL libraries) to call out to
the Nexmo API. Are these not being closed properly or something? How can I
crack down on those?)
On my development box (thank goodness it's not happening in
production—that I know of—yet), as I'm working on a PHP site, I get this
occasional error:
Warning: require_once(filename.php): failed to open stream: Too many open
files in path/functions.php on line 502
Fatal error: require_once(): Failed opening required 'filename.php'
(include_path='my_include_path') in path/functions.php on line 502
Line 502 of functions.php is my "autoload" function, so I don't have to
manually "require_once" files of classes I'm using:
function autoload($className)
{
require_once $className . ".php"; // <-- Line 502
}
By an "occasional" error, I mean that it'll work fine for about a day of
development, then when I first see this, I can refresh the page and it'll
be okay again, then refreshing gives me the same error. This happens just
a few times before it starts to show it every time. And sometimes the name
of the file it's requiring (I have a script split out into several PHP
files) is different... it's not always the first or last or middle files
that it bombs on.
Restarting php-fpm seems to solve the symptoms, but not the problem in the
long run.
I'm running PHP 5.5.3 on my Mac (OS X 10.8) with nginx 1.4.2 via php-fpm.
Running lsof | grep php-fpm | wc -l tells me that php-fpm has 824 files
open. When I examined the actual output, I saw that, along with some .so
and .dylib files, the vast majority of lines were like this:
php-fpm 4093 myuser 69u unix 0x45bc1a64810eb32b 0t0 ->(none)
The segment "69u" and the 0x45bc1a6481... number are different on each
row. What could this mean? Is this the problem? (ulimit is "unlimited")
Incidentally, though perhaps un-related, there's also one or two of these:
php-fpm 4093 myuser 8u IPv4 0x45bc1a646b0f97b3 0t0 TCP
192.168.1.2:59611->rest.nexmo.com:https (CLOSE_WAIT)
(I have some pages which use HttpRequest (PECL libraries) to call out to
the Nexmo API. Are these not being closed properly or something? How can I
crack down on those?)
Change visual of histogram from image using matplotlib in Python
Change visual of histogram from image using matplotlib in Python
I would like to present a histogram from an image in Python. Doing some
research, I found a way of doing it using matplotlib. So, I just do this:
im = plt.array(Image.open('Mean.png').convert('L'))
plt.figure()
plt.hist(im, facecolor='green', alpha=0.75)
plt.savefig("Histogram.png")
But I didn't like what I got:
The bars are not green, and it's kind of complicated to read the
histogram. I could not even figure out if the x axis is the number of
points and y axis the rgb color or the inverse... :S I would like to know
if somebody knows how could I turn this histogram more readable.
Thanks in advance.
I would like to present a histogram from an image in Python. Doing some
research, I found a way of doing it using matplotlib. So, I just do this:
im = plt.array(Image.open('Mean.png').convert('L'))
plt.figure()
plt.hist(im, facecolor='green', alpha=0.75)
plt.savefig("Histogram.png")
But I didn't like what I got:
The bars are not green, and it's kind of complicated to read the
histogram. I could not even figure out if the x axis is the number of
points and y axis the rgb color or the inverse... :S I would like to know
if somebody knows how could I turn this histogram more readable.
Thanks in advance.
Can't get a pause function to work with my javascript stopwatch
Can't get a pause function to work with my javascript stopwatch
Can some one help me. I can't seem to get this stopwatch to pause and
displayed the paused(stopped) time, and then reactivate when I hit start
again.
I don't know how to stop the timer from counting up. Not sure if it's best
practice to end the timer function, create a new function for current
time, or to keep subtracting 1 from it using the setInterval?
<script type="text/javascript">
var digit=-1.0;
var min=0;
var time;
function timer(){
digit++;
if(digit>59){
min++;
document.getElementById("mins").innerHTML=padTimer(min);
digit=0;
}
document.getElementById("secs").innerHTML=padTimer(digit);
}
function padTimer(x) {
if (x<=9) { x = ("0"+x); }
return x;
}
function start(){
time=setInterval(timer, 1000);
timer();
}
function pause() {
}
function reset(){
digit=-1.0;
timerPay=0;
}
</script>
<a href="#" onclick="start()">Click here to start the timer</a>
<a href="#" onclick="pause()">Click here to pause the timer</a>
<a href="#" onclick="reset()">Click here to reset the timer</a>
<div>
<span id="mins" >00</span>:<span id="secs">00</span><br>
</div>
Can some one help me. I can't seem to get this stopwatch to pause and
displayed the paused(stopped) time, and then reactivate when I hit start
again.
I don't know how to stop the timer from counting up. Not sure if it's best
practice to end the timer function, create a new function for current
time, or to keep subtracting 1 from it using the setInterval?
<script type="text/javascript">
var digit=-1.0;
var min=0;
var time;
function timer(){
digit++;
if(digit>59){
min++;
document.getElementById("mins").innerHTML=padTimer(min);
digit=0;
}
document.getElementById("secs").innerHTML=padTimer(digit);
}
function padTimer(x) {
if (x<=9) { x = ("0"+x); }
return x;
}
function start(){
time=setInterval(timer, 1000);
timer();
}
function pause() {
}
function reset(){
digit=-1.0;
timerPay=0;
}
</script>
<a href="#" onclick="start()">Click here to start the timer</a>
<a href="#" onclick="pause()">Click here to pause the timer</a>
<a href="#" onclick="reset()">Click here to reset the timer</a>
<div>
<span id="mins" >00</span>:<span id="secs">00</span><br>
</div>
Changing the draggable attribute
Changing the draggable attribute
I am making an maths puzzle page for kids. The answers are in s which drag
over the questions. When an answer is used, I would like to disable the
dragging of the specific answer. I can "dim" the answer and prevent it
from being dropped but thus far have found no way of preventing the from
being dragged.
Please help.... I would prefer not to use JQuery if possible
function handledrop(elt, evt) {
//Dim THE DRAGGED ITEM
dragitem.style.opacity=0.4; //***********This works
dragitem.style.hidden="true";//***********This doesn't or any
variation I an think of
//***********dragitem.draggable="false"
//***********dragitem.style.draggable="false"
//***********dragitem.draggable="false"
dragitem.ondrag = "donothing()";
dragitem.ondragstart="donothing()" ;
}
I am making an maths puzzle page for kids. The answers are in s which drag
over the questions. When an answer is used, I would like to disable the
dragging of the specific answer. I can "dim" the answer and prevent it
from being dropped but thus far have found no way of preventing the from
being dragged.
Please help.... I would prefer not to use JQuery if possible
function handledrop(elt, evt) {
//Dim THE DRAGGED ITEM
dragitem.style.opacity=0.4; //***********This works
dragitem.style.hidden="true";//***********This doesn't or any
variation I an think of
//***********dragitem.draggable="false"
//***********dragitem.style.draggable="false"
//***********dragitem.draggable="false"
dragitem.ondrag = "donothing()";
dragitem.ondragstart="donothing()" ;
}
Installing OpenCV 2.4.6.0 in Dev C++
Installing OpenCV 2.4.6.0 in Dev C++
I have tried other suggestion but they aren't working the latest version
of openCV has changed a lot. How to do that?
Just tel me 1. What to add on the linker commands? 2. Binary directories.
3. Library directories. 4. C and C++ directories.
And if I have do anything different on the rest of the part please tell
that also.
I have tried other suggestion but they aren't working the latest version
of openCV has changed a lot. How to do that?
Just tel me 1. What to add on the linker commands? 2. Binary directories.
3. Library directories. 4. C and C++ directories.
And if I have do anything different on the rest of the part please tell
that also.
error c0000:syntax error in vs
error c0000:syntax error in vs
***I Have syntax error in my shader class: " error c0000:syntax error "***
this is my read function and i think my program can not read my file:
char* Shader::read(char* filename) {
string line;
std::ifstream file;
file.open(filename);
file.open("FragmentShader.frag");
file.open("vertexShader.frag");
if (file.is_open())
{
while ( getline (file,line) )
{
cout << line << endl;
}
file.close();
}
else cout << "Unable to open file";
return 0;
}
And this my initializ vertex shader and fragment shader:
void Shader::init()
{
createVertexShader();
createFragmentShader();
mp = glCreateProgram ();
glAttachShader (mp, fs);
glAttachShader (mp, vs);
glLinkProgram (mp);
//validateProgram(mp);
}
and this are create vertex shader and fragment shader and compile them:
void Shader::createVertexShader()
{
vs = glCreateShader (GL_VERTEX_SHADER);
const char* vertexSource = read("vertexShader.vert");
if(!vertexSource)
{
std::cout << "errrrroooorrrr"<< std::endl;
return; // age intori she nabaiad baghieie code ejra beshe vagarna
hamin
}
glShaderSource (vs, 1, &vertexSource, NULL);
glCompileShader (vs);
}
/////////////////////////////////////////////////////////////////////
void Shader::createFragmentShader()
{
fs = glCreateShader (GL_FRAGMENT_SHADER);
const char* FragmentSource = read("FragmentShader.frag");
if(!FragmentSource)
{
std::cout << "errrrroooorrrr"<< std::endl;
return;
}
glShaderSource (fs, 1, &FragmentSource, NULL);
glCompileShader (fs);
}
but after run the program I have syntax error and program can not read my
text file
I need help to solve it,help me.der.h"
***I Have syntax error in my shader class: " error c0000:syntax error "***
this is my read function and i think my program can not read my file:
char* Shader::read(char* filename) {
string line;
std::ifstream file;
file.open(filename);
file.open("FragmentShader.frag");
file.open("vertexShader.frag");
if (file.is_open())
{
while ( getline (file,line) )
{
cout << line << endl;
}
file.close();
}
else cout << "Unable to open file";
return 0;
}
And this my initializ vertex shader and fragment shader:
void Shader::init()
{
createVertexShader();
createFragmentShader();
mp = glCreateProgram ();
glAttachShader (mp, fs);
glAttachShader (mp, vs);
glLinkProgram (mp);
//validateProgram(mp);
}
and this are create vertex shader and fragment shader and compile them:
void Shader::createVertexShader()
{
vs = glCreateShader (GL_VERTEX_SHADER);
const char* vertexSource = read("vertexShader.vert");
if(!vertexSource)
{
std::cout << "errrrroooorrrr"<< std::endl;
return; // age intori she nabaiad baghieie code ejra beshe vagarna
hamin
}
glShaderSource (vs, 1, &vertexSource, NULL);
glCompileShader (vs);
}
/////////////////////////////////////////////////////////////////////
void Shader::createFragmentShader()
{
fs = glCreateShader (GL_FRAGMENT_SHADER);
const char* FragmentSource = read("FragmentShader.frag");
if(!FragmentSource)
{
std::cout << "errrrroooorrrr"<< std::endl;
return;
}
glShaderSource (fs, 1, &FragmentSource, NULL);
glCompileShader (fs);
}
but after run the program I have syntax error and program can not read my
text file
I need help to solve it,help me.der.h"
Saturday, 14 September 2013
How to use HTML forms in play framework
How to use HTML forms in play framework
I am using playframework for displaying a form. I created this form with
the help of another external tool but it displays the html source slightly
diffeently. I observed that in the source I downloaded it contains the
main html and also a css and js folder. If I simply copy and paste the
html only , the form doesnt render correctly. How do I render the form
correctly? Is there any gui tool for creating forms for playframework.
Also once the form is created how do I get all the data entered from it
using the playframework? I am not using the template system and hence the
question.
I am using playframework for displaying a form. I created this form with
the help of another external tool but it displays the html source slightly
diffeently. I observed that in the source I downloaded it contains the
main html and also a css and js folder. If I simply copy and paste the
html only , the form doesnt render correctly. How do I render the form
correctly? Is there any gui tool for creating forms for playframework.
Also once the form is created how do I get all the data entered from it
using the playframework? I am not using the template system and hence the
question.
start a c++(exe) with input from a c++ gui
start a c++(exe) with input from a c++ gui
i just started learning how to program gui in c++ just using dev c++, so
nothing that fancy. with this code:
HWND hWndEdit = CreateWindowEx(
WS_EX_CLIENTEDGE,
TEXT("Edit"),
TEXT("input"),
WS_CHILD | WS_VISIBLE,
100, 20, 140, 20,
hWnd, NULL, NULL, NULL);
i create a text box for input. what i want to do is, get the input somehow
from that text box, and from that start another c++ program with the
command as the input, similar to what would be done on the command line.
if this is not possible, how would i go about getting the text from the
edit field and using it in code? and for other people like me who want to
learn gui from scratch without any kind of builders(like visual studio),
what would you suggest as a proper guide book? or even web tutorials.
i just started learning how to program gui in c++ just using dev c++, so
nothing that fancy. with this code:
HWND hWndEdit = CreateWindowEx(
WS_EX_CLIENTEDGE,
TEXT("Edit"),
TEXT("input"),
WS_CHILD | WS_VISIBLE,
100, 20, 140, 20,
hWnd, NULL, NULL, NULL);
i create a text box for input. what i want to do is, get the input somehow
from that text box, and from that start another c++ program with the
command as the input, similar to what would be done on the command line.
if this is not possible, how would i go about getting the text from the
edit field and using it in code? and for other people like me who want to
learn gui from scratch without any kind of builders(like visual studio),
what would you suggest as a proper guide book? or even web tutorials.
How do I use one row to pull multiple other rows from the same mySQL table
How do I use one row to pull multiple other rows from the same mySQL table
So, lets say i have a user table. Each user has the ability to be in a
team with upto 3 other users. So for now i have a column for each spot in
the team(4 columns total, so your own id fills in a spot so you know where
you fit in the team). And i put the ids to the other members of the team
in each of the other columns. In the end, everyone on one team would have
the same values in those 4 columns.
How would i query sql to look at those ids and pull the info for all the
other users on there team (so by looking at one user, i can pull all 4
team members rows)? Is this the most efficient way of storing that data?
So, lets say i have a user table. Each user has the ability to be in a
team with upto 3 other users. So for now i have a column for each spot in
the team(4 columns total, so your own id fills in a spot so you know where
you fit in the team). And i put the ids to the other members of the team
in each of the other columns. In the end, everyone on one team would have
the same values in those 4 columns.
How would i query sql to look at those ids and pull the info for all the
other users on there team (so by looking at one user, i can pull all 4
team members rows)? Is this the most efficient way of storing that data?
BM_SETIMAGE set left while text centred
BM_SETIMAGE set left while text centred
On a windows button is it at all possible to have the text centered while
the icon is set left? I'm using BS_PUSHBUTTON as the button and also
having set the icon and being able to replace it I'm wondering how I
remove the icon as I see no message to send for that?
On a windows button is it at all possible to have the text centered while
the icon is set left? I'm using BS_PUSHBUTTON as the button and also
having set the icon and being able to replace it I'm wondering how I
remove the icon as I see no message to send for that?
Deep URL redirection in Apache
Deep URL redirection in Apache
Can someone help me?
I am trying to do URL redirection like this using Apache on centos:
vvv.example1.com/page.jsp
to display the content of the page
vvv.example.com/page.jsp
and all of the links in the page http://www.example1.com/page.jsp
like:
http://vvv.example.com/somepage.jsp>
to be rewritten or redirected to
http://vvv.example1.com/somepage.jsp>.
Can someone tell me step by step all the things I need to do, what to
change, because I'm a begginer in Apache configuration.
Thanks
Can someone help me?
I am trying to do URL redirection like this using Apache on centos:
vvv.example1.com/page.jsp
to display the content of the page
vvv.example.com/page.jsp
and all of the links in the page http://www.example1.com/page.jsp
like:
http://vvv.example.com/somepage.jsp>
to be rewritten or redirected to
http://vvv.example1.com/somepage.jsp>.
Can someone tell me step by step all the things I need to do, what to
change, because I'm a begginer in Apache configuration.
Thanks
vb.net how to access embedding form?
vb.net how to access embedding form?
Im writting a dll which inherits a listbox and want to access the form of
the project which is using my library.
So Let's say you have a project 'bla' and a form 'form1' which uses my
lib. Is there any way to acces 'form1'?
I need this, because I want to add more controls to 'form1' than just my
modified listbox.
So I'm looking for something like:
EmmbeddingForm.Controls.Add(ButtonBla)
Thanks for any help!
Im writting a dll which inherits a listbox and want to access the form of
the project which is using my library.
So Let's say you have a project 'bla' and a form 'form1' which uses my
lib. Is there any way to acces 'form1'?
I need this, because I want to add more controls to 'form1' than just my
modified listbox.
So I'm looking for something like:
EmmbeddingForm.Controls.Add(ButtonBla)
Thanks for any help!
Strange Error occuring when using ajax and sql
Strange Error occuring when using ajax and sql
I got a problem and could use a little bit of advice,
I have a ajax script to show data from a sql database. however when i
switch between the entries really quickly it automatically logs me out.
and i have to re log back in. any clues how to keep this from happening?
I got a problem and could use a little bit of advice,
I have a ajax script to show data from a sql database. however when i
switch between the entries really quickly it automatically logs me out.
and i have to re log back in. any clues how to keep this from happening?
Friday, 13 September 2013
Connection to other side was lost in a non-clean fashion
Connection to other side was lost in a non-clean fashion
from scrapy.spider import BaseSpider
class dmozSpider(BaseSpider): name = "dmoz" allowed_domains = ["dmoz.org"]
start_urls = [
"http://www.dmoz.org/Computers/Programming/Languages/Python/Books/",
"http://www.dmoz.org/Computers/Programming/Languages/Python/Resources/" ]
def parse(self, response):
filename = response.url.split("/")[-2]
open(filename, 'wb').write(response.body)
then I run "scrapy crawl dmoz" then I got this error:
2013-09-14 13:20:56+0700 [dmoz] DEBUG: Retrying
http://www.dmoz.org/Computers/Programming/Languages/Python/Resources/>
(failed 1 times): Connection to other side was lost in a non-clean
fashion.
Does anyone know how to fix this?
from scrapy.spider import BaseSpider
class dmozSpider(BaseSpider): name = "dmoz" allowed_domains = ["dmoz.org"]
start_urls = [
"http://www.dmoz.org/Computers/Programming/Languages/Python/Books/",
"http://www.dmoz.org/Computers/Programming/Languages/Python/Resources/" ]
def parse(self, response):
filename = response.url.split("/")[-2]
open(filename, 'wb').write(response.body)
then I run "scrapy crawl dmoz" then I got this error:
2013-09-14 13:20:56+0700 [dmoz] DEBUG: Retrying
http://www.dmoz.org/Computers/Programming/Languages/Python/Resources/>
(failed 1 times): Connection to other side was lost in a non-clean
fashion.
Does anyone know how to fix this?
time in and time out checking
time in and time out checking
I am developing an attendance system of students using biometric
technology. And I am having problems with the students' time in and out of
the class.
These are my attributes for my Attendance Table
Attendance_ID - PK, Autoincrement.
Class_ID - ID of the class they are enrolled in.
Time_In - Time they went in.
Time_Out - Time they went out.
ID_Number - Student's ID Number
Date_Today - Date Today
Remarks - Absent, cutting class, present, late.
Is my table correct? Or does it need some modification?
I am developing an attendance system of students using biometric
technology. And I am having problems with the students' time in and out of
the class.
These are my attributes for my Attendance Table
Attendance_ID - PK, Autoincrement.
Class_ID - ID of the class they are enrolled in.
Time_In - Time they went in.
Time_Out - Time they went out.
ID_Number - Student's ID Number
Date_Today - Date Today
Remarks - Absent, cutting class, present, late.
Is my table correct? Or does it need some modification?
Excel: Keeping duplicates in data validation list in Excel
Excel: Keeping duplicates in data validation list in Excel
I am working on a tracker for a game in Excel. One of the functions I am
using is a drop-down list with a series of numbers, some repeated, for
character stats. I found some help to remove objects from a drop-down
after they've already been chosen; in this instance, I only need one of
them removed if there are multiples. Here's what I'm working with:
Column A has numbers 4, 3, 3, 2, 2, 2, 1, 1, 1, 1 which are the master
list contents.
Column B has a formula to generate a number to tell whether or not that
number has been used in that range. That formula is
=IF(COUNTIF('Character Tracker v1.0'!$B$25:$B$50,A12)>=1,"",ROW())
Column C has a formula to remove used entries from the list. Column C
itself is the list source. That formula is:
=IF(ROW(A7)-ROW(A$7)+1>COUNT(B$7:B$16),"",
INDEX(A:A,SMALL(B$7:B$16,1+ROW(A7)-ROW(A$7))))
For example: if I choose a 3 from the drop down, both instances of 3
disappear, and I only need one instance of 3 to be removed when chosen
(and if I choose another 3, that one disappears). I'm pretty sure it's the
formula in column B that I need to alter (as it generates a number which
is read by Column C to determine whether that entry is used or not), but
I'm not sure what to change.
Any hel pwould be appreciated.
I am working on a tracker for a game in Excel. One of the functions I am
using is a drop-down list with a series of numbers, some repeated, for
character stats. I found some help to remove objects from a drop-down
after they've already been chosen; in this instance, I only need one of
them removed if there are multiples. Here's what I'm working with:
Column A has numbers 4, 3, 3, 2, 2, 2, 1, 1, 1, 1 which are the master
list contents.
Column B has a formula to generate a number to tell whether or not that
number has been used in that range. That formula is
=IF(COUNTIF('Character Tracker v1.0'!$B$25:$B$50,A12)>=1,"",ROW())
Column C has a formula to remove used entries from the list. Column C
itself is the list source. That formula is:
=IF(ROW(A7)-ROW(A$7)+1>COUNT(B$7:B$16),"",
INDEX(A:A,SMALL(B$7:B$16,1+ROW(A7)-ROW(A$7))))
For example: if I choose a 3 from the drop down, both instances of 3
disappear, and I only need one instance of 3 to be removed when chosen
(and if I choose another 3, that one disappears). I'm pretty sure it's the
formula in column B that I need to alter (as it generates a number which
is read by Column C to determine whether that entry is used or not), but
I'm not sure what to change.
Any hel pwould be appreciated.
Pixel appearing when using css ul li display-inline block
Pixel appearing when using css ul li display-inline block
The image is pretty self explanatory. I can't get rid of those two pixels
at the bottom of only one list element. I've inserted text-decoration:none
and list-style-type none in every corner of the css with no results.
Reason?
http://s1089.photobucket.com/user/3Joez/media/disp_zps6fe2774c.jpg.html
#rightnav {
float:right;
width:65%;
height:50px;
/*border:2px solid #Df1;*/
}
#rightnav ul {
margin-left:9.5%;
/*border:1px solid #F30;*/
width:500px;
}
#rightnav ul li {
display:inline-block;
font-family:Times New Roman, Times, serif;
font-size:1.4em;
margin-left:2%;
margin-top:1.5%;
color:#FFF;
text-decoration:none ;
list-style:none;
list-style-type:none;
}
The image is pretty self explanatory. I can't get rid of those two pixels
at the bottom of only one list element. I've inserted text-decoration:none
and list-style-type none in every corner of the css with no results.
Reason?
http://s1089.photobucket.com/user/3Joez/media/disp_zps6fe2774c.jpg.html
#rightnav {
float:right;
width:65%;
height:50px;
/*border:2px solid #Df1;*/
}
#rightnav ul {
margin-left:9.5%;
/*border:1px solid #F30;*/
width:500px;
}
#rightnav ul li {
display:inline-block;
font-family:Times New Roman, Times, serif;
font-size:1.4em;
margin-left:2%;
margin-top:1.5%;
color:#FFF;
text-decoration:none ;
list-style:none;
list-style-type:none;
}
How to use rails sass on the development enviroment?
How to use rails sass on the development enviroment?
I have new rails 4.0 application with the default settings.
config.assets.debug = false
How can I use the sass with it ?
I have new rails 4.0 application with the default settings.
config.assets.debug = false
How can I use the sass with it ?
Can't add UIBarButtonItem to toolbar
Can't add UIBarButtonItem to toolbar
After going through every single stackoverflow solution for this problem,
it's still frustratingly not working for me.
//UIBarButtonItem declaration
UIBarButtonItem* button1 = [[UIBarButtonItem alloc] initWithTitle:@"Button
Text"
style:UIBarButtonItemStyleBordered target:self action:@selector(myAction)];
//method 1
[self setToolbarItems:[NSArray arrayWithObjects: button1, nil] animated:YES];
//method 2
[self.navigationController.toolbar setItems:[NSArray
arrayWithObject:button1]];
//method 3
self.navigationController.toolbarItems = [NSArray arrayWithObject:button1];
//displaying toolbar
[self.navigationController setToolbarHidden:NO];
None of the above methods work for displaying a button on the toolbar -
all I get is a blank toolbar. Is there something obvious I'm missing here?
After going through every single stackoverflow solution for this problem,
it's still frustratingly not working for me.
//UIBarButtonItem declaration
UIBarButtonItem* button1 = [[UIBarButtonItem alloc] initWithTitle:@"Button
Text"
style:UIBarButtonItemStyleBordered target:self action:@selector(myAction)];
//method 1
[self setToolbarItems:[NSArray arrayWithObjects: button1, nil] animated:YES];
//method 2
[self.navigationController.toolbar setItems:[NSArray
arrayWithObject:button1]];
//method 3
self.navigationController.toolbarItems = [NSArray arrayWithObject:button1];
//displaying toolbar
[self.navigationController setToolbarHidden:NO];
None of the above methods work for displaying a button on the toolbar -
all I get is a blank toolbar. Is there something obvious I'm missing here?
Thursday, 12 September 2013
suggestion on workflow and tools to work with node.js
suggestion on workflow and tools to work with node.js
I'm developing some really simple node.js libraries for learning purposes.
It's about functions like HexToBase64 and things like that.
Ideally, I'd like to program in a text editor, and play with it on the
node repl, having the code automatically reloaded on the repl on every
save.
Any module or tool to interactively play with node?
I'm developing some really simple node.js libraries for learning purposes.
It's about functions like HexToBase64 and things like that.
Ideally, I'd like to program in a text editor, and play with it on the
node repl, having the code automatically reloaded on the repl on every
save.
Any module or tool to interactively play with node?
How to filter using a dropdown in a gridview and display all values when none is selected
How to filter using a dropdown in a gridview and display all values when
none is selected
I have a web page with 3 values (1 text box, and 2 drop-downs) and
displays result in a gridview. This is working great when the value that I
want to search is in the drop-down. However, if the user didn't select one
of the dropdownlist ( facilityCode), we would like to display all facility
codes versus only one. What is the easiest way to accomplish this? Below
is the code related to the sqldatasource:
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$
ConnectionStrings:HCSCRMConnectionString %>"
SelectCommand="SELECT MMM_Id_Nbr, Item_Desc, Supplier_Nbr,
Supplier_Name, Stocking_Facility_Code, Reorder_Point_Qty,
BodID, Active_Ind FROM BOD_ROP_TBL WHERE (MMM_Id_Nbr =
@MMM_Id_Nbr)and active_Ind=@Active_Ind and
Stocking_Facility_Code=@FacilityCode"
UpdateCommand="UPDATE BOD_ROP_TBL SET Reorder_Point_Qty =
@Reorder_Point_Qty, Active_Ind = @Active_Ind WHERE (BodID
= @BodID)">
<SelectParameters>
<asp:FormParameter FormField="txt3MID"
Name="MMM_Id_Nbr" Type="String" />
<asp:FormParameter FormField="dropActive"
Name="Active_Ind" Type="String" />
<asp:FormParameter FormField="FacilityCode"
Name="FacilityCode" Type="String" />
</SelectParameters>
none is selected
I have a web page with 3 values (1 text box, and 2 drop-downs) and
displays result in a gridview. This is working great when the value that I
want to search is in the drop-down. However, if the user didn't select one
of the dropdownlist ( facilityCode), we would like to display all facility
codes versus only one. What is the easiest way to accomplish this? Below
is the code related to the sqldatasource:
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$
ConnectionStrings:HCSCRMConnectionString %>"
SelectCommand="SELECT MMM_Id_Nbr, Item_Desc, Supplier_Nbr,
Supplier_Name, Stocking_Facility_Code, Reorder_Point_Qty,
BodID, Active_Ind FROM BOD_ROP_TBL WHERE (MMM_Id_Nbr =
@MMM_Id_Nbr)and active_Ind=@Active_Ind and
Stocking_Facility_Code=@FacilityCode"
UpdateCommand="UPDATE BOD_ROP_TBL SET Reorder_Point_Qty =
@Reorder_Point_Qty, Active_Ind = @Active_Ind WHERE (BodID
= @BodID)">
<SelectParameters>
<asp:FormParameter FormField="txt3MID"
Name="MMM_Id_Nbr" Type="String" />
<asp:FormParameter FormField="dropActive"
Name="Active_Ind" Type="String" />
<asp:FormParameter FormField="FacilityCode"
Name="FacilityCode" Type="String" />
</SelectParameters>
Slick for Scala compiler version 2.9.1
Slick for Scala compiler version 2.9.1
I am trying to install slick in to my build.sbt this way:
name := "project"
version := "1.0"
scalaVersion := "2.9.1"
libraryDependencies += "com.typesafe.slick" %% "slick" % "1.0.1"
and I am getting a an error when I am running my sbt
> run
[info] Updating {file:/home/chris/project/}project...
[info] Resolving com.typesafe.slick#slick_2.9.1;1.0.1 ...
[warn] module not found: com.typesafe.slick#slick_2.9.1;1.0.1
[warn] ==== local: tried
[warn]
/home/chris/.ivy2/local/com.typesafe.slick/slick_2.9.1/1.0.1/ivys/ivy.xml
[warn] ==== public: tried
[warn]
http://repo1.maven.org/maven2/com/typesafe/slick/slick_2.9.1/1.0.1/slick_2.9.1-1.0.1.pom
[info] Resolving org.fusesource.jansi#jansi;1.4 ...
[warn] ::::::::::::::::::::::::::::::::::::::::::::::
[warn] :: UNRESOLVED DEPENDENCIES ::
[warn] ::::::::::::::::::::::::::::::::::::::::::::::
[warn] :: com.typesafe.slick#slick_2.9.1;1.0.1: not found
[warn] ::::::::::::::::::::::::::::::::::::::::::::::
[trace] Stack trace suppressed: run last *:update for the full output.
[error] (*:update) sbt.ResolveException: unresolved dependency:
com.typesafe.slick#slick_2.9.1;1.0.1: not found
[error] Total time: 9 s, completed Sep 12, 2013 5:09:25 PM
The url in the error is not available, my question is where can I get the
code for this specific version if I cannot get it from that public url,
and once I have the code where do I install it to?
I am trying to install slick in to my build.sbt this way:
name := "project"
version := "1.0"
scalaVersion := "2.9.1"
libraryDependencies += "com.typesafe.slick" %% "slick" % "1.0.1"
and I am getting a an error when I am running my sbt
> run
[info] Updating {file:/home/chris/project/}project...
[info] Resolving com.typesafe.slick#slick_2.9.1;1.0.1 ...
[warn] module not found: com.typesafe.slick#slick_2.9.1;1.0.1
[warn] ==== local: tried
[warn]
/home/chris/.ivy2/local/com.typesafe.slick/slick_2.9.1/1.0.1/ivys/ivy.xml
[warn] ==== public: tried
[warn]
http://repo1.maven.org/maven2/com/typesafe/slick/slick_2.9.1/1.0.1/slick_2.9.1-1.0.1.pom
[info] Resolving org.fusesource.jansi#jansi;1.4 ...
[warn] ::::::::::::::::::::::::::::::::::::::::::::::
[warn] :: UNRESOLVED DEPENDENCIES ::
[warn] ::::::::::::::::::::::::::::::::::::::::::::::
[warn] :: com.typesafe.slick#slick_2.9.1;1.0.1: not found
[warn] ::::::::::::::::::::::::::::::::::::::::::::::
[trace] Stack trace suppressed: run last *:update for the full output.
[error] (*:update) sbt.ResolveException: unresolved dependency:
com.typesafe.slick#slick_2.9.1;1.0.1: not found
[error] Total time: 9 s, completed Sep 12, 2013 5:09:25 PM
The url in the error is not available, my question is where can I get the
code for this specific version if I cannot get it from that public url,
and once I have the code where do I install it to?
Getting Undefined Index using While statement in PHP
Getting Undefined Index using While statement in PHP
I have the following code
$sqlSubscription = "SELECT `user_id` FROM subscriptions WHERE `user_id` =
'".$user_id."' and `course_id` = 'calculus_1'";
$subscriptionResult = mysql_query($sqlSubscription);
if($subscriptionResult === FALSE) {
die(mysql_error()); // temp error handling
}
while ($rows = mysql_fetch_assoc($subscriptionResult))
{
$user_id = $rows['user_id'];
$course_id = $rows['course_id'];
if($user_id==1 && $course_id="calculus_1")
{
//do some work
}
}
I'm getting the error Notice: Undefined index: course_id The line that
causes the error is in the while statement $course_id =
$rows['course_id']; The strange part is that I can select from where both
user and course ids match, and there aren't any errors doing something
simple like an echo, but when I add this while statement to verify that
both the user and course_ids match a certain rule before outputting data I
get this error.
Here is an export of the PHP Arrays through phpMyAdmin
<?php
/**
* Export to PHP Array plugin for PHPMyAdmin
* @version 0.2b
*/
//
// Database `test`
//
// `escholars`.`subscriptions`
$subscriptions = array(
array('user_id' => 'test','course_id' => 'calculus_1','start_date' =>
'2013-09-12','end_date' => '2013-09-28')
);
Any ideas?
Thanks
I have the following code
$sqlSubscription = "SELECT `user_id` FROM subscriptions WHERE `user_id` =
'".$user_id."' and `course_id` = 'calculus_1'";
$subscriptionResult = mysql_query($sqlSubscription);
if($subscriptionResult === FALSE) {
die(mysql_error()); // temp error handling
}
while ($rows = mysql_fetch_assoc($subscriptionResult))
{
$user_id = $rows['user_id'];
$course_id = $rows['course_id'];
if($user_id==1 && $course_id="calculus_1")
{
//do some work
}
}
I'm getting the error Notice: Undefined index: course_id The line that
causes the error is in the while statement $course_id =
$rows['course_id']; The strange part is that I can select from where both
user and course ids match, and there aren't any errors doing something
simple like an echo, but when I add this while statement to verify that
both the user and course_ids match a certain rule before outputting data I
get this error.
Here is an export of the PHP Arrays through phpMyAdmin
<?php
/**
* Export to PHP Array plugin for PHPMyAdmin
* @version 0.2b
*/
//
// Database `test`
//
// `escholars`.`subscriptions`
$subscriptions = array(
array('user_id' => 'test','course_id' => 'calculus_1','start_date' =>
'2013-09-12','end_date' => '2013-09-28')
);
Any ideas?
Thanks
Converting a string rappresentation of a file (byte array) back to a file in C#
Converting a string rappresentation of a file (byte array) back to a file
in C#
As in the title I'm trying to convert back a string rappresentation of a
bytearray to the original file where the bytes where taken.
What I've done:
I've a web service that gets a whole file and sends it:
answer.FileByte = File.ReadAllBytes(@"C:\QRY.txt");
After the serialization in the transmitted result xml I've this line:
<a:FileByte>TVNIfGF8MjAxMzAxMDF8YQ1QSUR8YXxhfGF8YXxhfGF8YXwyMDEzMDEwMXxhfGF8YXxhfGF8YXxhfGF8YXxhfGF8YXxhDVBWMXxhfGF8YXxhfGF8YXxhfGF8YXxhfDIwMTMwMTAxfDIwMTMwMTAxfDB8MHxhDQo=</a:FileByte>
I've tried to convert it back with this line in another simple application:
//filepath is the path of the file created
//bytearray is the string from the xml (copypasted)
File.WriteAllBytes(filepath, Encoding.UTF8.GetBytes(bytearray));
I've used UTF8 as enconding since the xml declares to use this charset.
Keeping the datatype is not an option since I'm writing a simple utility
to check the file conversion.
Maybe I'm missing something very basic but I'm not able to come up with a
working solution.
in C#
As in the title I'm trying to convert back a string rappresentation of a
bytearray to the original file where the bytes where taken.
What I've done:
I've a web service that gets a whole file and sends it:
answer.FileByte = File.ReadAllBytes(@"C:\QRY.txt");
After the serialization in the transmitted result xml I've this line:
<a:FileByte>TVNIfGF8MjAxMzAxMDF8YQ1QSUR8YXxhfGF8YXxhfGF8YXwyMDEzMDEwMXxhfGF8YXxhfGF8YXxhfGF8YXxhfGF8YXxhDVBWMXxhfGF8YXxhfGF8YXxhfGF8YXxhfDIwMTMwMTAxfDIwMTMwMTAxfDB8MHxhDQo=</a:FileByte>
I've tried to convert it back with this line in another simple application:
//filepath is the path of the file created
//bytearray is the string from the xml (copypasted)
File.WriteAllBytes(filepath, Encoding.UTF8.GetBytes(bytearray));
I've used UTF8 as enconding since the xml declares to use this charset.
Keeping the datatype is not an option since I'm writing a simple utility
to check the file conversion.
Maybe I'm missing something very basic but I'm not able to come up with a
working solution.
joomla hot or not extension alternative
joomla hot or not extension alternative
I have Joomla version 3.1 with Love Factory and all extensions also for
version 3+. Now I need to implement something like Hot or Not
http://extensions.joomla.org/extensions/clients-a-communities/ratings-a-reviews/19553
But it is only compatible with 2.5.
Is there any other plugin like this?
I have Joomla version 3.1 with Love Factory and all extensions also for
version 3+. Now I need to implement something like Hot or Not
http://extensions.joomla.org/extensions/clients-a-communities/ratings-a-reviews/19553
But it is only compatible with 2.5.
Is there any other plugin like this?
How to change url expression for 'Print this' document_action in Plone to be used with for collective.documentviewer?
How to change url expression for 'Print this' document_action in Plone to
be used with for collective.documentviewer?
I am using Plone unified installer 4.1.4 and wish to change the URL
Expression for the portal_actions, document_actions for 'Print this'. so
that the same can be enabled for collective.documentviewer. I got this
reference from [enter link description here][1]Print / Fullscreen / Email
icons
Using this however only the contents of the current window are printed and
not the contents of the file being displayed in the viewer. I am not good
at javascript. If anyone could please revert with the javascipt
expression, I will be grateful.
Note: I do not wish to download the file from document viewer by clicking
the 'Original Document' as is the default behaviour of the viewer, but
wish to print the contents of the file from the viewer directly.
be used with for collective.documentviewer?
I am using Plone unified installer 4.1.4 and wish to change the URL
Expression for the portal_actions, document_actions for 'Print this'. so
that the same can be enabled for collective.documentviewer. I got this
reference from [enter link description here][1]Print / Fullscreen / Email
icons
Using this however only the contents of the current window are printed and
not the contents of the file being displayed in the viewer. I am not good
at javascript. If anyone could please revert with the javascipt
expression, I will be grateful.
Note: I do not wish to download the file from document viewer by clicking
the 'Original Document' as is the default behaviour of the viewer, but
wish to print the contents of the file from the viewer directly.
Wednesday, 11 September 2013
can't get parameter value out of a trigger event
can't get parameter value out of a trigger event
I have the following code in my backbone view:
this.trigger('item-id-changed', itemId);
and here's the subscriber:
that.shopItemDetailedView = new ShopItemDetailedView({ model: shop });
that.shopItemDetailedView.on('item-id-changed',
that.onModelChange);
in a different view. The question is how do I access the itemId that i
passed during the trigger on the function onModalChanged?
I have the following code in my backbone view:
this.trigger('item-id-changed', itemId);
and here's the subscriber:
that.shopItemDetailedView = new ShopItemDetailedView({ model: shop });
that.shopItemDetailedView.on('item-id-changed',
that.onModelChange);
in a different view. The question is how do I access the itemId that i
passed during the trigger on the function onModalChanged?
d3js plot zoomed in a modal window on 'click'
d3js plot zoomed in a modal window on 'click'
I used d3js to plot data from a csv file:
draw(filename, divID) {
d3.csv(filename, function(data){
...
.on('click', function(d){
//open a modal and plot csv filename again
draw_bigger(filename); //call $("#mymodal").modal(); inside
The idea is that once the user clicks on the plot, a modal window pops out
and re-plot the data with auto-range (more zoomed-in). Because of
javascript closure, "filename" gets passed naturally to the inner
draw_bigger function.
However the same file is requested twice from the server. I wonder if
there is a better way to do this.
I used d3js to plot data from a csv file:
draw(filename, divID) {
d3.csv(filename, function(data){
...
.on('click', function(d){
//open a modal and plot csv filename again
draw_bigger(filename); //call $("#mymodal").modal(); inside
The idea is that once the user clicks on the plot, a modal window pops out
and re-plot the data with auto-range (more zoomed-in). Because of
javascript closure, "filename" gets passed naturally to the inner
draw_bigger function.
However the same file is requested twice from the server. I wonder if
there is a better way to do this.
Is there a script to determine linux user name?
Is there a script to determine linux user name?
I am looking for some code to get the linux username.. I have come across
code to get current username but what I need to get is the username that
was used when installing linux..
For example, if im logged in as root user, how can i get the initial
username that was used when installing ubuntu?
I am looking for some code to get the linux username.. I have come across
code to get current username but what I need to get is the username that
was used when installing linux..
For example, if im logged in as root user, how can i get the initial
username that was used when installing ubuntu?
Can anyone give me a complete example of JMS Asynchronous implementation in Mule
Can anyone give me a complete example of JMS Asynchronous implementation
in Mule
I've been searching a lot and yes, I saw a few implementations but i still
don't get how a client can consume those responses asynchronously, can
anyone explain me or give me an example, please?
The only thing i got in mind now is, a little flow that sends the request
using one-way exchange-pattern to specify that it will be asynchronous.
Great, then what? i mean, once it's in the queue. How me, as a client, can
get my messages after a certain amount of time?
Thanks in advance.
in Mule
I've been searching a lot and yes, I saw a few implementations but i still
don't get how a client can consume those responses asynchronously, can
anyone explain me or give me an example, please?
The only thing i got in mind now is, a little flow that sends the request
using one-way exchange-pattern to specify that it will be asynchronous.
Great, then what? i mean, once it's in the queue. How me, as a client, can
get my messages after a certain amount of time?
Thanks in advance.
What's the easiest way to select Object(s) that don't have nested objects?
What's the easiest way to select Object(s) that don't have nested objects?
Say I have Item that has_many Posts.
And I need to select Items that don't have ANY Posts.
My current solution is this:
Item.where("NOT EXISTS (SELECT 1 FROM posts p WHERE p.item_id = items.id)")
Is that the best way? Maybe should use OUTER JOIN somehow?
Say I have Item that has_many Posts.
And I need to select Items that don't have ANY Posts.
My current solution is this:
Item.where("NOT EXISTS (SELECT 1 FROM posts p WHERE p.item_id = items.id)")
Is that the best way? Maybe should use OUTER JOIN somehow?
What's wrong with the most cited binary tree depth calculation algorithm?
What's wrong with the most cited binary tree depth calculation algorithm?
There is something that eats into my brain: how can the depth of the
following tree
b
/ \
a c
be 3, after the most cited algorithm (here in Java):
int depth(Node n)
{
if(n == null)
{
return 0;
}
int lDepth = depth(n.left);
int rDepth = depth(n.right);
return 1 + ((lDepth > rDepth) ? lDepth : rDepth);
}
when the depth of a tree with only a single (root) node is 0 according to
Wikipedia and many of my other sources where the depth is defined as
length of path to the deepest node? Obviously, the length of the path to
the deepest node for a tree with only a single node is 0, while the above
algorithm will never yield anything smaller than 1.
Is the depth of a tree with a single root node 0 or is it 1? If it is 0
then the algorithm above is faulty, because it will yield 1.
I never thought such a trivial thing would turn inside out on me.
There is something that eats into my brain: how can the depth of the
following tree
b
/ \
a c
be 3, after the most cited algorithm (here in Java):
int depth(Node n)
{
if(n == null)
{
return 0;
}
int lDepth = depth(n.left);
int rDepth = depth(n.right);
return 1 + ((lDepth > rDepth) ? lDepth : rDepth);
}
when the depth of a tree with only a single (root) node is 0 according to
Wikipedia and many of my other sources where the depth is defined as
length of path to the deepest node? Obviously, the length of the path to
the deepest node for a tree with only a single node is 0, while the above
algorithm will never yield anything smaller than 1.
Is the depth of a tree with a single root node 0 or is it 1? If it is 0
then the algorithm above is faulty, because it will yield 1.
I never thought such a trivial thing would turn inside out on me.
Generated image of Html Page not showing the gradient color in the generated image?
Generated image of Html Page not showing the gradient color in the
generated image?
Hi I am working on c# web project I am creating a Image from html page
using web-browser control in c#.
But I have a problem in my html page we have some html control like div
image etc. when i am trying to create image of the html page the image is
generated successfully with all background color of div and images.
But problem is that if I once i use the gradient color as background and
create an image of the html page than in the image gradient color is not
showing while all color and images are showing perfectly.
Code which i use to generate image
public class WebsiteThumbnailImageGenerator { public static Bitmap
GetWebSiteThumbnail(string Url, int BrowserWidth, int BrowserHeight, int
ThumbnailWidth, int ThumbnailHeight) { WebsiteThumbnailImage
thumbnailGenerator = new WebsiteThumbnailImage(Url, BrowserWidth,
BrowserHeight, ThumbnailWidth, ThumbnailHeight); return
thumbnailGenerator.GenerateWebSiteThumbnailImage(); }
private class WebsiteThumbnailImage
{
public WebsiteThumbnailImage(string Url, int BrowserWidth, int
BrowserHeight, int ThumbnailWidth, int ThumbnailHeight)
{
this.m_Url = Url;
this.m_BrowserWidth = BrowserWidth;
this.m_BrowserHeight = BrowserHeight;
this.m_ThumbnailHeight = ThumbnailHeight;
this.m_ThumbnailWidth = ThumbnailWidth;
}
private string m_Url = null;
public string Url
{
get
{
return m_Url;
}
set
{
m_Url = value;
}
}
private Bitmap m_Bitmap = null;
public Bitmap ThumbnailImage
{
get
{
return m_Bitmap;
}
}
private int m_ThumbnailWidth;
public int ThumbnailWidth
{
get
{
return m_ThumbnailWidth;
}
set
{
m_ThumbnailWidth = value;
}
}
private int m_ThumbnailHeight;
public int ThumbnailHeight
{
get
{
return m_ThumbnailHeight;
}
set
{
m_ThumbnailHeight = value;
}
}
private int m_BrowserWidth;
public int BrowserWidth
{
get
{
return m_BrowserWidth;
}
set
{
m_BrowserWidth = value;
}
}
private int m_BrowserHeight;
public int BrowserHeight
{
get
{
return m_BrowserHeight;
}
set
{
m_BrowserHeight = value;
}
}
public Bitmap GenerateWebSiteThumbnailImage()
{
Thread m_thread = new Thread(new
ThreadStart(_GenerateWebSiteThumbnailImage));
m_thread.SetApartmentState(ApartmentState.STA);
m_thread.Start();
m_thread.Join();
return m_Bitmap;
}
private void _GenerateWebSiteThumbnailImage()
{
WebBrowser m_WebBrowser = new WebBrowser();
m_WebBrowser.ScrollBarsEnabled = false;
m_WebBrowser.Navigate(m_Url);
m_WebBrowser.DocumentCompleted += new
WebBrowserDocumentCompletedEventHandler(WebBrowser_DocumentCompleted);
while (m_WebBrowser.ReadyState != WebBrowserReadyState.Complete)
Application.DoEvents();
m_WebBrowser.Dispose();
}
private void WebBrowser_DocumentCompleted(object sender,
WebBrowserDocumentCompletedEventArgs e)
{
WebBrowser m_WebBrowser = (WebBrowser)sender;
m_WebBrowser.ClientSize = new Size(this.m_BrowserWidth,
this.m_BrowserHeight);
m_WebBrowser.ScrollBarsEnabled = false;
m_Bitmap = new Bitmap(m_WebBrowser.Bounds.Width,
m_WebBrowser.Bounds.Height);
m_WebBrowser.BringToFront();
m_WebBrowser.DrawToBitmap(m_Bitmap, m_WebBrowser.Bounds);
m_Bitmap = (Bitmap)m_Bitmap.GetThumbnailImage(m_ThumbnailWidth,
m_ThumbnailHeight, null, IntPtr.Zero);
}
}
generated image?
Hi I am working on c# web project I am creating a Image from html page
using web-browser control in c#.
But I have a problem in my html page we have some html control like div
image etc. when i am trying to create image of the html page the image is
generated successfully with all background color of div and images.
But problem is that if I once i use the gradient color as background and
create an image of the html page than in the image gradient color is not
showing while all color and images are showing perfectly.
Code which i use to generate image
public class WebsiteThumbnailImageGenerator { public static Bitmap
GetWebSiteThumbnail(string Url, int BrowserWidth, int BrowserHeight, int
ThumbnailWidth, int ThumbnailHeight) { WebsiteThumbnailImage
thumbnailGenerator = new WebsiteThumbnailImage(Url, BrowserWidth,
BrowserHeight, ThumbnailWidth, ThumbnailHeight); return
thumbnailGenerator.GenerateWebSiteThumbnailImage(); }
private class WebsiteThumbnailImage
{
public WebsiteThumbnailImage(string Url, int BrowserWidth, int
BrowserHeight, int ThumbnailWidth, int ThumbnailHeight)
{
this.m_Url = Url;
this.m_BrowserWidth = BrowserWidth;
this.m_BrowserHeight = BrowserHeight;
this.m_ThumbnailHeight = ThumbnailHeight;
this.m_ThumbnailWidth = ThumbnailWidth;
}
private string m_Url = null;
public string Url
{
get
{
return m_Url;
}
set
{
m_Url = value;
}
}
private Bitmap m_Bitmap = null;
public Bitmap ThumbnailImage
{
get
{
return m_Bitmap;
}
}
private int m_ThumbnailWidth;
public int ThumbnailWidth
{
get
{
return m_ThumbnailWidth;
}
set
{
m_ThumbnailWidth = value;
}
}
private int m_ThumbnailHeight;
public int ThumbnailHeight
{
get
{
return m_ThumbnailHeight;
}
set
{
m_ThumbnailHeight = value;
}
}
private int m_BrowserWidth;
public int BrowserWidth
{
get
{
return m_BrowserWidth;
}
set
{
m_BrowserWidth = value;
}
}
private int m_BrowserHeight;
public int BrowserHeight
{
get
{
return m_BrowserHeight;
}
set
{
m_BrowserHeight = value;
}
}
public Bitmap GenerateWebSiteThumbnailImage()
{
Thread m_thread = new Thread(new
ThreadStart(_GenerateWebSiteThumbnailImage));
m_thread.SetApartmentState(ApartmentState.STA);
m_thread.Start();
m_thread.Join();
return m_Bitmap;
}
private void _GenerateWebSiteThumbnailImage()
{
WebBrowser m_WebBrowser = new WebBrowser();
m_WebBrowser.ScrollBarsEnabled = false;
m_WebBrowser.Navigate(m_Url);
m_WebBrowser.DocumentCompleted += new
WebBrowserDocumentCompletedEventHandler(WebBrowser_DocumentCompleted);
while (m_WebBrowser.ReadyState != WebBrowserReadyState.Complete)
Application.DoEvents();
m_WebBrowser.Dispose();
}
private void WebBrowser_DocumentCompleted(object sender,
WebBrowserDocumentCompletedEventArgs e)
{
WebBrowser m_WebBrowser = (WebBrowser)sender;
m_WebBrowser.ClientSize = new Size(this.m_BrowserWidth,
this.m_BrowserHeight);
m_WebBrowser.ScrollBarsEnabled = false;
m_Bitmap = new Bitmap(m_WebBrowser.Bounds.Width,
m_WebBrowser.Bounds.Height);
m_WebBrowser.BringToFront();
m_WebBrowser.DrawToBitmap(m_Bitmap, m_WebBrowser.Bounds);
m_Bitmap = (Bitmap)m_Bitmap.GetThumbnailImage(m_ThumbnailWidth,
m_ThumbnailHeight, null, IntPtr.Zero);
}
}
How to share "Starling" game in a facebook feed
How to share "Starling" game in a facebook feed
I want to share a part of the game that I made on facebook like it can be
done in Angrybirds.
but the problem is that the game was written in starling and
I am getting this error "application is not correctly embeded"
and my question are
can I use starling without hardware acceleration same how?
if same know of a way to tell Facebook to embed the swf in direct mode?
Here it end Angrybirds example just past it on facebook
https://angrybirds-facebook.appspot.com/embed?levelId=9-1&levelName=Surf+and+Turf-1&score=56530
I want to share a part of the game that I made on facebook like it can be
done in Angrybirds.
but the problem is that the game was written in starling and
I am getting this error "application is not correctly embeded"
and my question are
can I use starling without hardware acceleration same how?
if same know of a way to tell Facebook to embed the swf in direct mode?
Here it end Angrybirds example just past it on facebook
https://angrybirds-facebook.appspot.com/embed?levelId=9-1&levelName=Surf+and+Turf-1&score=56530
Integrating .NET application with Forio.com
Integrating .NET application with Forio.com
I have to integrate .NET application (Console application) with FORIO.COM
for creating session and licenses. If anyone have done this before, please
help me for this. Thanks in advance.
I have to integrate .NET application (Console application) with FORIO.COM
for creating session and licenses. If anyone have done this before, please
help me for this. Thanks in advance.
Tuesday, 10 September 2013
MapController scrollBy() going off the map
MapController scrollBy() going off the map
I am using MapController.scrollyBy() to adjust the screen after I center
on an object since on some devices the centering causes a popup I have to
get cut off. The animateTo() has been working fine for a long time but
when I added scrollBy() it causes the map to jump way off to the edge of
the map. I tried adding a delay as seen below thinking that the scrollBy()
was getting called when the map was still animating but it did not seem to
fix the problem. What could be causing this odd behavoir?
protected void animateTo(int index, GeoPoint center) {
int vertOffset = R.dimen.map_balloon_center_offset;
mc.animateTo(center);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
//Do something after 100ms
}
}, 100);
mc.scrollBy(0, vertOffset);
}
I am using MapController.scrollyBy() to adjust the screen after I center
on an object since on some devices the centering causes a popup I have to
get cut off. The animateTo() has been working fine for a long time but
when I added scrollBy() it causes the map to jump way off to the edge of
the map. I tried adding a delay as seen below thinking that the scrollBy()
was getting called when the map was still animating but it did not seem to
fix the problem. What could be causing this odd behavoir?
protected void animateTo(int index, GeoPoint center) {
int vertOffset = R.dimen.map_balloon_center_offset;
mc.animateTo(center);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
//Do something after 100ms
}
}, 100);
mc.scrollBy(0, vertOffset);
}
Can't assign a selector class to a heading 1
Can't assign a selector class to a heading 1
I have a website that i am working on and have encountered a major error
that will dramatically limit the design of the website. The issue is that
i cannot set a h1.logo a and h1.logo a:hover in my CSS. I am limited to
just style tags which works but destroys my other CSS for the navigation
bar. I want the top logo that says codegrammers to have noText-Decoration
and turn white when you hover over it. I will post a jsfiddle with the
code below.
JsFiddle: http://jsfiddle.net/HeyItsProdigy/8H3aK/
I have a website that i am working on and have encountered a major error
that will dramatically limit the design of the website. The issue is that
i cannot set a h1.logo a and h1.logo a:hover in my CSS. I am limited to
just style tags which works but destroys my other CSS for the navigation
bar. I want the top logo that says codegrammers to have noText-Decoration
and turn white when you hover over it. I will post a jsfiddle with the
code below.
JsFiddle: http://jsfiddle.net/HeyItsProdigy/8H3aK/
Ordering elements with jQuery without ids
Ordering elements with jQuery without ids
I am kinda stuck with re ordering issue with jQuery. In the followng code
structre is like input>label>div but I need to put div first, then label
and input in the lastest element.
As you can see label elements does not have id 's...so I am kinda stuck
here:( Any help?
<div class="taxonomy"
id="wwx5000InstrumentsPriceandconditions.model#PriceAndConditions.classifies__InputObjectType_0_DailySmokingFrequency">
<ul class="taxonomy_radiobuttons">
<li
class="wwx5000InstrumentsPriceandconditions.model#PriceAndConditions.classifies__InputObjectType_0_DailySmokingFrequency_Notsmoking">
<input type="radio" value="//wwx/6000 Context/Daily smoking
frequency.model#NotSmoking"
name="wwx5000InstrumentsPriceandconditions.model#PriceAndConditions.classifies__InputObjectType_0_DailySmokingFrequency"
id="wwx5000InstrumentsPriceandconditions.model#PriceAndConditions.classifies__InputObjectType_0_DailySmokingFrequency_Notsmoking">
<label
for="wwx5000InstrumentsPriceandconditions.model#PriceAndConditions.classifies__InputObjectType_0_DailySmokingFrequency_Notsmoking">.Not
smoking</label>
<div class="visual"><p><img
src="/myapp/resources/dynamic/7139b8eb"></p></div>
</li>
<li
class="wwx5000InstrumentsPriceandconditions.model#PriceAndConditions.classifies__InputObjectType_0_DailySmokingFrequency_0005">
<input type="radio" value="//wwx/6000 Context/Daily smoking
frequency.model#HalfPacket"
name="wwx5000InstrumentsPriceandconditions.model#PriceAndConditions.classifies__InputObjectType_0_DailySmokingFrequency"
id="wwx5000InstrumentsPriceandconditions.model#PriceAndConditions.classifies__InputObjectType_0_DailySmokingFrequency_0005">
<label
for="wwx5000InstrumentsPriceandconditions.model#PriceAndConditions.classifies__InputObjectType_0_DailySmokingFrequency_0005">0,0-0,5</label>
<div class="visual"><p><img
src="/myapp/resources/dynamic/49b8660"></p></div>
</li>
<li
class="wwx5000InstrumentsPriceandconditions.model#PriceAndConditions.classifies__InputObjectType_0_DailySmokingFrequency_0510">
<input type="radio" value="//wwx/6000 Context/Daily smoking
frequency.model#OnePacket"
name="wwx5000Instrumentsconditions.model#Conditions.classifies__InputObjectType_0_DailySmokingFrequency"
id="wwx5000Instrumentsconditions.model#Conditions.classifies__InputObjectType_0_DailySmokingFrequency_0510">
<label
for="wwx5000Instrumentsconditions.model#Conditions.classifies__InputObjectType_0_DailySmokingFrequency_0510">0,5-1,0</label>
<div class="visual"><p><img
src="/myapp/resources/dynamic/7e930afc"></p></div>
</li>
<li
class="wwx5000Instrumentsconditions.model#Conditions.classifies__InputObjectType_0_DailySmokingFrequency_1015">
<input type="radio" value="//wwx/6000 Context/Daily smoking
frequency.model#OneAndHalfPacket"
name="wwx5000Instrumentsconditions.model#Conditions.classifies__InputObjectType_0_DailySmokingFrequency"
id="wwx5000Instrumentsconditions.model#Conditions.classifies__InputObjectType_0_DailySmokingFrequency_1015">
<label
for="wwx5000Instrumentsconditions.model#Conditions.classifies__InputObjectType_0_DailySmokingFrequency_1015">1,0-1,5</label>
<div class="visual"><p><img
src="/myapp/resources/dynamic/67b6674f"></p></div>
</li>
<li
class="wwx5000Instrumentsconditions.model#Conditions.classifies__InputObjectType_0_DailySmokingFrequency_1520">
<input type="radio" value="//wwx/6000 Context/Daily smoking
frequency.model#TwoPacket"
name="wwx5000Instrumentsconditions.model#Conditions.classifies__InputObjectType_0_DailySmokingFrequency"
id="wwx5000Instrumentsconditions.model#Conditions.classifies__InputObjectType_0_DailySmokingFrequency_1520">
<label
for="wwx5000Instrumentsconditions.model#Conditions.classifies__InputObjectType_0_DailySmokingFrequency_1520">1,5-2,0</label>
<div class="visual"><p><img
src="/myapp/resources/dynamic/7838a8ba"></p></div>
</li>
<li
class="wwx5000Instrumentsconditions.model#Conditions.classifies__InputObjectType_0_DailySmokingFrequency_20">
<input type="radio" value="//wwx/6000 Context/Daily smoking
frequency.model#MoreThanTwoPacket"
name="wwx5000Instrumentsconditions.model#Conditions.classifies__InputObjectType_0_DailySmokingFrequency"
id="wwx5000Instrumentsconditions.model#Conditions.classifies__InputObjectType_0_DailySmokingFrequency_20">
<label
for="wwx5000Instrumentsconditions.model#Conditions.classifies__InputObjectType_0_DailySmokingFrequency_20">>2,0</label>
<div class="visual"><p><img
src="/myapp/resources/dynamic/4fcd88ff"></p></div>
</li>
</ul>
I am kinda stuck with re ordering issue with jQuery. In the followng code
structre is like input>label>div but I need to put div first, then label
and input in the lastest element.
As you can see label elements does not have id 's...so I am kinda stuck
here:( Any help?
<div class="taxonomy"
id="wwx5000InstrumentsPriceandconditions.model#PriceAndConditions.classifies__InputObjectType_0_DailySmokingFrequency">
<ul class="taxonomy_radiobuttons">
<li
class="wwx5000InstrumentsPriceandconditions.model#PriceAndConditions.classifies__InputObjectType_0_DailySmokingFrequency_Notsmoking">
<input type="radio" value="//wwx/6000 Context/Daily smoking
frequency.model#NotSmoking"
name="wwx5000InstrumentsPriceandconditions.model#PriceAndConditions.classifies__InputObjectType_0_DailySmokingFrequency"
id="wwx5000InstrumentsPriceandconditions.model#PriceAndConditions.classifies__InputObjectType_0_DailySmokingFrequency_Notsmoking">
<label
for="wwx5000InstrumentsPriceandconditions.model#PriceAndConditions.classifies__InputObjectType_0_DailySmokingFrequency_Notsmoking">.Not
smoking</label>
<div class="visual"><p><img
src="/myapp/resources/dynamic/7139b8eb"></p></div>
</li>
<li
class="wwx5000InstrumentsPriceandconditions.model#PriceAndConditions.classifies__InputObjectType_0_DailySmokingFrequency_0005">
<input type="radio" value="//wwx/6000 Context/Daily smoking
frequency.model#HalfPacket"
name="wwx5000InstrumentsPriceandconditions.model#PriceAndConditions.classifies__InputObjectType_0_DailySmokingFrequency"
id="wwx5000InstrumentsPriceandconditions.model#PriceAndConditions.classifies__InputObjectType_0_DailySmokingFrequency_0005">
<label
for="wwx5000InstrumentsPriceandconditions.model#PriceAndConditions.classifies__InputObjectType_0_DailySmokingFrequency_0005">0,0-0,5</label>
<div class="visual"><p><img
src="/myapp/resources/dynamic/49b8660"></p></div>
</li>
<li
class="wwx5000InstrumentsPriceandconditions.model#PriceAndConditions.classifies__InputObjectType_0_DailySmokingFrequency_0510">
<input type="radio" value="//wwx/6000 Context/Daily smoking
frequency.model#OnePacket"
name="wwx5000Instrumentsconditions.model#Conditions.classifies__InputObjectType_0_DailySmokingFrequency"
id="wwx5000Instrumentsconditions.model#Conditions.classifies__InputObjectType_0_DailySmokingFrequency_0510">
<label
for="wwx5000Instrumentsconditions.model#Conditions.classifies__InputObjectType_0_DailySmokingFrequency_0510">0,5-1,0</label>
<div class="visual"><p><img
src="/myapp/resources/dynamic/7e930afc"></p></div>
</li>
<li
class="wwx5000Instrumentsconditions.model#Conditions.classifies__InputObjectType_0_DailySmokingFrequency_1015">
<input type="radio" value="//wwx/6000 Context/Daily smoking
frequency.model#OneAndHalfPacket"
name="wwx5000Instrumentsconditions.model#Conditions.classifies__InputObjectType_0_DailySmokingFrequency"
id="wwx5000Instrumentsconditions.model#Conditions.classifies__InputObjectType_0_DailySmokingFrequency_1015">
<label
for="wwx5000Instrumentsconditions.model#Conditions.classifies__InputObjectType_0_DailySmokingFrequency_1015">1,0-1,5</label>
<div class="visual"><p><img
src="/myapp/resources/dynamic/67b6674f"></p></div>
</li>
<li
class="wwx5000Instrumentsconditions.model#Conditions.classifies__InputObjectType_0_DailySmokingFrequency_1520">
<input type="radio" value="//wwx/6000 Context/Daily smoking
frequency.model#TwoPacket"
name="wwx5000Instrumentsconditions.model#Conditions.classifies__InputObjectType_0_DailySmokingFrequency"
id="wwx5000Instrumentsconditions.model#Conditions.classifies__InputObjectType_0_DailySmokingFrequency_1520">
<label
for="wwx5000Instrumentsconditions.model#Conditions.classifies__InputObjectType_0_DailySmokingFrequency_1520">1,5-2,0</label>
<div class="visual"><p><img
src="/myapp/resources/dynamic/7838a8ba"></p></div>
</li>
<li
class="wwx5000Instrumentsconditions.model#Conditions.classifies__InputObjectType_0_DailySmokingFrequency_20">
<input type="radio" value="//wwx/6000 Context/Daily smoking
frequency.model#MoreThanTwoPacket"
name="wwx5000Instrumentsconditions.model#Conditions.classifies__InputObjectType_0_DailySmokingFrequency"
id="wwx5000Instrumentsconditions.model#Conditions.classifies__InputObjectType_0_DailySmokingFrequency_20">
<label
for="wwx5000Instrumentsconditions.model#Conditions.classifies__InputObjectType_0_DailySmokingFrequency_20">>2,0</label>
<div class="visual"><p><img
src="/myapp/resources/dynamic/4fcd88ff"></p></div>
</li>
</ul>
SDWebImage operations not being canceled
SDWebImage operations not being canceled
I have a table view that includes several feed cells that each have a few
images a piece. I'm loading in the images like this:
[timeLineCell.avatar setImageWithURL:[NSURL URLWithString:[feedAccount
accountAvatarUrl]] placeholderImage:avatarPlaceholderImage
options:SDWebImageRetryFailed];
This works fine, but on slow connections the operations tend to just climb
instead of removing old operations for the same images. That is -- if I
scroll down and back up through the same cells, it adds the same images
into the operation queue for a second time.
I'm also attempting to remove images from the download queue when the cell
gets reused like this in cellForRow:
- (void)prepareForReuse {
[super prepareForReuse];
[self.avatar cancelCurrentImageLoad];
}
But it seems like the operation doesn't match anything in the operation
queue in SDWebImage's methods, so it doesn't actually cancel anything. If
I run cancelAll on the shared manager it works, but it's obviously not
ideal.
I'm aware I'm only showing one image on this cell, but I have commented
out everything except for this image loading and the problem persists. It
also persists if I comment out the avatar image and allow a different
image (loaded similarly) to download instead.
Anyone have any tips on this?
P.S. I've tried changing the options from SDWebImageRetryFailed to other
things including no options at all, but it made no difference.
I have a table view that includes several feed cells that each have a few
images a piece. I'm loading in the images like this:
[timeLineCell.avatar setImageWithURL:[NSURL URLWithString:[feedAccount
accountAvatarUrl]] placeholderImage:avatarPlaceholderImage
options:SDWebImageRetryFailed];
This works fine, but on slow connections the operations tend to just climb
instead of removing old operations for the same images. That is -- if I
scroll down and back up through the same cells, it adds the same images
into the operation queue for a second time.
I'm also attempting to remove images from the download queue when the cell
gets reused like this in cellForRow:
- (void)prepareForReuse {
[super prepareForReuse];
[self.avatar cancelCurrentImageLoad];
}
But it seems like the operation doesn't match anything in the operation
queue in SDWebImage's methods, so it doesn't actually cancel anything. If
I run cancelAll on the shared manager it works, but it's obviously not
ideal.
I'm aware I'm only showing one image on this cell, but I have commented
out everything except for this image loading and the problem persists. It
also persists if I comment out the avatar image and allow a different
image (loaded similarly) to download instead.
Anyone have any tips on this?
P.S. I've tried changing the options from SDWebImageRetryFailed to other
things including no options at all, but it made no difference.
Interating native iOS app with phonegap 2.7.0
Interating native iOS app with phonegap 2.7.0
Hi I'm Beginner of Phonegap language. And I have some experience for
create the native iPhone application. So, I'm trying to create an app
which uses the combination of native functionality and the phoneGap 2.7.0
framework. The phonegap app has a button, upon the click of which the
native functionality has to be added to the view. Is there any way to
achieve this? or Please provide any tutorial?
Hi I'm Beginner of Phonegap language. And I have some experience for
create the native iPhone application. So, I'm trying to create an app
which uses the combination of native functionality and the phoneGap 2.7.0
framework. The phonegap app has a button, upon the click of which the
native functionality has to be added to the view. Is there any way to
achieve this? or Please provide any tutorial?
UITableView is null after first data load, reloadData does not work
UITableView is null after first data load, reloadData does not work
I have a custom UIView with a UITableView in it. I connect the delegate
and dataSource via interface builder, it looks like this:
http://postimg.org/image/nj9elaj4h/ (may not upload images yet :( )
When I load the view, the data is displayed as it should be. But when I
try to call reloadData, nothing happens. I checked if the uitableview is
set, but it is NULL. But as soon as I drag the tableView and it reloads it
views, the new data is presented. Anyone got an idea why reloadData does
not work?
.h looks like this:
@interface NextTitleView :
UIView<UITableViewDataSource,UITableViewDelegate,SociusClientDelegate,UIActionSheetDelegate,Ne
xtTitleCustomCellDelegate>
{
NexTitleCustomCell* _cellInFocus;
}
@property(nonatomic,retain)IBOutlet UITableView* _tableViewNextTitle;
@end
thanks for your help :D
I have a custom UIView with a UITableView in it. I connect the delegate
and dataSource via interface builder, it looks like this:
http://postimg.org/image/nj9elaj4h/ (may not upload images yet :( )
When I load the view, the data is displayed as it should be. But when I
try to call reloadData, nothing happens. I checked if the uitableview is
set, but it is NULL. But as soon as I drag the tableView and it reloads it
views, the new data is presented. Anyone got an idea why reloadData does
not work?
.h looks like this:
@interface NextTitleView :
UIView<UITableViewDataSource,UITableViewDelegate,SociusClientDelegate,UIActionSheetDelegate,Ne
xtTitleCustomCellDelegate>
{
NexTitleCustomCell* _cellInFocus;
}
@property(nonatomic,retain)IBOutlet UITableView* _tableViewNextTitle;
@end
thanks for your help :D
Subscribe to:
Comments (Atom)