excel issue - calculating formulas are not happening automatically
I am using Microsoft excel 2010. Values are getting downloaded from
database and I am writing them on to excel. I have some formulas written
in excel itself. So, my formulas would be using the values downloaded from
excel and showing the value of formula in one cell. But for some reason,
the value is not showing automatically and I need to press ALT+CTRL+F9 to
see the value (calculated using formula of that cell).
Can anyone tell me is there any other way to avoid pressing ALT+CTRL+F9 ?
downloading all the values and writing in excel is happening through java,
hibernate.
Thanks in Advance,
Thursday, 3 October 2013
Wednesday, 2 October 2013
Handling unknown structs imported from dll
Handling unknown structs imported from dll
I have tried to streamline this, but if you need more detail or code, let
me know.
First, some background: I am making a module for a program using exported
functions from a .dll to communicate with it. I do not have support from
the original developer, so I do not have access to the source code,
headers, .lib, or anything else. I used dependency walker to get a list of
function names, and explicitly linked using getProcAddress with success on
most functions. (Here is the solution I used to get this far.)
Now the problem I have run into is how to handle unknown structs. For
example, I have access to the following equations:
foo::bar::bar(void)
struct foo::bar magic(void)
foo::baz::baz(struct foo::bar const &)
int foo::baz::qux(void)
So the top function is a constructor that makes an object with the same
name as the struct. The second function is a magic function that outputs
the struct with all the data in it. The third function is another
constructor that makes a new object with that struct as an input. The
final function outputs an integer value (what I really care about) with
the object just created.
As you can see, I don't know, nor do I care what is in the struct. It just
gets magically created and immediately passed to another function that
deals with it. So here is how I attempted to handle it (look at the
solution linked in the first paragraph if this doesn't make sense):
struct barStruct {
void** unknown1[1024];
void** unknown2[1024];
void** unknown3[1024];
};
typedef barStruct (*_magic) (char *);
typedef void (*_bazConstructor) (char *, struct barStruct const &);
typedef int (*_qux) (char *);
I think I figured out how many elements there are in barStruct because
bazConstructor will crash if there are too many. The problem is, no matter
what I have tried, qux will crash. I am guessing this has something to do
with how I am handling barStruct. Is it necessary to define the struct
like this? Is there a way to pass it directly from magic to the
bazconstructor without trying to say what is in it?
Basically: How should I handle a struct if I have no idea what it is
supposed to contain?
I have tried to streamline this, but if you need more detail or code, let
me know.
First, some background: I am making a module for a program using exported
functions from a .dll to communicate with it. I do not have support from
the original developer, so I do not have access to the source code,
headers, .lib, or anything else. I used dependency walker to get a list of
function names, and explicitly linked using getProcAddress with success on
most functions. (Here is the solution I used to get this far.)
Now the problem I have run into is how to handle unknown structs. For
example, I have access to the following equations:
foo::bar::bar(void)
struct foo::bar magic(void)
foo::baz::baz(struct foo::bar const &)
int foo::baz::qux(void)
So the top function is a constructor that makes an object with the same
name as the struct. The second function is a magic function that outputs
the struct with all the data in it. The third function is another
constructor that makes a new object with that struct as an input. The
final function outputs an integer value (what I really care about) with
the object just created.
As you can see, I don't know, nor do I care what is in the struct. It just
gets magically created and immediately passed to another function that
deals with it. So here is how I attempted to handle it (look at the
solution linked in the first paragraph if this doesn't make sense):
struct barStruct {
void** unknown1[1024];
void** unknown2[1024];
void** unknown3[1024];
};
typedef barStruct (*_magic) (char *);
typedef void (*_bazConstructor) (char *, struct barStruct const &);
typedef int (*_qux) (char *);
I think I figured out how many elements there are in barStruct because
bazConstructor will crash if there are too many. The problem is, no matter
what I have tried, qux will crash. I am guessing this has something to do
with how I am handling barStruct. Is it necessary to define the struct
like this? Is there a way to pass it directly from magic to the
bazconstructor without trying to say what is in it?
Basically: How should I handle a struct if I have no idea what it is
supposed to contain?
Remove a single space character from a long string of spaces
Remove a single space character from a long string of spaces
I am trying to remove a single space character from a long string of let's
say 10 spaces. Example (first row is before, second row is after, dots
used instead of single spaces for better understanding):
".........."
"........."
Just one space removal at a time.
I am trying to remove a single space character from a long string of let's
say 10 spaces. Example (first row is before, second row is after, dots
used instead of single spaces for better understanding):
".........."
"........."
Just one space removal at a time.
Rcpp First Compilation trouble
Rcpp First Compilation trouble
I recently downloaded the 2013 Rcpp book off amazon to learn how to use
C++ with my R code better and I'm trying the first compilation example
with the first fibonacci recursion function and wrapper to see if I can do
it. I'm on Ubuntu with the latest R.
First my C++:
/* Cpp based recurive function */
int fibonacci(const int x){
if(x == 0) return(0);
if(x == 1) return(1);
return(fibonacci(x - 1) + fibonacci(x - 2));
}
/* Wrapper */
extern "C" SEXP fibWrapper(SEXP xs) {
int x = Rcpp::as<int>(xs);
int fib = fibonacci(x);
return(Rcpp::wrap(fib));
}
Then I start sh and type in:
PKG_CXXFLAGS=`Rscript -e 'Rcpp:::CxxFlags()'`
PKG_LIBS=`Rscript -e 'Rcpp:::LdFlags()'`
R CMD SHLIB Fibonacci.cpp
But I get:
g++ -I/usr/share/R/include -DNDEBUG -fpic -O3 -pipe -g -c
Fibonacci.cpp -o Fibonacci.o
Fibbonacci.cpp:10:12: error: 'SEXP' does not name a type
make: *** [Fibonacci.o] Error 1
I figure maybe I need the include directive in my C++ code, so I do it
again, but this time with #include<Rcpp.h> at the top of the C++ file, and
do the same commands in sh again, but still no joy:
g++ -I/usr/share/R/include -DNDEBUG -fpic -O3 -pipe -g -c
Fibonacci.cpp -o Fibonacci.o
Fibonacci.cpp:1:18: fatal error: Rcpp.h: No such file or directory
compilation terminated.
make: *** [Fibbonacci.o] Error 1
What have I done wrong? If I query the values I've set in sh:
$PKG_CXXFLAGS
sh: 9: -I/local/yrq12edu/R/x86_64-pc-linux-gnu-library/3.0/Rcpp/include:
not found
$PKG_LIBS
sh: 10: -L/local/yrq12edu/R/x86_64-pc-linux-gnu-library/3.0/Rcpp/lib: not
found
But I think the not found messages are just because of the -L flag since
the files are there if I cd to the directory.
Thanks, Ben.
I recently downloaded the 2013 Rcpp book off amazon to learn how to use
C++ with my R code better and I'm trying the first compilation example
with the first fibonacci recursion function and wrapper to see if I can do
it. I'm on Ubuntu with the latest R.
First my C++:
/* Cpp based recurive function */
int fibonacci(const int x){
if(x == 0) return(0);
if(x == 1) return(1);
return(fibonacci(x - 1) + fibonacci(x - 2));
}
/* Wrapper */
extern "C" SEXP fibWrapper(SEXP xs) {
int x = Rcpp::as<int>(xs);
int fib = fibonacci(x);
return(Rcpp::wrap(fib));
}
Then I start sh and type in:
PKG_CXXFLAGS=`Rscript -e 'Rcpp:::CxxFlags()'`
PKG_LIBS=`Rscript -e 'Rcpp:::LdFlags()'`
R CMD SHLIB Fibonacci.cpp
But I get:
g++ -I/usr/share/R/include -DNDEBUG -fpic -O3 -pipe -g -c
Fibonacci.cpp -o Fibonacci.o
Fibbonacci.cpp:10:12: error: 'SEXP' does not name a type
make: *** [Fibonacci.o] Error 1
I figure maybe I need the include directive in my C++ code, so I do it
again, but this time with #include<Rcpp.h> at the top of the C++ file, and
do the same commands in sh again, but still no joy:
g++ -I/usr/share/R/include -DNDEBUG -fpic -O3 -pipe -g -c
Fibonacci.cpp -o Fibonacci.o
Fibonacci.cpp:1:18: fatal error: Rcpp.h: No such file or directory
compilation terminated.
make: *** [Fibbonacci.o] Error 1
What have I done wrong? If I query the values I've set in sh:
$PKG_CXXFLAGS
sh: 9: -I/local/yrq12edu/R/x86_64-pc-linux-gnu-library/3.0/Rcpp/include:
not found
$PKG_LIBS
sh: 10: -L/local/yrq12edu/R/x86_64-pc-linux-gnu-library/3.0/Rcpp/lib: not
found
But I think the not found messages are just because of the -L flag since
the files are there if I cd to the directory.
Thanks, Ben.
Why this equation returns zero even though it should not?
Why this equation returns zero even though it should not?
So, I'm doing a fighting game in java and I have this equation that always
returns zero.
int x = 90/100*300;
It should be 270 but it returns zero. :|
So, I'm doing a fighting game in java and I have this equation that always
returns zero.
int x = 90/100*300;
It should be 270 but it returns zero. :|
Tuesday, 1 October 2013
Browser will not display images - PHP
Browser will not display images - PHP
It would be great if someone could help me figure out why the browser
cannot load the images (error 404). The code works, and the image source
is correct, but I cannot figure out what is wrong. (using localhost)
<?php
$dir = '/home/user/Pictures';
$file_display = array('jpg', 'jpeg', 'png', 'gif');
if (file_exists($dir) == false) {
echo 'Directory \'', $dir, '\' not found!';
} else {
$dir_contents = scandir($dir);
foreach ($dir_contents as $file) {
$file_type = strtolower(end(explode('.', $file)));
if ($file !== '.' && $file !== '..' && in_array($file_type,
$file_display) == true)
{
echo '<img src="', $dir, '/', $file, '" alt="', $file, '" />';
}
}
}
?>
It would be great if someone could help me figure out why the browser
cannot load the images (error 404). The code works, and the image source
is correct, but I cannot figure out what is wrong. (using localhost)
<?php
$dir = '/home/user/Pictures';
$file_display = array('jpg', 'jpeg', 'png', 'gif');
if (file_exists($dir) == false) {
echo 'Directory \'', $dir, '\' not found!';
} else {
$dir_contents = scandir($dir);
foreach ($dir_contents as $file) {
$file_type = strtolower(end(explode('.', $file)));
if ($file !== '.' && $file !== '..' && in_array($file_type,
$file_display) == true)
{
echo '<img src="', $dir, '/', $file, '" alt="', $file, '" />';
}
}
}
?>
handling posted images using asp.net mvc
handling posted images using asp.net mvc
I want to save multiple images at once using asp.net mvc4. At view side I
have 5 browse button and I'm successf. getting those file at the
controller side as parameter at post action
IEnumerable<HttpPostedFileBase> postedPhotos.
I want to know if postedPhotos[0] was sent, if so save it to the db.
iterate trough remaining postedPhotos collection and take further action
only to those which actually contains photo (user can send only one or two
image instead of five)
so I tried with
if(postedPhotos.First() != null)
foreach(var photo in postedPhotos.Where(x=>x.ContentLength>0))
{....}
but this doesn't work since I'm touching postedPhoto null value and I'm
getting exception
Object reference not set to an instance of an object.
ofcourse everything works if I send all five photos but I'm interesting
how to handle this situation.
THanks
I want to save multiple images at once using asp.net mvc4. At view side I
have 5 browse button and I'm successf. getting those file at the
controller side as parameter at post action
IEnumerable<HttpPostedFileBase> postedPhotos.
I want to know if postedPhotos[0] was sent, if so save it to the db.
iterate trough remaining postedPhotos collection and take further action
only to those which actually contains photo (user can send only one or two
image instead of five)
so I tried with
if(postedPhotos.First() != null)
foreach(var photo in postedPhotos.Where(x=>x.ContentLength>0))
{....}
but this doesn't work since I'm touching postedPhoto null value and I'm
getting exception
Object reference not set to an instance of an object.
ofcourse everything works if I send all five photos but I'm interesting
how to handle this situation.
THanks
Wait command usage in linux=?iso-8859-1?Q?=3F_=96_unix.stackexchange.com?=
Wait command usage in linux? – unix.stackexchange.com
#!/bin/bash function back() { sleep $1 exit $2 } back $1 $2 & b=$! if
`wait $!`;then echo success else echo failure fi bash-3.00# ./back 300 0
failure bash-3.00# ./back 300 1 …
#!/bin/bash function back() { sleep $1 exit $2 } back $1 $2 & b=$! if
`wait $!`;then echo success else echo failure fi bash-3.00# ./back 300 0
failure bash-3.00# ./back 300 1 …
Where can I download the dhcpd3-server source code?
Where can I download the dhcpd3-server source code?
could you tell me where I can find the source code for dhcpd3-server? I
know I can find the ready packages for Ubuntu/Fedora but I need to
download the source code so I can..study it
Thanx in advance
could you tell me where I can find the source code for dhcpd3-server? I
know I can find the ready packages for Ubuntu/Fedora but I need to
download the source code so I can..study it
Thanx in advance
Monday, 30 September 2013
Remove the [play-mvc] tag meta.stackoverflow.com
Remove the [play-mvc] tag – meta.stackoverflow.com
Yesterday I noticed an large amount of playframework questions hit the
first page of the active tab. They all got edited by the same user. In
about 20 minutes, the user retagged over 40 questions ...
Yesterday I noticed an large amount of playframework questions hit the
first page of the active tab. They all got edited by the same user. In
about 20 minutes, the user retagged over 40 questions ...
Five answers downvoted=?iso-8859-1?Q?=2C_without_any_comment_=96_meta.stackoverflow.com?=
Five answers downvoted, without any comment – meta.stackoverflow.com
Me and 4 others answered this question: PHP form validation gives parse
error You can see that all of them downvoted, this is not the case, but
the downvoter should provided a correct answer or ...
Me and 4 others answered this question: PHP form validation gives parse
error You can see that all of them downvoted, this is not the case, but
the downvoter should provided a correct answer or ...
Return all data from a SQLite DB into two columns in Android
Return all data from a SQLite DB into two columns in Android
I'm trying to return all data from my two column DB into two different
TextViews. In one attempt, I can return all the data, but it's only in one
TextView, in the second attempt, I can get it into the two TextViews, but
it only returns the first row from the DB. First try:
//--- Returns only first result
//--- DB Method
public String[] getPres2() {
String[] columns = new String[] { KEY_PRES, KEY_YEAR};
Cursor cursor = db.query(DB_TABLE, columns, null, null, null, null,
null);
if (cursor != null) {
cursor.moveToFirst();
String pstYr[] = new String[2];
pstYr[0] = cursor.getString(0);
pstYr[1] = cursor.getString(1);
cursor.close();
this.db.close();
return pstYr;
}
return null;
}
//--- in the activity
public void DBMethod2() {
dba = new DBAdapter(this);
dba.open();
String[] pst_Str = dba.getPres2();
dba.close();
pst_TV.setText(pst_Str[0]);
yrs_TV.setText(pst_Str[1]);
}
and the second try:
//--- Returns all results, but only in a single TextView
//--- DB Method
public String getPres3() {
String[] columns = new String[] { KEY_PRES, KEY_YEAR};
Cursor cursor = db.query(DB_TABLE, columns, null, null, null, null,
null);
String result = "";
int iPrs = cursor.getColumnIndex(KEY_PRES);
int iYr = cursor.getColumnIndex(KEY_YEAR);
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()){
result = result + cursor.getString(iPrs) + "\n" +
cursor.getString(iYr) + "\n" + "\n";
}
return result;
}
//--- In Activity
public void DBMethod3() {
dba = new DBAdapter(this);
dba.open();
String pstY_Str = dba.getPres3();
dba.close();
pst_TV.setText(pstY_Str);
}
Any help?
I'm trying to return all data from my two column DB into two different
TextViews. In one attempt, I can return all the data, but it's only in one
TextView, in the second attempt, I can get it into the two TextViews, but
it only returns the first row from the DB. First try:
//--- Returns only first result
//--- DB Method
public String[] getPres2() {
String[] columns = new String[] { KEY_PRES, KEY_YEAR};
Cursor cursor = db.query(DB_TABLE, columns, null, null, null, null,
null);
if (cursor != null) {
cursor.moveToFirst();
String pstYr[] = new String[2];
pstYr[0] = cursor.getString(0);
pstYr[1] = cursor.getString(1);
cursor.close();
this.db.close();
return pstYr;
}
return null;
}
//--- in the activity
public void DBMethod2() {
dba = new DBAdapter(this);
dba.open();
String[] pst_Str = dba.getPres2();
dba.close();
pst_TV.setText(pst_Str[0]);
yrs_TV.setText(pst_Str[1]);
}
and the second try:
//--- Returns all results, but only in a single TextView
//--- DB Method
public String getPres3() {
String[] columns = new String[] { KEY_PRES, KEY_YEAR};
Cursor cursor = db.query(DB_TABLE, columns, null, null, null, null,
null);
String result = "";
int iPrs = cursor.getColumnIndex(KEY_PRES);
int iYr = cursor.getColumnIndex(KEY_YEAR);
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()){
result = result + cursor.getString(iPrs) + "\n" +
cursor.getString(iYr) + "\n" + "\n";
}
return result;
}
//--- In Activity
public void DBMethod3() {
dba = new DBAdapter(this);
dba.open();
String pstY_Str = dba.getPres3();
dba.close();
pst_TV.setText(pstY_Str);
}
Any help?
Maskedtextbox Mask change depending to OS language
Maskedtextbox Mask change depending to OS language
Hello I have created maskedtextbox in my WinForms app with mask: 0/0 AAAAA
and when I do install this on PC where Czech language is set as default it
converts the backslash into dot so I have 0.0 AAAAA
May I ask if is there any way to avoid this automatic change?
Thank you for your time.
Hello I have created maskedtextbox in my WinForms app with mask: 0/0 AAAAA
and when I do install this on PC where Czech language is set as default it
converts the backslash into dot so I have 0.0 AAAAA
May I ask if is there any way to avoid this automatic change?
Thank you for your time.
Sunday, 29 September 2013
HTML Textbook JQuery removing background image
HTML Textbook JQuery removing background image
I'm having a textbox as below:
<input type="text" name="fname" class="username" id="fname">
And I have the corresponding CSS for it:
.username {
background:#FFFFFF url(images/admin4.png) no-repeat;
width: 256px; height: 24px
}
Now when user click on this textbox, I would like to remove the image, and
when the the textbox is blur, the image showing back.
I've tried something like below:
$( document ).ready(function() {
$('#fname').focus(
function(){
$(this).css({'url' : ''});
});
but the image remains there? I've tried alert in the function, both blur
and focus seems to working fine but images just cant be remove?
I'm having a textbox as below:
<input type="text" name="fname" class="username" id="fname">
And I have the corresponding CSS for it:
.username {
background:#FFFFFF url(images/admin4.png) no-repeat;
width: 256px; height: 24px
}
Now when user click on this textbox, I would like to remove the image, and
when the the textbox is blur, the image showing back.
I've tried something like below:
$( document ).ready(function() {
$('#fname').focus(
function(){
$(this).css({'url' : ''});
});
but the image remains there? I've tried alert in the function, both blur
and focus seems to working fine but images just cant be remove?
Events getting lost when moving to a RequireJS setup
Events getting lost when moving to a RequireJS setup
So, I am porting a small Backbone app to a RequireJS setup, surprisingly I
get a problem with this code:
define([
'jquery',
'underscore',
'backbone',
'channel',
'templates'
], function ($, _, Backbone, channel, JST) {
'use strict';
var SomeView = Backbone.View.extend({
// ... template, render
initialize: function() {
var that = this;
// was working previosuly, not sure why not now...
// this.collection.on('reset', function() {
// that.render()
// });
// hack:
this.collection.deferred.then(function() {
that.render()
});
So, I found that introducing an event bus like this helps:
this.listenTo(channel, 'reset', function(id) {
that.render()
});
But I am not sure if I miss something else. Does communication between
modules with RequireJS involve in general an event bus, or can I debug the
missing 'reset' event in another way?
Thanks!
So, I am porting a small Backbone app to a RequireJS setup, surprisingly I
get a problem with this code:
define([
'jquery',
'underscore',
'backbone',
'channel',
'templates'
], function ($, _, Backbone, channel, JST) {
'use strict';
var SomeView = Backbone.View.extend({
// ... template, render
initialize: function() {
var that = this;
// was working previosuly, not sure why not now...
// this.collection.on('reset', function() {
// that.render()
// });
// hack:
this.collection.deferred.then(function() {
that.render()
});
So, I found that introducing an event bus like this helps:
this.listenTo(channel, 'reset', function(id) {
that.render()
});
But I am not sure if I miss something else. Does communication between
modules with RequireJS involve in general an event bus, or can I debug the
missing 'reset' event in another way?
Thanks!
Excel count number of cells in column with "an" until next cell is non"an"
Excel count number of cells in column with "an" until next cell is non"an"
I would like to count the number of cells in column with "an", where the
counting starts at a given row and counts go down to count the number of
cells with "an" until a non-"an" cell is found?
For example Column A : opp an an an an opp
I would like to calculate how many cell with "an" until the next non an
cell. For this example answer will be 4.
Another example Column B :an an opp an an an
The answer will be 2.
I would like to count the number of cells in column with "an", where the
counting starts at a given row and counts go down to count the number of
cells with "an" until a non-"an" cell is found?
For example Column A : opp an an an an opp
I would like to calculate how many cell with "an" until the next non an
cell. For this example answer will be 4.
Another example Column B :an an opp an an an
The answer will be 2.
Undefined variable notice in php/mysql
Undefined variable notice in php/mysql
I'm trying to update some records in by database via php. This is the part
of my code that returns error:
// Check if button name "Submit" is active, do this
if(isset($_POST['Submit'])){
for($i=0;$i<$count;$i++){
$query="UPDATE products SET title='$title[$i]', descr='$descr[$i]',
price='$price[$i]', cname='$cname[$i]' WHERE pid='$pid[$i]'";
$upd=mysql_query($query);
}
}
if($upd){
echo "Successful";
echo "<BR>";
//display_manager_menu();
}
else {
echo "ERROR";
}
It returns: "Notice: Undefined variable: upd ". Since I set $upd as
mysql_query result, I have no idea why I get this message. Any ideas?
I'm trying to update some records in by database via php. This is the part
of my code that returns error:
// Check if button name "Submit" is active, do this
if(isset($_POST['Submit'])){
for($i=0;$i<$count;$i++){
$query="UPDATE products SET title='$title[$i]', descr='$descr[$i]',
price='$price[$i]', cname='$cname[$i]' WHERE pid='$pid[$i]'";
$upd=mysql_query($query);
}
}
if($upd){
echo "Successful";
echo "<BR>";
//display_manager_menu();
}
else {
echo "ERROR";
}
It returns: "Notice: Undefined variable: upd ". Since I set $upd as
mysql_query result, I have no idea why I get this message. Any ideas?
Saturday, 28 September 2013
Count and sort by number of occurrences
Count and sort by number of occurrences
I have an array like this:
var items = [
{name: 'popcorn', category: 'snacks'},
{name: 'nachos', category: 'snacks'},
...
{name: 'coke', category: 'drinks'}
];
I want to get a list of categories ordered by the number of items on it
(most items first):
['snacks', 'drinks']
Here is how I did it:
var categories = _.chain(items)
.countBy(function (i) { return i.category })
.pairs()
.sortBy(function (c) { return -c[1] })
.value();
So the result of countBy is an object, and I have to use pairs to convert
it into an array of arrays in order to sort it.
I wonder if there is a more straightforward way to do it? Built-in function?
I have an array like this:
var items = [
{name: 'popcorn', category: 'snacks'},
{name: 'nachos', category: 'snacks'},
...
{name: 'coke', category: 'drinks'}
];
I want to get a list of categories ordered by the number of items on it
(most items first):
['snacks', 'drinks']
Here is how I did it:
var categories = _.chain(items)
.countBy(function (i) { return i.category })
.pairs()
.sortBy(function (c) { return -c[1] })
.value();
So the result of countBy is an object, and I have to use pairs to convert
it into an array of arrays in order to sort it.
I wonder if there is a more straightforward way to do it? Built-in function?
Get application name in Django model
Get application name in Django model
The following is the model for a Django app. Let the app be called MyApp.
The idea is for every app to have it's folder under the MEDIA_ROOT.
class MyModel(models.Model):
.... #Other fields
datoteka = models.FileField(upload_to = 'MyApp',null = True)
Is there a way to get the name of the app from somewhere and remove the
hardcoded MyApp.
This is a similar question, however I have no access to the request object
in the model.
The following is the model for a Django app. Let the app be called MyApp.
The idea is for every app to have it's folder under the MEDIA_ROOT.
class MyModel(models.Model):
.... #Other fields
datoteka = models.FileField(upload_to = 'MyApp',null = True)
Is there a way to get the name of the app from somewhere and remove the
hardcoded MyApp.
This is a similar question, however I have no access to the request object
in the model.
Double scripted array as an lvalue
Double scripted array as an lvalue
I was wondering, how would i express it in code?
rand() % 2 == 0 ? map[x][y] = 'm' : map[x][y] = 'M';
when I compile that line in g++, it doesn't give an error. However gcc
tells me I need an lvalue left of the assignment statement. I thought
maybe I should give them an integer
int i = rand() % 2 ? .......
but that also gives me an error. Can someone please help? Thanks
I was wondering, how would i express it in code?
rand() % 2 == 0 ? map[x][y] = 'm' : map[x][y] = 'M';
when I compile that line in g++, it doesn't give an error. However gcc
tells me I need an lvalue left of the assignment statement. I thought
maybe I should give them an integer
int i = rand() % 2 ? .......
but that also gives me an error. Can someone please help? Thanks
Graphical Layout of XML not showing when i install updates Android
Graphical Layout of XML not showing when i install updates Android
Android: Graphical layout of XML file is not showing up, this happened
when i installed updates and SDK tools from SDK manager.
I searched on google. But i am not getting the answer which can help me.
Kindly help me i am kinda stuck in my work.
Android: Graphical layout of XML file is not showing up, this happened
when i installed updates and SDK tools from SDK manager.
I searched on google. But i am not getting the answer which can help me.
Kindly help me i am kinda stuck in my work.
Friday, 27 September 2013
Export Website Code to txt file
Export Website Code to txt file
I would like to know if it is possible to make an application or script or
etc, that could export the html code of websites that I visit on my
browser. If so, please let me know what language could take a care of this
job and if I need resources such as an api. Thank you.
I would like to know if it is possible to make an application or script or
etc, that could export the html code of websites that I visit on my
browser. If so, please let me know what language could take a care of this
job and if I need resources such as an api. Thank you.
Weird response with foreach
Weird response with foreach
i am trying to concatenate values into a string which later is attached to
a hidden input.
This is the forach loop:
<?php
$langid = array();
$transLang = '';
foreach($translator['langs'] as $lang) {
$curlang = $lang->term_id;
$langid[] = $curlang;
$transLang .= '('.$curlang.'), ';
// for testing
echo $transLang."<br />";
}
?>
<input type="hidden" name="selectedLang" value="<?php echo $transLang; ?>" />
..
The langid[] array grabs everything correctly
but $transLang echoed into the input only shows the first value which is:
(3),
When i use this line:
echo $transLang."<br />";
Which i added for testing it echoes:
(3),
(3), (10),
(3), (10), (12),
(3), (10), (12), (27),
(3), (10), (12), (27), (19),
(3), (10), (12), (27), (19), (20),
The last one is the complete string after the foreach finished runing but
the input field value is always only the first run meaning (3),
Any idea why this is happening?
i am trying to concatenate values into a string which later is attached to
a hidden input.
This is the forach loop:
<?php
$langid = array();
$transLang = '';
foreach($translator['langs'] as $lang) {
$curlang = $lang->term_id;
$langid[] = $curlang;
$transLang .= '('.$curlang.'), ';
// for testing
echo $transLang."<br />";
}
?>
<input type="hidden" name="selectedLang" value="<?php echo $transLang; ?>" />
..
The langid[] array grabs everything correctly
but $transLang echoed into the input only shows the first value which is:
(3),
When i use this line:
echo $transLang."<br />";
Which i added for testing it echoes:
(3),
(3), (10),
(3), (10), (12),
(3), (10), (12), (27),
(3), (10), (12), (27), (19),
(3), (10), (12), (27), (19), (20),
The last one is the complete string after the foreach finished runing but
the input field value is always only the first run meaning (3),
Any idea why this is happening?
How to create a fade out button
How to create a fade out button
I want to make a button onclick to fade out the music and call the media
player to stop?
I want this to be over 5 sec
I have tried to make a timer like code, but i dont get how to make it work
- can you guys help me?
float volume = 1;
float speed = 0.05f;
public void FadeOut(float deltaTime);
{
mpMain.setVolume(1, 1);
volume -= speed* deltaTime; }
public void FadeIn(float deltaTime1);
{
mpMain.setVolume(0, 0);
volume += speed* deltaTime1; }
}}
I want to make a button onclick to fade out the music and call the media
player to stop?
I want this to be over 5 sec
I have tried to make a timer like code, but i dont get how to make it work
- can you guys help me?
float volume = 1;
float speed = 0.05f;
public void FadeOut(float deltaTime);
{
mpMain.setVolume(1, 1);
volume -= speed* deltaTime; }
public void FadeIn(float deltaTime1);
{
mpMain.setVolume(0, 0);
volume += speed* deltaTime1; }
}}
Find neighbour LLDP - access points participating in a mesh network
Find neighbour LLDP - access points participating in a mesh network
Is it possible to find the neighbour in a wireless mesh network? If there
is an AP say AP1 which is connected to a switch and also another AP say
AP2 to form a mesh then is it possible to find the neighbour of AP1 (which
is AP2) if both access points support LLDP?
Is it possible to find the neighbour in a wireless mesh network? If there
is an AP say AP1 which is connected to a switch and also another AP say
AP2 to form a mesh then is it possible to find the neighbour of AP1 (which
is AP2) if both access points support LLDP?
take an element class and put it to another element as atribute
take an element class and put it to another element as atribute
SOURCE CODE
<div class="level_1 euItem generation_y _2012">
<img border="0" src="img2.jpg" class="euImg" alt="Run">
<a href="/sport/sport_2014/media_gallery/images/car.htm"
class="lightview">Run</a>
</div>
<div class="level_1 euItem youth_forum">
<img border="0" src="img3.jpg" class="euImg" alt="Run">
<a href="/sport/sport_2014/media_gallery/images/aircraft.htm"
class="lightview">Run</a>
</div>
i need to take the third class of a div element and put it as attribute to
a A element
RESULT CODE:
<div class="level_1 euItem generation_y _2012">
<img border="0" src="img2.jpg" class="euImg" alt="Run">
<a href="/sport/sport_2014/media_gallery/images/car.htm"
class="lightview" data-lightview-group="generation_y _2012">Run</a>
</div>
<div class="level_1 euItem youth_forum">
<img border="0" src="img3.jpg" class="euImg">
<a href="/sport/sport_2014/media_gallery/images/aircraft.htm"
class="lightview" alt="Run" data-lightview-group="youth_forum">Run</a>
</div>
i am at this point now, but it doesn't work. note that each div have a
different class that i have to use:
var lightviewGroup = $(this).attr('class').split(' ');
$('div.euBox div.level_1 h4
a.link-ico').attr('data-lightview-group',imgCaption[2]);
SOURCE CODE
<div class="level_1 euItem generation_y _2012">
<img border="0" src="img2.jpg" class="euImg" alt="Run">
<a href="/sport/sport_2014/media_gallery/images/car.htm"
class="lightview">Run</a>
</div>
<div class="level_1 euItem youth_forum">
<img border="0" src="img3.jpg" class="euImg" alt="Run">
<a href="/sport/sport_2014/media_gallery/images/aircraft.htm"
class="lightview">Run</a>
</div>
i need to take the third class of a div element and put it as attribute to
a A element
RESULT CODE:
<div class="level_1 euItem generation_y _2012">
<img border="0" src="img2.jpg" class="euImg" alt="Run">
<a href="/sport/sport_2014/media_gallery/images/car.htm"
class="lightview" data-lightview-group="generation_y _2012">Run</a>
</div>
<div class="level_1 euItem youth_forum">
<img border="0" src="img3.jpg" class="euImg">
<a href="/sport/sport_2014/media_gallery/images/aircraft.htm"
class="lightview" alt="Run" data-lightview-group="youth_forum">Run</a>
</div>
i am at this point now, but it doesn't work. note that each div have a
different class that i have to use:
var lightviewGroup = $(this).attr('class').split(' ');
$('div.euBox div.level_1 h4
a.link-ico').attr('data-lightview-group',imgCaption[2]);
Powershell function issue
Powershell function issue
Error I'm getting is the following
Missing closing '}' in statement block.
I'm using this to automate adding user to a .dat file which has hundreds
of user's for one of our systems. I was task with taking this part over
and well I don't like to do anything manually. So I wrote a script to do
95% of it for me and it removes user's just fine. But this function I'm
trying here adds the user in 2 different specific places to keep it nice
and net. I'm still learning powershell so any direction would be great and
you wont hurt my feelings I'm no pro nor novice here.
Function Add{
$username = Read-Host "User to add to REP01-02 Printing"
$LOCreportADD1 = "\\rep01\E$\orant\Report60\Server\cgicmd.dat"
$LOCreportADD2 = "\\rep02\e$\orant\Report60\Server\cgicmd.dat"
$Username1 = $username+": "
$prd = "prd: "
$userid = "userid="
$henation = "/henation@rmsprd %*"
$Text1 = get-content $LOCreportADD1
$Text2 = get-content $LOCreportADD2
$NewText1 = @()
foreach ($Line in $Text1) {
if ($Line -eq "Insert new user1") {
$Line = $Line.Replace("Insert new user1 \", "Insert new user1 \")
$NewText1 += $Line
$NewText1 += $username1+$userid+$username+$henation
}
Elseif ($Line -eq "New User2") {
$Line = $Line.Replace("New User2 \", "New User2 \")
$NewText12 += $Line
$NewText12 += $username+$prd+$userid+$username+$henation
}
$NewText1 | Set-Content $LOCreportADD1
}
Error I'm getting is the following
Missing closing '}' in statement block.
I'm using this to automate adding user to a .dat file which has hundreds
of user's for one of our systems. I was task with taking this part over
and well I don't like to do anything manually. So I wrote a script to do
95% of it for me and it removes user's just fine. But this function I'm
trying here adds the user in 2 different specific places to keep it nice
and net. I'm still learning powershell so any direction would be great and
you wont hurt my feelings I'm no pro nor novice here.
Function Add{
$username = Read-Host "User to add to REP01-02 Printing"
$LOCreportADD1 = "\\rep01\E$\orant\Report60\Server\cgicmd.dat"
$LOCreportADD2 = "\\rep02\e$\orant\Report60\Server\cgicmd.dat"
$Username1 = $username+": "
$prd = "prd: "
$userid = "userid="
$henation = "/henation@rmsprd %*"
$Text1 = get-content $LOCreportADD1
$Text2 = get-content $LOCreportADD2
$NewText1 = @()
foreach ($Line in $Text1) {
if ($Line -eq "Insert new user1") {
$Line = $Line.Replace("Insert new user1 \", "Insert new user1 \")
$NewText1 += $Line
$NewText1 += $username1+$userid+$username+$henation
}
Elseif ($Line -eq "New User2") {
$Line = $Line.Replace("New User2 \", "New User2 \")
$NewText12 += $Line
$NewText12 += $username+$prd+$userid+$username+$henation
}
$NewText1 | Set-Content $LOCreportADD1
}
wordpress and woocommerce - how to programmatically set menu order for products
wordpress and woocommerce - how to programmatically set menu order for
products
I am new to wordpress and woocommerce and I would like to programmatically
set the menu order for products. I have been looking for solutions and
found this post here
Woocommerce Displaying Products With Product Images
However I am a wordpress novice and don't really understand how or when I
would call the function in the post solution. The poster says it is
written as a plugin but I don't know how to write plugins. I could modify
this function to do what I want but when or how would i call it from a
webpage?
Thanks a lot
products
I am new to wordpress and woocommerce and I would like to programmatically
set the menu order for products. I have been looking for solutions and
found this post here
Woocommerce Displaying Products With Product Images
However I am a wordpress novice and don't really understand how or when I
would call the function in the post solution. The poster says it is
written as a plugin but I don't know how to write plugins. I could modify
this function to do what I want but when or how would i call it from a
webpage?
Thanks a lot
Thursday, 26 September 2013
In C#, should I use struct to wrap an object in order to fulfill additional interfaces?
In C#, should I use struct to wrap an object in order to fulfill
additional interfaces?
There is an existing class from a third-party library I want to reuse, but
it does not implement some of the required interfaces. I'm thinking of
wrapping it inside a struct to fulfill the required interfaces (basically
like how Scala does it). The reason why I prefer struct over class for
this use case is because it only stores one thing: the wrapped object, and
it probably won't incur performance penalties? But I'm not sure if boxing
would occur if I pass a struct to some method that takes in an interface?
And are there any other drawbacks about this approach?
additional interfaces?
There is an existing class from a third-party library I want to reuse, but
it does not implement some of the required interfaces. I'm thinking of
wrapping it inside a struct to fulfill the required interfaces (basically
like how Scala does it). The reason why I prefer struct over class for
this use case is because it only stores one thing: the wrapped object, and
it probably won't incur performance penalties? But I'm not sure if boxing
would occur if I pass a struct to some method that takes in an interface?
And are there any other drawbacks about this approach?
Wednesday, 25 September 2013
Give me some code for styling the checkbox in css3?
Give me some code for styling the checkbox in css3?
I don't know css in depth.So please give me some code for styling the
checkbox. thank u.
I don't know css in depth.So please give me some code for styling the
checkbox. thank u.
Thursday, 19 September 2013
I am using eclipse and i get an error--I think it's an error with the way i imported the becker file
I am using eclipse and i get an error--I think it's an error with the way
i imported the becker file
I am using eclipse and i get this error:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
at Wall.main(Wall.java:6)
her's a screen shot"http://postimg.org/image/ufvv9p6aj/"
Here is the code:
import becker.robots.*;
import javax.swing.*;
public class Wall
{
public static void main (String[] args)
{
JFrame frame = new JFrame ();
frame.setVisible(true);
JPanel panel = new JPanel ();
panel.setVisible(true);
frame.add(panel);
JColorChooser color = new JColorChooser();
panel.add(color);
}
}
i imported the becker file
I am using eclipse and i get this error:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
at Wall.main(Wall.java:6)
her's a screen shot"http://postimg.org/image/ufvv9p6aj/"
Here is the code:
import becker.robots.*;
import javax.swing.*;
public class Wall
{
public static void main (String[] args)
{
JFrame frame = new JFrame ();
frame.setVisible(true);
JPanel panel = new JPanel ();
panel.setVisible(true);
frame.add(panel);
JColorChooser color = new JColorChooser();
panel.add(color);
}
}
How can i put a variable in string.xml?
How can i put a variable in string.xml?
I have a variable settings in this way:
String result = " Non in carica";
String resultusb = " No";
--
--
if (isCharging) {
result = " In carica";
}
if (usbCharge){
resultusb = " Si";
}
The variable result or resultusb assuming two values depending on the
situation..there is no TextView only this, Only one variable with more
values. I need translate them so i have to put them in the strings.xml..
How can i do it? How can i translate them?
I have a variable settings in this way:
String result = " Non in carica";
String resultusb = " No";
--
--
if (isCharging) {
result = " In carica";
}
if (usbCharge){
resultusb = " Si";
}
The variable result or resultusb assuming two values depending on the
situation..there is no TextView only this, Only one variable with more
values. I need translate them so i have to put them in the strings.xml..
How can i do it? How can i translate them?
SQL query with "not exists" not working
SQL query with "not exists" not working
I'm trying to use a simple query but I'm not getting anywhere. The
objective is to "learn" how "not exists" works. I have a simple table with
"idUsuario" as default ID for users and a name.
SELECT * FROM usuario
WHERE NOT EXISTS (
SELECT * FROM usuario
WHERE u.idUsuario =16
)
Here i'm trying to get ALL the users from the table where the ID IS NOT
16. But it just get all of them.. What am I doing wrong?
Thanks in advance!
I'm trying to use a simple query but I'm not getting anywhere. The
objective is to "learn" how "not exists" works. I have a simple table with
"idUsuario" as default ID for users and a name.
SELECT * FROM usuario
WHERE NOT EXISTS (
SELECT * FROM usuario
WHERE u.idUsuario =16
)
Here i'm trying to get ALL the users from the table where the ID IS NOT
16. But it just get all of them.. What am I doing wrong?
Thanks in advance!
#1241 - Operand should contain 1 column(s) IN
#1241 - Operand should contain 1 column(s) IN
i have a problem with mysql 5.6 version. Sorry if my english sucks, and
sorry if the format is not the right one, im in a hurry.
Mysql throws me this error "#1241 - Operand should contain 1 column(s)"
from this query:
SELECT DISTINCT (P.`P_nombre`, P.`P_raza`)
FROM `Perros` AS P,
`Adiestramientos` as A
WHERE P.`P_codigo` = A.`P_codigo` AND A.`A_nroLegajo` = '1500'
AND P.`P_codigo` NOT IN(
SELECT A.`P_codigo`
FROM `Adiestramientos` as A
WHERE A.`A_nroLegajo`= '4600'
)
It seems to work fine on Mysql 5.0, the problem seems to be on the IN
operator
Hope you can help me.
Thanks!
i have a problem with mysql 5.6 version. Sorry if my english sucks, and
sorry if the format is not the right one, im in a hurry.
Mysql throws me this error "#1241 - Operand should contain 1 column(s)"
from this query:
SELECT DISTINCT (P.`P_nombre`, P.`P_raza`)
FROM `Perros` AS P,
`Adiestramientos` as A
WHERE P.`P_codigo` = A.`P_codigo` AND A.`A_nroLegajo` = '1500'
AND P.`P_codigo` NOT IN(
SELECT A.`P_codigo`
FROM `Adiestramientos` as A
WHERE A.`A_nroLegajo`= '4600'
)
It seems to work fine on Mysql 5.0, the problem seems to be on the IN
operator
Hope you can help me.
Thanks!
Sharing a jdbc "Connection" across threads
Sharing a jdbc "Connection" across threads
I have a main thread that runs periodically. It opens a connection, with
setAutoCommit(false), and is passed as reference to few child threads to
do various database read/write operations. A reasonably good number of
operations are performed in the child threads. After all the child threads
had completed their db operations, the main thread commits the transaction
with the opened connection. Kindly note that I run the threads inside the
ExecutorService. comments/advise/a-new-idea are welcome. take a look at
the pseudo code below...
Connection con = getPrimaryDatabaseConnection();
// let me decide whether to commit or rollback
con.setAutoCommit(false);
ExecutorService executorService = getExecutor();
// connection is sent as param to the class constructor/set-method
// the jobs uses the provided connection to do the db operation
Callable jobs[] = getJobs(con);
List futures = new ArrayList();
// note: generics are not mentioned just to keep this simple
for(Callable job:jobs) {
futures.add(executorService.submit(job));
}
executorService.shutdown();
// wait till the jobs complete
while (!executorService.isTerminated()) {
;
}
List result = ...;
for (Future future : futures) {
try {
results.add(future.get());
} catch (InterruptedException e) {
try {
// a jobs has failed, we will rollback the transaction and throw
exception
connection.rollback();
result = null;
throw SomeException();
} catch(Exception e) {
// exception
} finally {
try {
connection.close();
} catch(Exception e) {//nothing to do}
}
}
}
// all the jobs completed successfully!
try {
// some other checks
connection.commit();
return results;
} finally {
try {
connection.close();
} catch(Exception e){//nothing to do}
}
I have a main thread that runs periodically. It opens a connection, with
setAutoCommit(false), and is passed as reference to few child threads to
do various database read/write operations. A reasonably good number of
operations are performed in the child threads. After all the child threads
had completed their db operations, the main thread commits the transaction
with the opened connection. Kindly note that I run the threads inside the
ExecutorService. comments/advise/a-new-idea are welcome. take a look at
the pseudo code below...
Connection con = getPrimaryDatabaseConnection();
// let me decide whether to commit or rollback
con.setAutoCommit(false);
ExecutorService executorService = getExecutor();
// connection is sent as param to the class constructor/set-method
// the jobs uses the provided connection to do the db operation
Callable jobs[] = getJobs(con);
List futures = new ArrayList();
// note: generics are not mentioned just to keep this simple
for(Callable job:jobs) {
futures.add(executorService.submit(job));
}
executorService.shutdown();
// wait till the jobs complete
while (!executorService.isTerminated()) {
;
}
List result = ...;
for (Future future : futures) {
try {
results.add(future.get());
} catch (InterruptedException e) {
try {
// a jobs has failed, we will rollback the transaction and throw
exception
connection.rollback();
result = null;
throw SomeException();
} catch(Exception e) {
// exception
} finally {
try {
connection.close();
} catch(Exception e) {//nothing to do}
}
}
}
// all the jobs completed successfully!
try {
// some other checks
connection.commit();
return results;
} finally {
try {
connection.close();
} catch(Exception e){//nothing to do}
}
partial match dictionary key(of tuples) in python
partial match dictionary key(of tuples) in python
I have a dictionary that maps 3tuple to 3tuple where key-tuples have some
element in common
dict= { (a,b,c):(1:2:3),
(a,b,d):tuple1,
(a,e,b):tuple,
.
(f,g,h):tuple,
.
.
.
tuple:tuple
}
now how can I find the values that match to (a,b,anyX) in a dictionary ie
(1:2:3) and tuple1
this is computer generated and very large thus, it takes effort to
determine anyX.
so, any good ways I can do this?
I have a dictionary that maps 3tuple to 3tuple where key-tuples have some
element in common
dict= { (a,b,c):(1:2:3),
(a,b,d):tuple1,
(a,e,b):tuple,
.
(f,g,h):tuple,
.
.
.
tuple:tuple
}
now how can I find the values that match to (a,b,anyX) in a dictionary ie
(1:2:3) and tuple1
this is computer generated and very large thus, it takes effort to
determine anyX.
so, any good ways I can do this?
i am not able to read the entity message from javax.ws.rs.core.Response in java client
i am not able to read the entity message from javax.ws.rs.core.Response in
java client
hi i created the restful server and client using jax-rs in apache tomee.i
am returning status and entity from server and i am reading successful but
i am not able to read the entity from response object.
This is my code in server side Rest.
@Path("/login")
@POST
public javax.ws.rs.core.Response login(String user,@Context
HttpServletRequest request,@Context HttpServletResponse response)throws
ServletException, IOException
{
int sc=200;
//this above status code i am changing base on the error
return javax.ws.rs.core.Response.status(sc).entity("error on server
side").type(MediaType.TEXT_PLAIN).build();
}
i created client for invoking the above service in java
Response
response=WebClient.create("http://myserver:8080/Snefocare").path("/User/login").post(user);
System.out.println("the status is "+response.getStatus());
System.out.println("the metadata is "+response.getEntity());
System.out.println("the entity "+response.getEntity());
output of above code
the status is 200
the metadata is
sun.net.www.protocol.http.HttpURLConnection$HttpInputStream@294c4c55
the entity
sun.net.www.protocol.http.HttpURLConnection$HttpInputStream@294c4c55
i do not know why entity is printing in some other formate.
java client
hi i created the restful server and client using jax-rs in apache tomee.i
am returning status and entity from server and i am reading successful but
i am not able to read the entity from response object.
This is my code in server side Rest.
@Path("/login")
@POST
public javax.ws.rs.core.Response login(String user,@Context
HttpServletRequest request,@Context HttpServletResponse response)throws
ServletException, IOException
{
int sc=200;
//this above status code i am changing base on the error
return javax.ws.rs.core.Response.status(sc).entity("error on server
side").type(MediaType.TEXT_PLAIN).build();
}
i created client for invoking the above service in java
Response
response=WebClient.create("http://myserver:8080/Snefocare").path("/User/login").post(user);
System.out.println("the status is "+response.getStatus());
System.out.println("the metadata is "+response.getEntity());
System.out.println("the entity "+response.getEntity());
output of above code
the status is 200
the metadata is
sun.net.www.protocol.http.HttpURLConnection$HttpInputStream@294c4c55
the entity
sun.net.www.protocol.http.HttpURLConnection$HttpInputStream@294c4c55
i do not know why entity is printing in some other formate.
Wednesday, 18 September 2013
Relationship between return keyword and finally keyword in c#
Relationship between return keyword and finally keyword in c#
i want to find out that the relationship between "return" and "finally"
keywords. what is the execution order and what happens when exception
occurs and return keyword is called after code block does some stuff, if
there is two nested finally blocks as shown below,
try
{
try
{
}
catch (Exception)
{
//do some stuff
return;
}
finally
{
}
}
catch (Exception)
{
}
finally
{
}
i want to find out that the relationship between "return" and "finally"
keywords. what is the execution order and what happens when exception
occurs and return keyword is called after code block does some stuff, if
there is two nested finally blocks as shown below,
try
{
try
{
}
catch (Exception)
{
//do some stuff
return;
}
finally
{
}
}
catch (Exception)
{
}
finally
{
}
Usecase of |= in python
Usecase of |= in python
I came across |= operator today in codebase and did not recognise it, and
searching google for python "|=" returns nothing useful for me.
Testing the outcome of operations below yields the following:
>>> from itertools import combinations
>>> def wtf_is_it(left, right):
>>> orig_left = left
>>> left |= right
>>> return '%s |= %s == %s ' % (orig_left, right, left)
>>> results = [wtf_is_it(l, r) for l, r in combinations(xrange(5), 2)]
>>> print '\n'.join(results)
0 |= 1 == 1
0 |= 2 == 2
0 |= 3 == 3
0 |= 4 == 4
1 |= 0 == 1
1 |= 2 == 3
1 |= 3 == 3
1 |= 4 == 5
2 |= 0 == 2
2 |= 1 == 3
2 |= 3 == 3
2 |= 4 == 6
3 |= 0 == 3
3 |= 1 == 3
3 |= 2 == 3
3 |= 4 == 7
4 |= 0 == 4
4 |= 1 == 5
4 |= 2 == 6
4 |= 3 == 7
Looks like it does an or and if the right side is greater than the left
then it adds the two together, otherwise it maintains the orig value?
What is the name of this operator and what is the value of it?
I came across |= operator today in codebase and did not recognise it, and
searching google for python "|=" returns nothing useful for me.
Testing the outcome of operations below yields the following:
>>> from itertools import combinations
>>> def wtf_is_it(left, right):
>>> orig_left = left
>>> left |= right
>>> return '%s |= %s == %s ' % (orig_left, right, left)
>>> results = [wtf_is_it(l, r) for l, r in combinations(xrange(5), 2)]
>>> print '\n'.join(results)
0 |= 1 == 1
0 |= 2 == 2
0 |= 3 == 3
0 |= 4 == 4
1 |= 0 == 1
1 |= 2 == 3
1 |= 3 == 3
1 |= 4 == 5
2 |= 0 == 2
2 |= 1 == 3
2 |= 3 == 3
2 |= 4 == 6
3 |= 0 == 3
3 |= 1 == 3
3 |= 2 == 3
3 |= 4 == 7
4 |= 0 == 4
4 |= 1 == 5
4 |= 2 == 6
4 |= 3 == 7
Looks like it does an or and if the right side is greater than the left
then it adds the two together, otherwise it maintains the orig value?
What is the name of this operator and what is the value of it?
How to define and consume enums in typescript when using AMD?
How to define and consume enums in typescript when using AMD?
The following tsc command doesn't create a usable foo.d.ts:
TSC -declaration -m amd foo.ts
foo.ts:
export enum foo {
bar
}
foo.d.ts:
export declare enum foo {
bar,
}
But
///<reference path="./foo.d.ts"/>
doesn't work until the "export" is removed fro foo.d.ts. Is there another
way of declaring a variable of type foo in a second file? Seems to me
referencing foo.ts should have worked (it didn't):
///<reference path="./foo.ts"/>
Am I missing a keyword?
The following tsc command doesn't create a usable foo.d.ts:
TSC -declaration -m amd foo.ts
foo.ts:
export enum foo {
bar
}
foo.d.ts:
export declare enum foo {
bar,
}
But
///<reference path="./foo.d.ts"/>
doesn't work until the "export" is removed fro foo.d.ts. Is there another
way of declaring a variable of type foo in a second file? Seems to me
referencing foo.ts should have worked (it didn't):
///<reference path="./foo.ts"/>
Am I missing a keyword?
Endpoint authentication, Trying to add header JSESSION to ClientService in JAVA API
Endpoint authentication, Trying to add header JSESSION to ClientService in
JAVA API
I'm implementing a custom API on top of SBT. I'm doing this so I can
manipulate and transform the response from connections before returning it
to the user.
The basic auth with username and password is working. But I can't seem to
find out how I can add the JSESSIONID header to ClientService
(ClientService.Args) on a request before its sent.
Any idea how this can be done ?
JAVA API
I'm implementing a custom API on top of SBT. I'm doing this so I can
manipulate and transform the response from connections before returning it
to the user.
The basic auth with username and password is working. But I can't seem to
find out how I can add the JSESSIONID header to ClientService
(ClientService.Args) on a request before its sent.
Any idea how this can be done ?
Take in a array from another class
Take in a array from another class
I have this code for my table view:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
NSArray *array = [[NSArray alloc] initWithObjects:@"Kupong 1",@"Kupong
2",@"Kupong 3",@"Kupong 4", @"Kupong 5", @"Kupong 5",@"Kupong
6",@"Kupong 7",@"Kupong 8",nil];
self.kupongArray = array;
self.title = @"Kupong";
}
but I want to change the array to a different array from another class,
how can I do this?
I have this code for my table view:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
NSArray *array = [[NSArray alloc] initWithObjects:@"Kupong 1",@"Kupong
2",@"Kupong 3",@"Kupong 4", @"Kupong 5", @"Kupong 5",@"Kupong
6",@"Kupong 7",@"Kupong 8",nil];
self.kupongArray = array;
self.title = @"Kupong";
}
but I want to change the array to a different array from another class,
how can I do this?
Java Regexp does not match exact number of matches
Java Regexp does not match exact number of matches
I've got the following string:
0 days 00 hour 20 min 51 sec
I would like to extract all the numbers from it using Java's Regular
Expressions:
Pattern pattern = Pattern.compile("(\\d){1,2} days (\\d){2} hour (\\d){2}
min (\\d){2} sec");
Matcher m = pattern.matcher("0 days 00 hour 20 min 51 sec");
To my surprisde m.group(4) returns 1 and not 51. The same goes for
m.group(2) which returns 0 and not 00
I found this confusing since {n} should match exactly n occurrences of the
preceding expression , not ?
I've got the following string:
0 days 00 hour 20 min 51 sec
I would like to extract all the numbers from it using Java's Regular
Expressions:
Pattern pattern = Pattern.compile("(\\d){1,2} days (\\d){2} hour (\\d){2}
min (\\d){2} sec");
Matcher m = pattern.matcher("0 days 00 hour 20 min 51 sec");
To my surprisde m.group(4) returns 1 and not 51. The same goes for
m.group(2) which returns 0 and not 00
I found this confusing since {n} should match exactly n occurrences of the
preceding expression , not ?
Continuous carousel speed control
Continuous carousel speed control
I have a button that calls an animate function:
$(document).on("click", this.settings.startButton, function () {
$(self.settings.itemClass).each(function (i, item) {
self.animateItem(this, 100, self);
});
})
and my animate function looks like this:
animateItem: function (item, speed, self) {
var width = $(item).outerWidth(true);
var containerWidth = $(self.settings.itemContainerClass).width();
var left = parseInt($(item).css("left"));
if (left < 0) {
$(item).css("left", containerWidth - (2 * width) + "px");
self.animateItem(item, speed, self);
} else {
$(item).animate({ "left": left - width + "px" }, {
duration: speed,
complete: function () {
self.animateItem(this, speed, self);
}
});
}
}
Now, when the animateItem function is called, everything works fine. The
Carousel is moving fast but what I want is to control the speed. I would
like to start of fairly slow and quickly progress to very fast and then
slowly stop.
Does anyone know of a way I can get that to happen?
If you need to see my html or css, just let me know.
Cheers, /r3plica
I have a button that calls an animate function:
$(document).on("click", this.settings.startButton, function () {
$(self.settings.itemClass).each(function (i, item) {
self.animateItem(this, 100, self);
});
})
and my animate function looks like this:
animateItem: function (item, speed, self) {
var width = $(item).outerWidth(true);
var containerWidth = $(self.settings.itemContainerClass).width();
var left = parseInt($(item).css("left"));
if (left < 0) {
$(item).css("left", containerWidth - (2 * width) + "px");
self.animateItem(item, speed, self);
} else {
$(item).animate({ "left": left - width + "px" }, {
duration: speed,
complete: function () {
self.animateItem(this, speed, self);
}
});
}
}
Now, when the animateItem function is called, everything works fine. The
Carousel is moving fast but what I want is to control the speed. I would
like to start of fairly slow and quickly progress to very fast and then
slowly stop.
Does anyone know of a way I can get that to happen?
If you need to see my html or css, just let me know.
Cheers, /r3plica
Hows this macro working?
Hows this macro working?
#define MAX_T(a,b,d) \
{ int len = (d);printf("len %d", len);}
int main()
{
//MAX_T(10,30, smgarbage)
MAX_T(10,30, len)
}
I wrote this code in C
when i comment MAX_T(10,30, smgarbage) and run with output len 24
when i comment MAX_T(10,30, len) and run MAX_T(10,30, smgarbage) i get
this compiler error
test.c: In function 'main':
test.c:34: error: 'smgarbage' undeclared (first use in this function)
test.c:34: error: (Each undeclared identifier is reported only once
test.c:34: error: for each function it appears in.)
when executing MAX_T(10,30, len) why compiler error is not coming? Is
statement int len = (d); causing this? How?
#define MAX_T(a,b,d) \
{ int len = (d);printf("len %d", len);}
int main()
{
//MAX_T(10,30, smgarbage)
MAX_T(10,30, len)
}
I wrote this code in C
when i comment MAX_T(10,30, smgarbage) and run with output len 24
when i comment MAX_T(10,30, len) and run MAX_T(10,30, smgarbage) i get
this compiler error
test.c: In function 'main':
test.c:34: error: 'smgarbage' undeclared (first use in this function)
test.c:34: error: (Each undeclared identifier is reported only once
test.c:34: error: for each function it appears in.)
when executing MAX_T(10,30, len) why compiler error is not coming? Is
statement int len = (d); causing this? How?
Tuesday, 17 September 2013
Show merge header in Gridview
Show merge header in Gridview
I want to show Merge header of grid view using C#+ASP.net as shown in my
image bellow:
Any idea how to achieve this?
I want to show Merge header of grid view using C#+ASP.net as shown in my
image bellow:
Any idea how to achieve this?
Why Looper.prepare() is needed when read clipboard?
Why Looper.prepare() is needed when read clipboard?
Code:
public static String[] getClipboard(Context context) {
String[] result = null;
try {
Looper.prepare();
ClipboardManager cm = (ClipboardManager)
context.getSystemService(Context.CLIPBOARD_SERVICE);
CharSequence text = cm.getText();
if (text != null && text.toString().length() > 0) {
result = new String[] { text.toString() };
}
// Looper.loop();
} catch (Exception e) {
Log.d(TAG, "getClipboard(): " + e);
}
return result;
}
private class UpdateTask extends AsyncTask<Void, HistoryItem, Void> {
private ProgressDialog dialog;
protected Void doInBackground(Void... params) {
try {
HistoryItem item = new HistoryItem(HistoryEnum.CLIPBOARD);
item.records = HistoryUtil.getClipboard(getContext());
...
Logcat:
getClipboard(): java.lang.RuntimeException: Can't create handler inside
thread that has not called Looper.prepare()
Code:
public static String[] getClipboard(Context context) {
String[] result = null;
try {
Looper.prepare();
ClipboardManager cm = (ClipboardManager)
context.getSystemService(Context.CLIPBOARD_SERVICE);
CharSequence text = cm.getText();
if (text != null && text.toString().length() > 0) {
result = new String[] { text.toString() };
}
// Looper.loop();
} catch (Exception e) {
Log.d(TAG, "getClipboard(): " + e);
}
return result;
}
private class UpdateTask extends AsyncTask<Void, HistoryItem, Void> {
private ProgressDialog dialog;
protected Void doInBackground(Void... params) {
try {
HistoryItem item = new HistoryItem(HistoryEnum.CLIPBOARD);
item.records = HistoryUtil.getClipboard(getContext());
...
Logcat:
getClipboard(): java.lang.RuntimeException: Can't create handler inside
thread that has not called Looper.prepare()
undefined reference to opEquals: Linker errors with Derelict3 Bindings to SDL2
undefined reference to opEquals: Linker errors with Derelict3 Bindings to
SDL2
I am trying to write a simple hello world using the Derelict3 bindings for
SDL2. I am getting errors during linking that I have not seen before.
module main;
import derelict.sdl2.sdl;
pragma(lib, "DerelictSDL2");
pragma(lib, "DerelictUtil");
pragma(lib, "dl");
int main(string[] args)
{
DerelictSDL2.load();
return 0;
}
command line:
dmd src/main.d -debug -Iinclude -Isrc -L-Llib -L-lSDL2
output:
> lib/libDerelictSDL2.a(sdl_55_698.o):(.rodata+0x41e8): undefined
reference to `_D6object6Object8opEqualsMFC6ObjectC6ObjectZb'
> lib/libDerelictUtil.a(exception_9b_6db.o):(.rodata+0xe8): undefined
> reference to `_D6object6Object8opEqualsMFC6ObjectC6ObjectZb'
> lib/libDerelictUtil.a(exception_9d_89d.o):(.rodata+0x178): undefined
> reference to `_D6object6Object8opEqualsMFC6ObjectC6ObjectZb'
> lib/libDerelictUtil.a(exception_9e_7a5.o):(.rodata+0x118): undefined
> reference to `_D6object6Object8opEqualsMFC6ObjectC6ObjectZb' collect2:
> ld returned 1 exit status
> --- errorlevel 1
what I have tried:
verify that Derelict3 and SDL2 are up-to-date
changing the order of my linked libraries
searching online: I could only find 1 other post related to this:
http://dblog.aldacron.net/forum/index.php?topic=834.0
I am using DMD64 D Compiler v2.063.2. Any help is appreciated. Thanks.
SDL2
I am trying to write a simple hello world using the Derelict3 bindings for
SDL2. I am getting errors during linking that I have not seen before.
module main;
import derelict.sdl2.sdl;
pragma(lib, "DerelictSDL2");
pragma(lib, "DerelictUtil");
pragma(lib, "dl");
int main(string[] args)
{
DerelictSDL2.load();
return 0;
}
command line:
dmd src/main.d -debug -Iinclude -Isrc -L-Llib -L-lSDL2
output:
> lib/libDerelictSDL2.a(sdl_55_698.o):(.rodata+0x41e8): undefined
reference to `_D6object6Object8opEqualsMFC6ObjectC6ObjectZb'
> lib/libDerelictUtil.a(exception_9b_6db.o):(.rodata+0xe8): undefined
> reference to `_D6object6Object8opEqualsMFC6ObjectC6ObjectZb'
> lib/libDerelictUtil.a(exception_9d_89d.o):(.rodata+0x178): undefined
> reference to `_D6object6Object8opEqualsMFC6ObjectC6ObjectZb'
> lib/libDerelictUtil.a(exception_9e_7a5.o):(.rodata+0x118): undefined
> reference to `_D6object6Object8opEqualsMFC6ObjectC6ObjectZb' collect2:
> ld returned 1 exit status
> --- errorlevel 1
what I have tried:
verify that Derelict3 and SDL2 are up-to-date
changing the order of my linked libraries
searching online: I could only find 1 other post related to this:
http://dblog.aldacron.net/forum/index.php?topic=834.0
I am using DMD64 D Compiler v2.063.2. Any help is appreciated. Thanks.
How to get different ranksep for certain ranks
How to get different ranksep for certain ranks
I want my bottom rank of nodes to have smaller ranksep than the rest of my
graph. How do you do this? I can't seem to find the right syntax to set
ranksep separately for different subgraphs.
This is not working - all ranks are separated the same (both the big
ranksep and small ranksep are ignored):
graph G{
{ ranksep=1.0; // big separation
1 -- 2
1 -- 3
}
{ ranksep=0.2; // small separation
2 -- 4
2 -- 5
3 -- 6
3 -- 7
}
}
Result:
I want my bottom rank of nodes to have smaller ranksep than the rest of my
graph. How do you do this? I can't seem to find the right syntax to set
ranksep separately for different subgraphs.
This is not working - all ranks are separated the same (both the big
ranksep and small ranksep are ignored):
graph G{
{ ranksep=1.0; // big separation
1 -- 2
1 -- 3
}
{ ranksep=0.2; // small separation
2 -- 4
2 -- 5
3 -- 6
3 -- 7
}
}
Result:
Bit masks and long-long
Bit masks and long-long
I have a masking procedure (which creates an all-ones bit mask for the
bottom half for a given size):
template<class T>
T bottom_half() {
T halfway = ((sizeof(T) * 8) / 2);
T mask = (1 << halfway) - 1;
return mask;
}
which works fine if I call bottom_half<int>() or long or char. But for
some reason when I run it with long long, halfway is correctly set to 32,
but mask is 0. Why would that be?
I have a masking procedure (which creates an all-ones bit mask for the
bottom half for a given size):
template<class T>
T bottom_half() {
T halfway = ((sizeof(T) * 8) / 2);
T mask = (1 << halfway) - 1;
return mask;
}
which works fine if I call bottom_half<int>() or long or char. But for
some reason when I run it with long long, halfway is correctly set to 32,
but mask is 0. Why would that be?
Git hook to push commits to a dedicated git-svn branch
Git hook to push commits to a dedicated git-svn branch
I have a git repository with 3 branches develop, master, and svn. I want
to take the latest commits to develop and push or mirror them, if you
will, to the svn branch where I will then immediately git svn dcommit them
to my SVN repo.
The reason I want to do it this was is to basically have a develop branch
and a develop-svn mirror branch where they both have the same code
history, but the develop branch is clean and doesn't contain any of the
git-svn metadata like git-svn-id's
Is there a straightforward way to achieve this with a Git Hook system?
I have a git repository with 3 branches develop, master, and svn. I want
to take the latest commits to develop and push or mirror them, if you
will, to the svn branch where I will then immediately git svn dcommit them
to my SVN repo.
The reason I want to do it this was is to basically have a develop branch
and a develop-svn mirror branch where they both have the same code
history, but the develop branch is clean and doesn't contain any of the
git-svn metadata like git-svn-id's
Is there a straightforward way to achieve this with a Git Hook system?
Sunday, 15 September 2013
tfs 2012 publish does not work
tfs 2012 publish does not work
I am trying to deploy my asp.net mvc application to another server but
getting this error:
Error 101 Web deployment task failed. (Could not connect to the remote
computer ...
I have installed the Web Management service on the server and it is running?
I have also tried to queue a build in tfs which builds fine on the
buildserver however the deployment is not happening:
/p:DeployOnBuild=True
/p:DeployTarget=MSDeployPublish
/p:CreatePackageOnPublish=True
/p:MsDeployServiceUrl=https://myserver:8172/msdeploy.axd
/p:MsDeployPublishMethod=WMSVC
/p:UserName=myserver\myadmin
/p:Password=mypassword
/p:AllowUntrustedCertificate=True
/p:DeployIisAppPath="Default Web Site/myappname"
I am trying to deploy my asp.net mvc application to another server but
getting this error:
Error 101 Web deployment task failed. (Could not connect to the remote
computer ...
I have installed the Web Management service on the server and it is running?
I have also tried to queue a build in tfs which builds fine on the
buildserver however the deployment is not happening:
/p:DeployOnBuild=True
/p:DeployTarget=MSDeployPublish
/p:CreatePackageOnPublish=True
/p:MsDeployServiceUrl=https://myserver:8172/msdeploy.axd
/p:MsDeployPublishMethod=WMSVC
/p:UserName=myserver\myadmin
/p:Password=mypassword
/p:AllowUntrustedCertificate=True
/p:DeployIisAppPath="Default Web Site/myappname"
C# - How to not redraw image each time picture box is repainted
C# - How to not redraw image each time picture box is repainted
I have a picture box with some images that never need to move. It's for a
map designer. The user chooses how many columns and rows the map will
have, then it gets drawn as a line grid, and i have a mouseMove method
because when the user hovers over the edge of a cell it needs to highlight
red. So the map is being repainted continuously, very fast, when the mouse
is moving. This was no issue when i just had drawLines on the map for rows
and columns. But now that i just added a cell background image, the cell
background images flicker on mouse move as they are being redrawn too
fast.
Any help appreciated. Thanks.
I have a picture box with some images that never need to move. It's for a
map designer. The user chooses how many columns and rows the map will
have, then it gets drawn as a line grid, and i have a mouseMove method
because when the user hovers over the edge of a cell it needs to highlight
red. So the map is being repainted continuously, very fast, when the mouse
is moving. This was no issue when i just had drawLines on the map for rows
and columns. But now that i just added a cell background image, the cell
background images flicker on mouse move as they are being redrawn too
fast.
Any help appreciated. Thanks.
popup in my chrome extension is tiny and does not show data
popup in my chrome extension is tiny and does not show data
My chrome extension that I uploaded has a popup that is tiny. You can see
one pixel of information but that is it. Does anyone have a solution?
Here is a screenshot:
http://imgur.com/mVy0aOZ (it wont let me upload an image because i'm new.)
Thanks!
My chrome extension that I uploaded has a popup that is tiny. You can see
one pixel of information but that is it. Does anyone have a solution?
Here is a screenshot:
http://imgur.com/mVy0aOZ (it wont let me upload an image because i'm new.)
Thanks!
PHP - same code on one or multiple lines
PHP - same code on one or multiple lines
This are two lines of codes. Could anyone tell me what the difference is
between the first way and the second? I'd like both to do exactly the same
thing.
$test = isset($_POST['test'])?$_POST['test']:[];
if(isset($_POST['test'])){
$test[] = $_POST['test'];
}
Thanks !
This are two lines of codes. Could anyone tell me what the difference is
between the first way and the second? I'd like both to do exactly the same
thing.
$test = isset($_POST['test'])?$_POST['test']:[];
if(isset($_POST['test'])){
$test[] = $_POST['test'];
}
Thanks !
Creating and filling a matrix by input in C++
Creating and filling a matrix by input in C++
im trying to write a program in C++ which is able to multiply matrices.
Unfortunately, I'm not able to create a matrice out of 2 vectors. The
goal: I typ in the number of rows and the number of coloms. Then there
should be a matrix created with those dimensions. Then I can fill (for
example rows = 2 cols = 2 => Matrix = 2 x 2) the matrix by typing in the
numbers. I tried it with this 2 codes: (second one is in a header file)
#include <iostream>
#include "Matrix_functions.hpp"
using namespace std;
int main ()
{
//matrices and dimensions
int rows1, cols1, rows2, cols2;
int **matrix1, **matrix2, **result = 0;
cout << "Enter matrix dimensions" << "\n" << endl;
cin >> rows1 >> cols1 >> rows2 >> cols2;
cout << "Enter a matrix" << "\n" << endl;
matrix1 = new int*[rows1];
matrix2 = new int*[rows2];
// Read values from the command line into a matrix
read_matrix(matrix1, rows1, cols1);
read_matrix(matrix2, rows2, cols2);
// Multiply matrix1 one and matrix2, and put the result in matrix result
//multiply_matrix(matrix1, rows1, cols1, matrix2, rows2, cols2, result);
//print_matrix(result, rows1, cols2);
//TODO: free memory holding the matrices
return 0;
}
This is the main code. Now the header file with the read_matrix function:
#ifndef MATRIX_FUNCTIONS_H_INCLUDED
#define MATRIX_FUNCTIONS_H_INCLUDED
void read_matrix(int** matrix, int rows, int cols)
{
for(int i = 0; i < rows; ++i)
matrix[i] = new int[cols];
}
//int print_matrix(int result, int rows1, int cols1)
//{
// return 0;
//}
//int multiply_matrix(int matrix2, int rows2, int cols2, int matrix3, int
rows3, int cols3, int result2)
//{
// return result2;
//}
im trying to write a program in C++ which is able to multiply matrices.
Unfortunately, I'm not able to create a matrice out of 2 vectors. The
goal: I typ in the number of rows and the number of coloms. Then there
should be a matrix created with those dimensions. Then I can fill (for
example rows = 2 cols = 2 => Matrix = 2 x 2) the matrix by typing in the
numbers. I tried it with this 2 codes: (second one is in a header file)
#include <iostream>
#include "Matrix_functions.hpp"
using namespace std;
int main ()
{
//matrices and dimensions
int rows1, cols1, rows2, cols2;
int **matrix1, **matrix2, **result = 0;
cout << "Enter matrix dimensions" << "\n" << endl;
cin >> rows1 >> cols1 >> rows2 >> cols2;
cout << "Enter a matrix" << "\n" << endl;
matrix1 = new int*[rows1];
matrix2 = new int*[rows2];
// Read values from the command line into a matrix
read_matrix(matrix1, rows1, cols1);
read_matrix(matrix2, rows2, cols2);
// Multiply matrix1 one and matrix2, and put the result in matrix result
//multiply_matrix(matrix1, rows1, cols1, matrix2, rows2, cols2, result);
//print_matrix(result, rows1, cols2);
//TODO: free memory holding the matrices
return 0;
}
This is the main code. Now the header file with the read_matrix function:
#ifndef MATRIX_FUNCTIONS_H_INCLUDED
#define MATRIX_FUNCTIONS_H_INCLUDED
void read_matrix(int** matrix, int rows, int cols)
{
for(int i = 0; i < rows; ++i)
matrix[i] = new int[cols];
}
//int print_matrix(int result, int rows1, int cols1)
//{
// return 0;
//}
//int multiply_matrix(int matrix2, int rows2, int cols2, int matrix3, int
rows3, int cols3, int result2)
//{
// return result2;
//}
Squire is breaking other tests
Squire is breaking other tests
I'm using Karma, Jasmine, Jasmine.Async, Sinon and Chai.
The good news...this test works correctly. The dependency is mocked, spies
get called, and intentionally breaking the test subject results in failed
tests.
define(['chai', 'squire'], function (chai, Squire) {
var should = chai.should(),
async = new AsyncSpec(this),
subject, injector = new Squire();
describe('EventsView', function () {
describe('when an event is clicked', function () {
var mockModel, stub;
async.beforeEach(function (done) {
setFixtures('<div id="screen"></div>');
mockModel = {
toJSON: function () {
return {
dimensions: "hu1 vu2",
events: [{
date: "8/29/2013",
id: "8923",
title: "Fancy Show",
venue: "Lovely venue",
}, {
date: "8/29/2013",
id: "9034",
title: "Exciting Game",
venue: "Lovely stadium"
}],
id: 3566,
kind: "events",
title: "Top events this week"
};
},
fetch: function () {}
};
stub = sinon.stub();
injector.mock('tiles/events-tile/events-detail-model',
Squire.Helpers.constructs({
fetch: stub
}));
injector.require(["tiles/events-tile/events-view"],
function (ev) {
subject = new ev(mockModel);
done();
});
});
async.afterEach(function (done) {
injector.clean();
injector.remove();
done();
});
async.it('should attempt to fetch the event details', function
(done) {
$('#screen').html(subject.$el);
$('.event').first().click();
stub.called.should.be.true;
done();
});
});
});
});
The bad news...a shed load of other tests that were previously fine are
now failing for weird reasons. For example: Error: Backbone.history has
already been started and TypeError: 'undefined' is not an object
(evaluating 'Backbone.Validation.mixin')
If I comment out the snippet
injector.require(["tiles/events-tile/events-view"], function (ev) {
subject = new ev(mockModel);
done();
});
Then the other tests work again. I've had stuff like this happen before
and it has usually been down to a sinon mock not getting restored. The
injector.clean() call doesn't seem to be providing the magic bullet I was
hoping for.
I'm using Karma, Jasmine, Jasmine.Async, Sinon and Chai.
The good news...this test works correctly. The dependency is mocked, spies
get called, and intentionally breaking the test subject results in failed
tests.
define(['chai', 'squire'], function (chai, Squire) {
var should = chai.should(),
async = new AsyncSpec(this),
subject, injector = new Squire();
describe('EventsView', function () {
describe('when an event is clicked', function () {
var mockModel, stub;
async.beforeEach(function (done) {
setFixtures('<div id="screen"></div>');
mockModel = {
toJSON: function () {
return {
dimensions: "hu1 vu2",
events: [{
date: "8/29/2013",
id: "8923",
title: "Fancy Show",
venue: "Lovely venue",
}, {
date: "8/29/2013",
id: "9034",
title: "Exciting Game",
venue: "Lovely stadium"
}],
id: 3566,
kind: "events",
title: "Top events this week"
};
},
fetch: function () {}
};
stub = sinon.stub();
injector.mock('tiles/events-tile/events-detail-model',
Squire.Helpers.constructs({
fetch: stub
}));
injector.require(["tiles/events-tile/events-view"],
function (ev) {
subject = new ev(mockModel);
done();
});
});
async.afterEach(function (done) {
injector.clean();
injector.remove();
done();
});
async.it('should attempt to fetch the event details', function
(done) {
$('#screen').html(subject.$el);
$('.event').first().click();
stub.called.should.be.true;
done();
});
});
});
});
The bad news...a shed load of other tests that were previously fine are
now failing for weird reasons. For example: Error: Backbone.history has
already been started and TypeError: 'undefined' is not an object
(evaluating 'Backbone.Validation.mixin')
If I comment out the snippet
injector.require(["tiles/events-tile/events-view"], function (ev) {
subject = new ev(mockModel);
done();
});
Then the other tests work again. I've had stuff like this happen before
and it has usually been down to a sinon mock not getting restored. The
injector.clean() call doesn't seem to be providing the magic bullet I was
hoping for.
how to insert new data to an already existing table?
how to insert new data to an already existing table?
in my table I have email but I also want to add more data to that table I
was thinking of adding
insert into but that adds the new data to a new record in the database but
I want to add it to the same record as email. what im doing is when
someone signs up it saves that data to a separate table and only saves
email to the table I want to add more data to. how can I link the email
address after login to add more data to the table where the email address
is ? please help
in my table I have email but I also want to add more data to that table I
was thinking of adding
insert into but that adds the new data to a new record in the database but
I want to add it to the same record as email. what im doing is when
someone signs up it saves that data to a separate table and only saves
email to the table I want to add more data to. how can I link the email
address after login to add more data to the table where the email address
is ? please help
Saturday, 14 September 2013
crystal formula to show 2 different values in same row with a criteria
crystal formula to show 2 different values in same row with a criteria
Have a query that displays result as follows
Student ScoreType Score Course Total Grade 120001 EXAMS SCORE (70%) 37.1
Mathematics 61.1 C5
120001 CLASS SCORE (30%) 24 Mathematics 61.1 C5
120001 EXAMS SCORE (70%) 46.9 English 67.9 C4 120001 CLASS SCORE (30%) 21
English 67.9 C4
120001 CLASS SCORE (30%) 28.5 ICT 90.1 A1
120001 EXAMS SCORE (70%) 61.6 ICT 90.1 A1
In crystal report, I have grouped by Course, now in the same line, I want
the results to be something like this Course Class Score Exams Score Total
Score Grade Mathematics 24 37.1 61.1 C5 English 21 46.9 67.9 C5 ICT 28.5
61.6 90.1 A1 The difficulty am having is the Class Score & Exam Score,
that is dependent on the ScoreType field so i create a crystal formula
called class Score like this Class Score = if {table.ScoreType} = "CLASS
SCORE (30%)" then {table.Total} else 0 Exam Score = if {table.ScoreType} =
"EXAMS SCORE (70%)" then {table.Total} else 0 Unfortunately, these
formulas give wrong information for almost all the columns, what can i do.
I have tried with cross-tab and it doesn't give what i want, any help on
the formula will be great since the scoreType will not change. Thank you
Have a query that displays result as follows
Student ScoreType Score Course Total Grade 120001 EXAMS SCORE (70%) 37.1
Mathematics 61.1 C5
120001 CLASS SCORE (30%) 24 Mathematics 61.1 C5
120001 EXAMS SCORE (70%) 46.9 English 67.9 C4 120001 CLASS SCORE (30%) 21
English 67.9 C4
120001 CLASS SCORE (30%) 28.5 ICT 90.1 A1
120001 EXAMS SCORE (70%) 61.6 ICT 90.1 A1
In crystal report, I have grouped by Course, now in the same line, I want
the results to be something like this Course Class Score Exams Score Total
Score Grade Mathematics 24 37.1 61.1 C5 English 21 46.9 67.9 C5 ICT 28.5
61.6 90.1 A1 The difficulty am having is the Class Score & Exam Score,
that is dependent on the ScoreType field so i create a crystal formula
called class Score like this Class Score = if {table.ScoreType} = "CLASS
SCORE (30%)" then {table.Total} else 0 Exam Score = if {table.ScoreType} =
"EXAMS SCORE (70%)" then {table.Total} else 0 Unfortunately, these
formulas give wrong information for almost all the columns, what can i do.
I have tried with cross-tab and it doesn't give what i want, any help on
the formula will be great since the scoreType will not change. Thank you
Java: Creating new custom object in main function?
Java: Creating new custom object in main function?
I created an object within a class:
private class Viscosity{
float magnitude;
private Viscosity(float Magnitude){
magnitude = Magnitude;
}
}
In my main function, I attempt to extract data from a text file and create
a new Viscosity object, but it seems that I cannot access this private
object.
For example, I want to add it to a List of Objects:
listofObjects.add(new Viscosity(50.0f));
But I receive the error:
No enclosing instance of type is accessible. Must qualify the allocation
with an enclosing instance of type ClassName (e.g. x.new A() where x is an
instance of ClassName).
How can I accomplish this?
I created an object within a class:
private class Viscosity{
float magnitude;
private Viscosity(float Magnitude){
magnitude = Magnitude;
}
}
In my main function, I attempt to extract data from a text file and create
a new Viscosity object, but it seems that I cannot access this private
object.
For example, I want to add it to a List of Objects:
listofObjects.add(new Viscosity(50.0f));
But I receive the error:
No enclosing instance of type is accessible. Must qualify the allocation
with an enclosing instance of type ClassName (e.g. x.new A() where x is an
instance of ClassName).
How can I accomplish this?
How can I dynamically modify a subview from another view?
How can I dynamically modify a subview from another view?
Let me explain my problem in the context of the program I'm working with.
This program consists of one main window which has an NSOutlineView and an
NSTabView. The NSTabViewItems (and their corresponding subview) are added
dynamically at runtime (using Cmd+T). The aforementioned subview is part
of a separate XIB file; the subview consists of various simple input
controls. All of this works as I've just described.
I want the NSOutlineView to offer context menus for the various items it
is displaying which may manipulate some of the controls within the
currently active NSTabViewItem's subview.
The most obvious way that I see to do this is (this is just a simplified
example, not my actual code):
NSOutlineViewSubclass.h
@interface ... : NSOutlineView
@property (weak) IBOutlet NSTabView *tabView;
@end
NSOutlineViewSubclass.m
@implementation ...
@synthesize tabView;
- (void)foo
{
NSTabViewItem *currentTab = [tabView selectedTabViewItem];
TabViewSubView *tabViewSubView = [currentTab view];
//
//Manipulate subview controls here
//
}
@end
This seems like it violates the MVC paradigm, since I am manipulating data
directly in the view (in this case, NSOutlineViewSubclass), rather than
going through a controller. But, for now, the only time I use the
NSOutlineViewSubclassViewController is to spawn a new view for a new tab
in the first place. My NSOutlineViewSubclass doesn't even know about it's
NSOutlineViewSubclassViewController. Did I miss a step here in connecting
these two?
Thanks!
Let me explain my problem in the context of the program I'm working with.
This program consists of one main window which has an NSOutlineView and an
NSTabView. The NSTabViewItems (and their corresponding subview) are added
dynamically at runtime (using Cmd+T). The aforementioned subview is part
of a separate XIB file; the subview consists of various simple input
controls. All of this works as I've just described.
I want the NSOutlineView to offer context menus for the various items it
is displaying which may manipulate some of the controls within the
currently active NSTabViewItem's subview.
The most obvious way that I see to do this is (this is just a simplified
example, not my actual code):
NSOutlineViewSubclass.h
@interface ... : NSOutlineView
@property (weak) IBOutlet NSTabView *tabView;
@end
NSOutlineViewSubclass.m
@implementation ...
@synthesize tabView;
- (void)foo
{
NSTabViewItem *currentTab = [tabView selectedTabViewItem];
TabViewSubView *tabViewSubView = [currentTab view];
//
//Manipulate subview controls here
//
}
@end
This seems like it violates the MVC paradigm, since I am manipulating data
directly in the view (in this case, NSOutlineViewSubclass), rather than
going through a controller. But, for now, the only time I use the
NSOutlineViewSubclassViewController is to spawn a new view for a new tab
in the first place. My NSOutlineViewSubclass doesn't even know about it's
NSOutlineViewSubclassViewController. Did I miss a step here in connecting
these two?
Thanks!
backbone iterate over router
backbone iterate over router
I have parts of the site that can be loaded via WebSocket (and render with
underscore), or if a view doesn't exist for that particular URI, it should
load via ajax.
I would like to bind a event for each link from site, check if the URI is
in my router. If it is, navigate to it and trigger the function from the
router which does the job. If it's not, navigate to it, but don't trigger.
Make the ajax request and just put the html under #main.
Here is part of my route (you see routes are traditionally defined via the
"routes" key, but also via this.route):
Router = Backbone.Router.extend({
routes: {
"about": "about",
"*path": "notFound"
},
initialize: function() {
this.route(/g\/([a-z0-9]{2,})$/, "game");
this.route(/rank\/([0-9]{1,})$/, "rank");
//...
},
//...
});
What I would like (this code works, but I need the variabile "Router"
populated (http://jsfiddle.net/3jdSe/):
var Router = {
'routes': [
{
'uri' : 'about'
},
{
'uri' : /rank\/([0-9]{1,})$/
},
]
};
doesUriExistInRouter = function(uri) {
var routeFound = null;
_(Router.routes).each(function(route){
var routeUri = route.uri;
var regexPattern = null;
if( routeUri.toString()[routeUri.toString().length - 2] == '$' )
{// is defined as regex
regexPattern = new RegExp( '^' + routeUri.toString().substr(0,
routeUri.toString().length - 2) + '$' );
} else {
regexPattern = new RegExp( '^' + routeUri + '$' );
}
if (!_.isNull(uri.match(regexPattern))) {
routeFound = routeUri;
return;
}
});
return routeFound != null ? routeFound : false;
}
_(['about', '/rank/2', 'nope']).each(function(uri){
if(doesUriExistInRouter(uri) !== false) {
console.log('Router for '+uri+' found');
} else {
console.log('Router for '+uri+' NOT found');
}
});
I may have some alternatives (although are hack-y). I hesitated to do some
other things that were so easy to solve via a simple iterator and a regex
match. So I'm asking you now.
Thanks in advance!
I have parts of the site that can be loaded via WebSocket (and render with
underscore), or if a view doesn't exist for that particular URI, it should
load via ajax.
I would like to bind a event for each link from site, check if the URI is
in my router. If it is, navigate to it and trigger the function from the
router which does the job. If it's not, navigate to it, but don't trigger.
Make the ajax request and just put the html under #main.
Here is part of my route (you see routes are traditionally defined via the
"routes" key, but also via this.route):
Router = Backbone.Router.extend({
routes: {
"about": "about",
"*path": "notFound"
},
initialize: function() {
this.route(/g\/([a-z0-9]{2,})$/, "game");
this.route(/rank\/([0-9]{1,})$/, "rank");
//...
},
//...
});
What I would like (this code works, but I need the variabile "Router"
populated (http://jsfiddle.net/3jdSe/):
var Router = {
'routes': [
{
'uri' : 'about'
},
{
'uri' : /rank\/([0-9]{1,})$/
},
]
};
doesUriExistInRouter = function(uri) {
var routeFound = null;
_(Router.routes).each(function(route){
var routeUri = route.uri;
var regexPattern = null;
if( routeUri.toString()[routeUri.toString().length - 2] == '$' )
{// is defined as regex
regexPattern = new RegExp( '^' + routeUri.toString().substr(0,
routeUri.toString().length - 2) + '$' );
} else {
regexPattern = new RegExp( '^' + routeUri + '$' );
}
if (!_.isNull(uri.match(regexPattern))) {
routeFound = routeUri;
return;
}
});
return routeFound != null ? routeFound : false;
}
_(['about', '/rank/2', 'nope']).each(function(uri){
if(doesUriExistInRouter(uri) !== false) {
console.log('Router for '+uri+' found');
} else {
console.log('Router for '+uri+' NOT found');
}
});
I may have some alternatives (although are hack-y). I hesitated to do some
other things that were so easy to solve via a simple iterator and a regex
match. So I'm asking you now.
Thanks in advance!
PHP curl_multi_exec is using 99% cpu . Any special apache or php configuration to lower this issue?
PHP curl_multi_exec is using 99% cpu . Any special apache or php
configuration to lower this issue?
By runing the basic example from php.net , httpd.exe is using 99% cpu .
Are there any
php or apache configuration to fix this ? I know i don't have enough
processing power
, but I have never seen such a simple script to load that much a 2,4GHz
single core cpu .
configuration to lower this issue?
By runing the basic example from php.net , httpd.exe is using 99% cpu .
Are there any
php or apache configuration to fix this ? I know i don't have enough
processing power
, but I have never seen such a simple script to load that much a 2,4GHz
single core cpu .
How JSON POST request can be handled by WCF?
How JSON POST request can be handled by WCF?
I need to handle, in my .net WCF service, JSON data (POST request) from a
third party application. Basically the third party app would be consuming
my WCF service. The posted JSON data structure is known. I would like to
know how the JSON data can be de-serialized in my service?
I need to handle, in my .net WCF service, JSON data (POST request) from a
third party application. Basically the third party app would be consuming
my WCF service. The posted JSON data structure is known. I would like to
know how the JSON data can be de-serialized in my service?
Only display value of text_field if @search is present
Only display value of text_field if @search is present
I have an search form, for my Search model. My problem is that i only want
to display the value of the form if @search is present. I wrote this code:
<%= f.text_field :keyword, :value => @search.keyword if @search.present? %>
My problem is that when @search is not present the whole form is not
displayed! I only want that the value is not displayed in this case!
I have an search form, for my Search model. My problem is that i only want
to display the value of the form if @search is present. I wrote this code:
<%= f.text_field :keyword, :value => @search.keyword if @search.present? %>
My problem is that when @search is not present the whole form is not
displayed! I only want that the value is not displayed in this case!
Friday, 13 September 2013
How to use Faroo search API in cocoa
How to use Faroo search API in cocoa
I never use web API and don't know what i may read about this. I read
FAROO Return Values doc, but i don't understand how i may get result-array
(or dictionary) in cocoa. Please anybody give me example or tutorial how
to use Faroo API (or other web API) in objective-c.
Thank you.
I never use web API and don't know what i may read about this. I read
FAROO Return Values doc, but i don't understand how i may get result-array
(or dictionary) in cocoa. Please anybody give me example or tutorial how
to use Faroo API (or other web API) in objective-c.
Thank you.
Not able to delete a directory with read only files in UNIX?
Not able to delete a directory with read only files in UNIX?
I am trying to delete hidden read only files from a unix directory.I
actually want to delete the directory itself but not able to. It has many
directories within it as well. I am the owner and I should have
permission.
I tried giving permission access it to my own username but not able to
delete or change permission using chmod 777, tried rmdir, rf and
everything as well. Any suggestions?
Thanks in advance.
I am trying to delete hidden read only files from a unix directory.I
actually want to delete the directory itself but not able to. It has many
directories within it as well. I am the owner and I should have
permission.
I tried giving permission access it to my own username but not able to
delete or change permission using chmod 777, tried rmdir, rf and
everything as well. Any suggestions?
Thanks in advance.
Using XML to generate row value constructors comparison?
Using XML to generate row value constructors comparison?
I am trying to generate the row value constructors like the following
example.
where
( (A = 3 and B = 8 and C = '2001-12-10' and D >= 'XCS')
or (A = 3 and B = 8 and C > '2001-12-10')
or (A = 3 and B > 8)
or (A > 3)
)
and
( (A = 9 and B = 4 and C = '2002-06-01' and D <= 'CCC')
or (A = 9 and B = 4 and C < '2002-06-01')
or (A = 9 and B < 4)
or (A < 9)
)
However, the following script doesn't generate the above code yet. How to
write the xquery?
declare @sql varchar(max);
declare @x xml = '
<Cols>
<Column>
<COLUMN_NAME>A</COLUMN_NAME>
<LQuote />
<RQuote />
<Lower>3</Lower>
<Higher>9</Higher>
</Column>
<Column>
<COLUMN_NAME>B</COLUMN_NAME>
<LQuote />
<RQuote />
<Lower>8</Lower>
<Higher>4</Higher>
</Column>
<Column>
<COLUMN_NAME>C</COLUMN_NAME>
<LQuote>''</LQuote>
<RQuote>''</RQuote>
<Lower>2001-12-10</Lower>
<Higher>2002-06-01</Higher>
</Column>
<Column>
<COLUMN_NAME>D</COLUMN_NAME>
<LQuote>''</LQuote>
<RQuote>''</RQuote>
<Lower>XCS</Lower>
<Higher>CCC</Higher>
</Column>
</Cols>';
set @sql = replace(Replace(@x.query('<sql>where
(~{
for $r in //Column
return
<sql>or ({for $c in //Column return <s>{$c/COLUMN_NAME} =
{$c/LQuote}{$c/Lower}{$c/RQuote} and </s>}~)
</sql>
})
and
(~{
for $r in //Column
return
<sql>or ({for $c in //Column return <s>{$c/COLUMN_NAME} =
{$c/LQuote}{$c/Higher}{$c/RQuote} and </s>}~)
</sql>
})
</sql>').value('.', 'nvarchar(max)'), 'and ~', ''), '~or', '')
print @sql
Current output of the code.
where
( (A = 3 and B = 8 and C = '2001-12-10' and D = 'XCS' )
or (A = 3 and B = 8 and C = '2001-12-10' and D = 'XCS' )
or (A = 3 and B = 8 and C = '2001-12-10' and D = 'XCS' )
or (A = 3 and B = 8 and C = '2001-12-10' and D = 'XCS' )
)
and
( (A = 9 and B = 4 and C = '2002-06-01' and D = 'CCC' )
or (A = 9 and B = 4 and C = '2002-06-01' and D = 'CCC' )
or (A = 9 and B = 4 and C = '2002-06-01' and D = 'CCC' )
or (A = 9 and B = 4 and C = '2002-06-01' and D = 'CCC' )
)
I am trying to generate the row value constructors like the following
example.
where
( (A = 3 and B = 8 and C = '2001-12-10' and D >= 'XCS')
or (A = 3 and B = 8 and C > '2001-12-10')
or (A = 3 and B > 8)
or (A > 3)
)
and
( (A = 9 and B = 4 and C = '2002-06-01' and D <= 'CCC')
or (A = 9 and B = 4 and C < '2002-06-01')
or (A = 9 and B < 4)
or (A < 9)
)
However, the following script doesn't generate the above code yet. How to
write the xquery?
declare @sql varchar(max);
declare @x xml = '
<Cols>
<Column>
<COLUMN_NAME>A</COLUMN_NAME>
<LQuote />
<RQuote />
<Lower>3</Lower>
<Higher>9</Higher>
</Column>
<Column>
<COLUMN_NAME>B</COLUMN_NAME>
<LQuote />
<RQuote />
<Lower>8</Lower>
<Higher>4</Higher>
</Column>
<Column>
<COLUMN_NAME>C</COLUMN_NAME>
<LQuote>''</LQuote>
<RQuote>''</RQuote>
<Lower>2001-12-10</Lower>
<Higher>2002-06-01</Higher>
</Column>
<Column>
<COLUMN_NAME>D</COLUMN_NAME>
<LQuote>''</LQuote>
<RQuote>''</RQuote>
<Lower>XCS</Lower>
<Higher>CCC</Higher>
</Column>
</Cols>';
set @sql = replace(Replace(@x.query('<sql>where
(~{
for $r in //Column
return
<sql>or ({for $c in //Column return <s>{$c/COLUMN_NAME} =
{$c/LQuote}{$c/Lower}{$c/RQuote} and </s>}~)
</sql>
})
and
(~{
for $r in //Column
return
<sql>or ({for $c in //Column return <s>{$c/COLUMN_NAME} =
{$c/LQuote}{$c/Higher}{$c/RQuote} and </s>}~)
</sql>
})
</sql>').value('.', 'nvarchar(max)'), 'and ~', ''), '~or', '')
print @sql
Current output of the code.
where
( (A = 3 and B = 8 and C = '2001-12-10' and D = 'XCS' )
or (A = 3 and B = 8 and C = '2001-12-10' and D = 'XCS' )
or (A = 3 and B = 8 and C = '2001-12-10' and D = 'XCS' )
or (A = 3 and B = 8 and C = '2001-12-10' and D = 'XCS' )
)
and
( (A = 9 and B = 4 and C = '2002-06-01' and D = 'CCC' )
or (A = 9 and B = 4 and C = '2002-06-01' and D = 'CCC' )
or (A = 9 and B = 4 and C = '2002-06-01' and D = 'CCC' )
or (A = 9 and B = 4 and C = '2002-06-01' and D = 'CCC' )
)
fill select input value dirrectly without java script
fill select input value dirrectly without java script
is it possible fill model's field by value of select input ? without using
java script cod. in tbl_purchase , i have Idtbl_bank . how can i fill in
view directly?
@model Project.Models.tbl_purchase
<select id="Idtbl_bank" class="span5">
<option>---select bank name ---</option>
@foreach (var item in ViewBag.BankNames as
List<Project.Models.tbl_bank>)
{
<option
value="@item.id">@item.namebank
</option>
}
</select>
is it possible fill model's field by value of select input ? without using
java script cod. in tbl_purchase , i have Idtbl_bank . how can i fill in
view directly?
@model Project.Models.tbl_purchase
<select id="Idtbl_bank" class="span5">
<option>---select bank name ---</option>
@foreach (var item in ViewBag.BankNames as
List<Project.Models.tbl_bank>)
{
<option
value="@item.id">@item.namebank
</option>
}
</select>
Writing a method that finds the Greatest Common Divisor between 2 integers USING RECURSION?
Writing a method that finds the Greatest Common Divisor between 2 integers
USING RECURSION?
Euclid's algorithm tells us how to compute the greatest common divisor
(GCD) of two positive integers a and b. Using Euclid's algorithm, to find
the GCD of 206 and 40 (for example), first find the remainder when 206 is
divided by 40. Then find the GCD of 40 and this remainder (which turns out
to be 6), using the same idea again. When you reach the point where the
second number is 0, the first number will be the GCD of 206 and 40 that
you were looking for, as shown below.
gcd(206, 40) = gcd(40, 6) = gcd(6, 4) = gcd(4, 2) = gcd(2, 0) = 2
Write a method called gcd. YOU MUST USE RECURSION IN THIS METHOD (calling
the method within the method). This method should use Euclid's algorithm
to return the greatest common divisor of two positive integers.
So basically I don't know how to do this without recursion.. Please help!
:( I have been stuck on this for so long.. I wrote a method, but it
doesn't use recursion and it only woks for the given 206 and 40..
USING RECURSION?
Euclid's algorithm tells us how to compute the greatest common divisor
(GCD) of two positive integers a and b. Using Euclid's algorithm, to find
the GCD of 206 and 40 (for example), first find the remainder when 206 is
divided by 40. Then find the GCD of 40 and this remainder (which turns out
to be 6), using the same idea again. When you reach the point where the
second number is 0, the first number will be the GCD of 206 and 40 that
you were looking for, as shown below.
gcd(206, 40) = gcd(40, 6) = gcd(6, 4) = gcd(4, 2) = gcd(2, 0) = 2
Write a method called gcd. YOU MUST USE RECURSION IN THIS METHOD (calling
the method within the method). This method should use Euclid's algorithm
to return the greatest common divisor of two positive integers.
So basically I don't know how to do this without recursion.. Please help!
:( I have been stuck on this for so long.. I wrote a method, but it
doesn't use recursion and it only woks for the given 206 and 40..
how to make any text in richtext box as hyperlink
how to make any text in richtext box as hyperlink
I am having text in rich text box separated with ';' I want to make every
value as hyperlink which is separated with ';'. Please Help
I am having text in rich text box separated with ';' I want to make every
value as hyperlink which is separated with ';'. Please Help
Thursday, 12 September 2013
Hide MKAnnotations when user zooms out and annotations are too close to each other
Hide MKAnnotations when user zooms out and annotations are too close to
each other
I've seen this in some apps so far that when the user zooms out then the
annotations move closer to each other and if they're too close then
they're replaced by e.g. a '+5' pin or something else.
How to do that? I think it should be done in regionDidChangeAnimated and
checking the distance on mapview (not the real distance) for each Pin to
each other.
Would that be the right approach? How to get the distance on mapview
instead of distance inside it (e.g. distance between NY and SF will always
be the same, but if user zooms out, the distance between the pins on the
map shrink)
each other
I've seen this in some apps so far that when the user zooms out then the
annotations move closer to each other and if they're too close then
they're replaced by e.g. a '+5' pin or something else.
How to do that? I think it should be done in regionDidChangeAnimated and
checking the distance on mapview (not the real distance) for each Pin to
each other.
Would that be the right approach? How to get the distance on mapview
instead of distance inside it (e.g. distance between NY and SF will always
be the same, but if user zooms out, the distance between the pins on the
map shrink)
Passing a dynamically generated variable into $_SESSION
Passing a dynamically generated variable into $_SESSION
I'm trying to use the following code to dynamically generate a list of
links to video files on a website. Instead of creating a separate page for
every video, I wanted to be able to have a template page (ex: video.php)
and have it generate the streaming content based on information passed on
to it from the previous page. Essentially, the chapter_id field will allow
me to pass that variable into MySQL and pull the URL info along with file
description, and help store any type of feedback data (such as poor
quality video, or a type of ratings system).
PHP/HTML:
while ($rows = mysql_fetch_assoc($subscriptionResult)) {
$user_id = $rows['user_id'];
$course_id = $rows['course_id'];
$sqlChapters = "SELECT * FROM `chapters` WHERE
`course_id`='".$course_id."' ORDER BY `chapter_id`";
$result = mysql_query($sqlChapters) or mysql_die($sqlChapters);
if (mysql_num_rows($result) > 0) {
while ($rows = mysql_fetch_assoc($result)) {
$chapter_id = $rows['chapter_id'];
$course_id = $rows['course_id']
$title = $rows['title'];
echo '<li><a
href="http://localhost/video.php>"',$title,'</a>,</li>';
}
}
}
What I wanted to do was maybe use the following <a
href=localhost/video.php?data_id=',$rows['chapter_id'],'>',$title,'</a>
So the goal is to pass chapter_id into $data_id.
But the concern I have is: It's not as secure as session, someone can
manually input a chapter_id and still access the video (I know I can write
additional code in the video.php to verify that the right user is
accessing it).
Is there another way to do this, maybe using javascript?
PS. I am aware that mysql_* functions have become deprecated! Thank you in
advance for the warnings!
I'm trying to use the following code to dynamically generate a list of
links to video files on a website. Instead of creating a separate page for
every video, I wanted to be able to have a template page (ex: video.php)
and have it generate the streaming content based on information passed on
to it from the previous page. Essentially, the chapter_id field will allow
me to pass that variable into MySQL and pull the URL info along with file
description, and help store any type of feedback data (such as poor
quality video, or a type of ratings system).
PHP/HTML:
while ($rows = mysql_fetch_assoc($subscriptionResult)) {
$user_id = $rows['user_id'];
$course_id = $rows['course_id'];
$sqlChapters = "SELECT * FROM `chapters` WHERE
`course_id`='".$course_id."' ORDER BY `chapter_id`";
$result = mysql_query($sqlChapters) or mysql_die($sqlChapters);
if (mysql_num_rows($result) > 0) {
while ($rows = mysql_fetch_assoc($result)) {
$chapter_id = $rows['chapter_id'];
$course_id = $rows['course_id']
$title = $rows['title'];
echo '<li><a
href="http://localhost/video.php>"',$title,'</a>,</li>';
}
}
}
What I wanted to do was maybe use the following <a
href=localhost/video.php?data_id=',$rows['chapter_id'],'>',$title,'</a>
So the goal is to pass chapter_id into $data_id.
But the concern I have is: It's not as secure as session, someone can
manually input a chapter_id and still access the video (I know I can write
additional code in the video.php to verify that the right user is
accessing it).
Is there another way to do this, maybe using javascript?
PS. I am aware that mysql_* functions have become deprecated! Thank you in
advance for the warnings!
How to change text color in a hotkey using MFC?
How to change text color in a hotkey using MFC?
The question is like this: define a new class inheritance CHotKeyCtrl, I
want to change the text color in hotkey. Using ON_WM_CTLCOLOR_REFLECT,but
the test color is not changed.the onctlcolor function cannot run.
MyHotKey.h
class CMyHotKey: public CHotKeyCtrl
{
DECLARE_DYNAMIC(CMyHotKey)
protected:
DECLARE_MESSAGE_MAP()
public:
afx_msg HBRUSH CtlColor(CDC* pDC, UINT nCtlColor);
};
MyHotKey.cpp
BEGIN_MESSAGE_MAP(CMyHotkey, CHotKeyCtrl)
ON_WM_CTLCOLOR_REFLECT()
ON_WM_ERASEBKGND()
END_MESSAGE_MAP()
HBRUSH CMyHotKey::CtlColor(CDC* pDC, UINT nCtlColor)
{
if(pDC)
{
pDC->SetTextColor(RGB(255,0,0));
pDC->SetBkMode(TRANSPARENT);
}
return (HBRUSH)GetStockObject(NULL_BRUSH);
}
Can anyone suggest what I might be doing wrong?
The question is like this: define a new class inheritance CHotKeyCtrl, I
want to change the text color in hotkey. Using ON_WM_CTLCOLOR_REFLECT,but
the test color is not changed.the onctlcolor function cannot run.
MyHotKey.h
class CMyHotKey: public CHotKeyCtrl
{
DECLARE_DYNAMIC(CMyHotKey)
protected:
DECLARE_MESSAGE_MAP()
public:
afx_msg HBRUSH CtlColor(CDC* pDC, UINT nCtlColor);
};
MyHotKey.cpp
BEGIN_MESSAGE_MAP(CMyHotkey, CHotKeyCtrl)
ON_WM_CTLCOLOR_REFLECT()
ON_WM_ERASEBKGND()
END_MESSAGE_MAP()
HBRUSH CMyHotKey::CtlColor(CDC* pDC, UINT nCtlColor)
{
if(pDC)
{
pDC->SetTextColor(RGB(255,0,0));
pDC->SetBkMode(TRANSPARENT);
}
return (HBRUSH)GetStockObject(NULL_BRUSH);
}
Can anyone suggest what I might be doing wrong?
TomEE and MySql - query don't returns any results
TomEE and MySql - query don't returns any results
I am using TomeEE + MySql and i have problem because function
createNamedQuery don't returns any results. I thought that problem is with
my entityManager but i checked in debugMode and is injected.
This is my code:
User Entity:
package pl.gsite.db.model;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
@Entity
@Table(name = "user")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "User.loginAndPassword", query = "SELECT u FROM
User u WHERE u.login = :login and u.password = :password"),
@NamedQuery(name = "User.findAll", query = "SELECT u FROM User u"),
@NamedQuery(name = "User.findById", query = "SELECT u FROM User u
WHERE u.id = :id"),
@NamedQuery(name = "User.findByLogin", query = "SELECT u FROM User u
WHERE u.login = :login"),
@NamedQuery(name = "User.findByPassword", query = "SELECT u FROM User
u WHERE u.password = :password")})
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Basic(optional = false)
@NotNull
@Column(name = "id")
private Integer id;
@Size(max = 100)
@Column(name = "login")
private String login;
@Size(max = 100)
@Column(name = "password")
private String password;
public User() {
}
public User(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id
fields are not set
if (!(object instanceof User)) {
return false;
}
User other = (User) object;
if ((this.id == null && other.id != null) || (this.id != null &&
!this.id.equals(other.id))) {
return false;
}
return true;
}
@Override
public String toString() {
return "pl.gsite.db.model.User[ id=" + id + " ]";
}
}
My ManagedBean:
package pl.gsite.bean.request;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.Stateful;
import javax.inject.Named;
import javax.enterprise.context.RequestScoped;
import javax.enterprise.context.spi.Context;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import pl.gsite.bean.session.LoggedUserBean;
import pl.gsite.db.model.User;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContextType;
import javax.persistence.Query;
@Named(value = "loginRequest")
@RequestScoped
public class LoginRequest {
@PersistenceContext(unitName = "gsitePU")
private EntityManager em;
@Inject
private LoggedUserBean loggedUserBean;
private String login;
private String password;
public LoginRequest() {
}
public String authentication() {
try {
List<User> uList = new ArrayList<User>();
TypedQuery qq = em.createNamedQuery("User.findAll", User.class);
uList = qq.getResultList(); // <-- returns empty list
TypedQuery<User> query =
em.createNamedQuery("User.loginAndPassword",
User.class).setParameter("login",
login).setParameter("password", password);
User u = query.getSingleResult(); // <-- throws an
NoResultException
this.loggedUserBean.setLoggedUser(u);
}
catch(NoResultException e) {
e.printStackTrace();
}
return "index";
}
/**
* @return the login
*/
public String getLogin() {
return login;
}
/**
* @param login the login to set
*/
public void setLogin(String login) {
this.login = login;
}
/**
* @return the password
*/
public String getPassword() {
return password;
}
/**
* @param password the password to set
*/
public void setPassword(String password) {
this.password = password;
}
}
persistance.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="gsitePU" transaction-type="JTA">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<jta-data-source>gsite_mysql</jta-data-source>
<properties>
<property name="openjpa.jdbc.SynchronizeMappings"
value="buildSchema(foreignKeys=true)"/>
</properties>
</persistence-unit>
</persistence>
I am using TomeEE + MySql and i have problem because function
createNamedQuery don't returns any results. I thought that problem is with
my entityManager but i checked in debugMode and is injected.
This is my code:
User Entity:
package pl.gsite.db.model;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
@Entity
@Table(name = "user")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "User.loginAndPassword", query = "SELECT u FROM
User u WHERE u.login = :login and u.password = :password"),
@NamedQuery(name = "User.findAll", query = "SELECT u FROM User u"),
@NamedQuery(name = "User.findById", query = "SELECT u FROM User u
WHERE u.id = :id"),
@NamedQuery(name = "User.findByLogin", query = "SELECT u FROM User u
WHERE u.login = :login"),
@NamedQuery(name = "User.findByPassword", query = "SELECT u FROM User
u WHERE u.password = :password")})
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Basic(optional = false)
@NotNull
@Column(name = "id")
private Integer id;
@Size(max = 100)
@Column(name = "login")
private String login;
@Size(max = 100)
@Column(name = "password")
private String password;
public User() {
}
public User(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id
fields are not set
if (!(object instanceof User)) {
return false;
}
User other = (User) object;
if ((this.id == null && other.id != null) || (this.id != null &&
!this.id.equals(other.id))) {
return false;
}
return true;
}
@Override
public String toString() {
return "pl.gsite.db.model.User[ id=" + id + " ]";
}
}
My ManagedBean:
package pl.gsite.bean.request;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.Stateful;
import javax.inject.Named;
import javax.enterprise.context.RequestScoped;
import javax.enterprise.context.spi.Context;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import pl.gsite.bean.session.LoggedUserBean;
import pl.gsite.db.model.User;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContextType;
import javax.persistence.Query;
@Named(value = "loginRequest")
@RequestScoped
public class LoginRequest {
@PersistenceContext(unitName = "gsitePU")
private EntityManager em;
@Inject
private LoggedUserBean loggedUserBean;
private String login;
private String password;
public LoginRequest() {
}
public String authentication() {
try {
List<User> uList = new ArrayList<User>();
TypedQuery qq = em.createNamedQuery("User.findAll", User.class);
uList = qq.getResultList(); // <-- returns empty list
TypedQuery<User> query =
em.createNamedQuery("User.loginAndPassword",
User.class).setParameter("login",
login).setParameter("password", password);
User u = query.getSingleResult(); // <-- throws an
NoResultException
this.loggedUserBean.setLoggedUser(u);
}
catch(NoResultException e) {
e.printStackTrace();
}
return "index";
}
/**
* @return the login
*/
public String getLogin() {
return login;
}
/**
* @param login the login to set
*/
public void setLogin(String login) {
this.login = login;
}
/**
* @return the password
*/
public String getPassword() {
return password;
}
/**
* @param password the password to set
*/
public void setPassword(String password) {
this.password = password;
}
}
persistance.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="gsitePU" transaction-type="JTA">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<jta-data-source>gsite_mysql</jta-data-source>
<properties>
<property name="openjpa.jdbc.SynchronizeMappings"
value="buildSchema(foreignKeys=true)"/>
</properties>
</persistence-unit>
</persistence>
Internal structure of jagged array in .NET
Internal structure of jagged array in .NET
I created simple jagged array:
int[][] a = new int[2][];
for (int i = 0; i < 2; i++)
{
a[i] = new int[3];
for (int j = 0; j < 3; j++)
a[i][j] = i * 3 + j;
}
After that I started debugging my application and looked to this array
sturcture in memory:
0x03022478 0 // SyncBlockIndex (a)
0x0302247C 0x61B8D5BC // TypeHandle (a)
0x03022480 2 // a.Length
0x03022484 0x617A4C8A // ???
0x03022488 0x03022494 // a[0]
0x0302248C 0x030224AC // a[1]
0x03022490 0 // SyncBlockIndex (a[0])
0x03022494 0x61B9C448 // TypeHandle (a[0])
0x03022498 3 // a[0].Length
0x0302249C 0 // a[0][0]
0x030224A0 1 // a[0][1]
0x030224A4 2 // a[0][2]
0x030224A8 0 // SyncBlockIndex (a[1])
0x030224AC 0x61B9C448 // TypeHandle (a[1])
0x030224B0 3 // a[1].Length
0x030224B4 3 // a[1][0]
0x030224B8 4 // a[1][1]
0x030224BC 5 // a[1][2]
I understand almost all the data: SyncBlockIndexes, TypeHandles, Lengths,
Elements. But I can't understand only one line:
0x03022484 0x617A4C8A // ???
What it is?
I created simple jagged array:
int[][] a = new int[2][];
for (int i = 0; i < 2; i++)
{
a[i] = new int[3];
for (int j = 0; j < 3; j++)
a[i][j] = i * 3 + j;
}
After that I started debugging my application and looked to this array
sturcture in memory:
0x03022478 0 // SyncBlockIndex (a)
0x0302247C 0x61B8D5BC // TypeHandle (a)
0x03022480 2 // a.Length
0x03022484 0x617A4C8A // ???
0x03022488 0x03022494 // a[0]
0x0302248C 0x030224AC // a[1]
0x03022490 0 // SyncBlockIndex (a[0])
0x03022494 0x61B9C448 // TypeHandle (a[0])
0x03022498 3 // a[0].Length
0x0302249C 0 // a[0][0]
0x030224A0 1 // a[0][1]
0x030224A4 2 // a[0][2]
0x030224A8 0 // SyncBlockIndex (a[1])
0x030224AC 0x61B9C448 // TypeHandle (a[1])
0x030224B0 3 // a[1].Length
0x030224B4 3 // a[1][0]
0x030224B8 4 // a[1][1]
0x030224BC 5 // a[1][2]
I understand almost all the data: SyncBlockIndexes, TypeHandles, Lengths,
Elements. But I can't understand only one line:
0x03022484 0x617A4C8A // ???
What it is?
numpy array of strings indexing behavior
numpy array of strings indexing behavior
I have an array of strings
>>> lines
array(['RL5\\Stark_223', 'RL5\\Stark_223', 'RL5\\Stark_223', ...,
'RL5\\Stark_238', 'RL5\\Stark_238', 'RL5\\Stark_238'],
dtype='|S27')
Why can I index into a string for the first array element
>>> lines[0][0:3]
'RL5'
But not into the same place for all array elements
>>> lines[:][0:3]
array(['RL5\\Stark_223', 'RL5\\Stark_223', 'RL5\\Stark_223'],
dtype='|S27')
Can anyone suggest a method to get the following result:
array(['RL5', 'RL5', 'RL5', ...'RL5', 'RL5')
I have an array of strings
>>> lines
array(['RL5\\Stark_223', 'RL5\\Stark_223', 'RL5\\Stark_223', ...,
'RL5\\Stark_238', 'RL5\\Stark_238', 'RL5\\Stark_238'],
dtype='|S27')
Why can I index into a string for the first array element
>>> lines[0][0:3]
'RL5'
But not into the same place for all array elements
>>> lines[:][0:3]
array(['RL5\\Stark_223', 'RL5\\Stark_223', 'RL5\\Stark_223'],
dtype='|S27')
Can anyone suggest a method to get the following result:
array(['RL5', 'RL5', 'RL5', ...'RL5', 'RL5')
Dojo Query by ID defaulting to getElementById
Dojo Query by ID defaulting to getElementById
Looking through the code in Dojo's library for dojo/query, it looks like
they default to use document.getElementById if the selector passed in is
an ID selector.
For example, if I do:
query("#myId")
This will behind the scenes run:
document.getElementById("myId")
This is fine for querying nodes in the window document, but what if you
are building nodes not yet put in the document? If I am constructing a
node in memory to put in the DOM later and I need to query on that node by
ID, I can't do it. Because this node isn't in the document yet.
I understand that this is how jQuery does it, too, but jQuery is different
because the approach for querying by an ID or a different selector (class,
attribute, etc.) is the same regardless. For example:
$("#myId")
$(".myClass")
$("div[align=center]")
The approach is the same. So, defaulting to document.getElementById in
this instance is fine to me.
With Dojo, its pretty misleading in light of the fact that Dojo offers a
separate function that serves as an alias to getElementById (dom.byId). If
I wanted ID querying against the actual document, I'd use that. If I'm
using dojo/query by a selector, then I want to be able to query the
document or a contextual node.
Dojo uses the lite.js selector engine in situations where a viable native
selector engine is available. The beginning of the file has a "fast path"
block that actually does this default to dom.byId. If I comment out this
block, the engine reverts to use a querySelectorAll, which in turn fixes
this issue.
Can anyone explain the reasoning for Dojo doing this? Or if there is a
viable workaround that doesn't require me to comment out Dojo's code? One
approach I've seen that works is the use of data-attributes in place of
IDs, which fake out the engine but that just seems lame.
EDIT:
Note: You can pass a contextual node to dojo/query when querying, but in
Dojo even if you create a node outside the DOM using dom-construct, the
ownerDocument of that node is still the window.document. In other words:
var node = domConstruct.toDom('<div><p><span
id="myId">Content</span></p></div>');
var doc = node.ownerDocument;
will result in 'doc' being the window.document. So, doing something like:
doc.getElementById("myId") will fail. As will this:
var results = query("#myId", node);
Because Dojo's code looks for the ownerDocument of 'node', which again is
the window.document
In the above,
Looking through the code in Dojo's library for dojo/query, it looks like
they default to use document.getElementById if the selector passed in is
an ID selector.
For example, if I do:
query("#myId")
This will behind the scenes run:
document.getElementById("myId")
This is fine for querying nodes in the window document, but what if you
are building nodes not yet put in the document? If I am constructing a
node in memory to put in the DOM later and I need to query on that node by
ID, I can't do it. Because this node isn't in the document yet.
I understand that this is how jQuery does it, too, but jQuery is different
because the approach for querying by an ID or a different selector (class,
attribute, etc.) is the same regardless. For example:
$("#myId")
$(".myClass")
$("div[align=center]")
The approach is the same. So, defaulting to document.getElementById in
this instance is fine to me.
With Dojo, its pretty misleading in light of the fact that Dojo offers a
separate function that serves as an alias to getElementById (dom.byId). If
I wanted ID querying against the actual document, I'd use that. If I'm
using dojo/query by a selector, then I want to be able to query the
document or a contextual node.
Dojo uses the lite.js selector engine in situations where a viable native
selector engine is available. The beginning of the file has a "fast path"
block that actually does this default to dom.byId. If I comment out this
block, the engine reverts to use a querySelectorAll, which in turn fixes
this issue.
Can anyone explain the reasoning for Dojo doing this? Or if there is a
viable workaround that doesn't require me to comment out Dojo's code? One
approach I've seen that works is the use of data-attributes in place of
IDs, which fake out the engine but that just seems lame.
EDIT:
Note: You can pass a contextual node to dojo/query when querying, but in
Dojo even if you create a node outside the DOM using dom-construct, the
ownerDocument of that node is still the window.document. In other words:
var node = domConstruct.toDom('<div><p><span
id="myId">Content</span></p></div>');
var doc = node.ownerDocument;
will result in 'doc' being the window.document. So, doing something like:
doc.getElementById("myId") will fail. As will this:
var results = query("#myId", node);
Because Dojo's code looks for the ownerDocument of 'node', which again is
the window.document
In the above,
Python re.search from text file
Python re.search from text file
Hi guys I have problem with re.search from text matching text names and
print them to new file as output xml.
My python code looks like
/usr/bin/env python import re
output = open('epg.xml','w') n = 0 print >> output, ''+'\t' print >>
output, ''
with open('epg_slo_utf_xml.txt','r') as txt: for line in txt: if
re.search('Program', line) !=None: n = n + 1 e =''+line+''
if re.search('Start', line) !=None:
n = n + 1
f ='<start>'+line+'</start>'
if re.search('duration', line) !=None:
n = n + 1
g ='<duration>'+line+'<duration>'
wo = e + f + g
print >> output, wo
print >> output , '`
And my output will be like xml :
"{ Program 9 Start 2013-09-12 06:45:00 Program 3
Start 2013-09-12 07:10:00 }
But problem is with two more tags ( and ), what i get when i run script is
Traceback (most recent call last): File "./epg_transform.py", line 25, in
<module> wo = e + f + g NameError: name 'g' is not defined
Example of my text file is : `Program 6
Start 2013-09-12 06:40:00 Duration 00:50:00 Title Vihar
Program 9
Start 2013-09-12 06:45:00 Duration 00:29:00 Title TV prodaja
Program 7
Program 6
Program 13
Start 2013-09-12 06:20:00
Duration 00:50:00
Title Kursadije `
I don't know is there problem with re.search where he don't find program +
all other (start, duration, title). Can you help me with this problem? BR!
Hi guys I have problem with re.search from text matching text names and
print them to new file as output xml.
My python code looks like
/usr/bin/env python import re
output = open('epg.xml','w') n = 0 print >> output, ''+'\t' print >>
output, ''
with open('epg_slo_utf_xml.txt','r') as txt: for line in txt: if
re.search('Program', line) !=None: n = n + 1 e =''+line+''
if re.search('Start', line) !=None:
n = n + 1
f ='<start>'+line+'</start>'
if re.search('duration', line) !=None:
n = n + 1
g ='<duration>'+line+'<duration>'
wo = e + f + g
print >> output, wo
print >> output , '`
And my output will be like xml :
"{ Program 9 Start 2013-09-12 06:45:00 Program 3
Start 2013-09-12 07:10:00 }
But problem is with two more tags ( and ), what i get when i run script is
Traceback (most recent call last): File "./epg_transform.py", line 25, in
<module> wo = e + f + g NameError: name 'g' is not defined
Example of my text file is : `Program 6
Start 2013-09-12 06:40:00 Duration 00:50:00 Title Vihar
Program 9
Start 2013-09-12 06:45:00 Duration 00:29:00 Title TV prodaja
Program 7
Program 6
Program 13
Start 2013-09-12 06:20:00
Duration 00:50:00
Title Kursadije `
I don't know is there problem with re.search where he don't find program +
all other (start, duration, title). Can you help me with this problem? BR!
Wednesday, 11 September 2013
why my code is so slow?
why my code is so slow?
i runing this code on android after load a cursor with the query i pass to
the adapter, but my date is in long in milliseconds format so a need to
format properly before load the adapter! problem is this code is taking 14
seconds to pass a 50 items load, the problem get worst if i call it inside
the adapter getView cause get slow when i scrool, if i take this function
out the program runs smoothly
this is call inside my listfragment
private String dateFormatPatternEdited(long timeMS) {
android.text.format.DateFormat df = new android.text.format.DateFormat();
final Calendar eDate = Calendar.getInstance();
Calendar sDate = Calendar.getInstance();
sDate.setTimeInMillis(timeMS);
long daysBetween = 0;
while (sDate.before(eDate)) {
sDate.add(Calendar.DAY_OF_MONTH, 1);
daysBetween++;
}
String mDateFormatPattern =
FuelTrackerApplication.dateFormat.format(timeMS);
if (daysBetween < 2){
mDateFormatPattern =
FuelTrackerApplication.timeFormat.format(timeMS);
} else if(daysBetween < 365){
mDateFormatPattern =
df.format(FuelTrackerApplication.dateFormatPattern,timeMS).toString();
}
return mDateFormatPattern;
}
and this is were i initialize the date formats i gonna use its called
inside onCreate in FuelTrackerApplication i dont think theres nothing
wrong with this
public void initializeDateFormat() {
android.text.format.DateFormat df = new android.text.format.DateFormat();
dateFormatPattern = "MMM dd";
if (android.os.Build.VERSION.SDK_INT >= 18){
dateFormatPattern = df.getBestDateTimePattern(Locale.getDefault(),
dateFormatPattern);
}
dateFormat = df.getMediumDateFormat(getApplicationContext());
timeFormat = df.getTimeFormat(getApplicationContext());
dateFormat2 = df.getLongDateFormat(getApplicationContext());
}
i runing this code on android after load a cursor with the query i pass to
the adapter, but my date is in long in milliseconds format so a need to
format properly before load the adapter! problem is this code is taking 14
seconds to pass a 50 items load, the problem get worst if i call it inside
the adapter getView cause get slow when i scrool, if i take this function
out the program runs smoothly
this is call inside my listfragment
private String dateFormatPatternEdited(long timeMS) {
android.text.format.DateFormat df = new android.text.format.DateFormat();
final Calendar eDate = Calendar.getInstance();
Calendar sDate = Calendar.getInstance();
sDate.setTimeInMillis(timeMS);
long daysBetween = 0;
while (sDate.before(eDate)) {
sDate.add(Calendar.DAY_OF_MONTH, 1);
daysBetween++;
}
String mDateFormatPattern =
FuelTrackerApplication.dateFormat.format(timeMS);
if (daysBetween < 2){
mDateFormatPattern =
FuelTrackerApplication.timeFormat.format(timeMS);
} else if(daysBetween < 365){
mDateFormatPattern =
df.format(FuelTrackerApplication.dateFormatPattern,timeMS).toString();
}
return mDateFormatPattern;
}
and this is were i initialize the date formats i gonna use its called
inside onCreate in FuelTrackerApplication i dont think theres nothing
wrong with this
public void initializeDateFormat() {
android.text.format.DateFormat df = new android.text.format.DateFormat();
dateFormatPattern = "MMM dd";
if (android.os.Build.VERSION.SDK_INT >= 18){
dateFormatPattern = df.getBestDateTimePattern(Locale.getDefault(),
dateFormatPattern);
}
dateFormat = df.getMediumDateFormat(getApplicationContext());
timeFormat = df.getTimeFormat(getApplicationContext());
dateFormat2 = df.getLongDateFormat(getApplicationContext());
}
Malloc with a structure containing variably sized objects
Malloc with a structure containing variably sized objects
I'm trying to create a structure which contains information from each line
in a file, so the size of the structure is dependent on the length of the
file. C doesn't like me doing,
int makeStruct(int x){
typedef struct
{
int a[x], b[x];
char c[x], d[x];
char string[100][x];
} agentInfo;
return 0;
}
I know I have to Malloc, but I'm not sure what. Do I have to Malloc the
structure and the arrays inside of it? I don't know how I'd Malloc the
entire struct as I won't know how big it will be until I know x, so I
can't use size-of? Any help appreciated.
I'm trying to create a structure which contains information from each line
in a file, so the size of the structure is dependent on the length of the
file. C doesn't like me doing,
int makeStruct(int x){
typedef struct
{
int a[x], b[x];
char c[x], d[x];
char string[100][x];
} agentInfo;
return 0;
}
I know I have to Malloc, but I'm not sure what. Do I have to Malloc the
structure and the arrays inside of it? I don't know how I'd Malloc the
entire struct as I won't know how big it will be until I know x, so I
can't use size-of? Any help appreciated.
Remove slashes from string using RegEx in JavaScript
Remove slashes from string using RegEx in JavaScript
I am trying to remove all special characters except punctuation from a
customer complaint textarea using this code:
var tmp = complaint;
complaint = new RegExp(tmp.replace(/[^a-zA-Z,.!?\d\s:]/gi, ''));
but it keeps placing "/" in front, and in back of the string after
sanitizing.
Example:
Hi, I h@ve a% probl&em wit#h (one) of your products.
Comes out like this
/Hi, I have a problem with one of your products./
I want
Hi, I have a problem with one of your products.
Thanks in advance for any help given.
I am trying to remove all special characters except punctuation from a
customer complaint textarea using this code:
var tmp = complaint;
complaint = new RegExp(tmp.replace(/[^a-zA-Z,.!?\d\s:]/gi, ''));
but it keeps placing "/" in front, and in back of the string after
sanitizing.
Example:
Hi, I h@ve a% probl&em wit#h (one) of your products.
Comes out like this
/Hi, I have a problem with one of your products./
I want
Hi, I have a problem with one of your products.
Thanks in advance for any help given.
Fresnel ellipsoid in matlab
Fresnel ellipsoid in matlab
IN CONSIDERING two remote sites. how to generate a profile of a radio link
Matlab (Fresnel ellipsoid)? then I have the source code?
BR.
IN CONSIDERING two remote sites. how to generate a profile of a radio link
Matlab (Fresnel ellipsoid)? then I have the source code?
BR.
Set PrimeFace Datatable Column Width
Set PrimeFace Datatable Column Width
I am trying to set the column widths of my data table. I have looked at
this question for an answer PrimeFaces 3.0 - How to set width of a
<p:column> in a <p:dataTable>.
I am however trying to do something a little bit different. I only want
the column to be as wide as the widest element it it is displaying. Most
of my data is text.
So for example, it should not look like this
-----------------------------
| This is some text |
-----------------------------
It should look like this
---------------------
| This is some text |
---------------------
I am trying to set the column widths of my data table. I have looked at
this question for an answer PrimeFaces 3.0 - How to set width of a
<p:column> in a <p:dataTable>.
I am however trying to do something a little bit different. I only want
the column to be as wide as the widest element it it is displaying. Most
of my data is text.
So for example, it should not look like this
-----------------------------
| This is some text |
-----------------------------
It should look like this
---------------------
| This is some text |
---------------------
Is there a way to use g++ compiler in windows better than code::blocks
Is there a way to use g++ compiler in windows better than code::blocks
is there a way to use g++ compiler in Windows? I would like to use the g++
compiler... Or is there any other way to include the STL in the source
code...In Turbo C++ and the rest we cannot even inlcude
is there a way to use g++ compiler in Windows? I would like to use the g++
compiler... Or is there any other way to include the STL in the source
code...In Turbo C++ and the rest we cannot even inlcude
Mule on Amazon Cloud
Mule on Amazon Cloud
I installed Mule Community Server on AWS cloud and it is functioning
properly. When I use http end point and invoke Mule services from browser
on my Amazon EC2 machine they work. When I access them from outside, the
request timeout. The end points are not bound to local host but mapped to
0.0.0.0:8081. I have checked all firewall settings using amaozon security
group and set permission for all. Yet it doesnt work. I am able to access
the Windows IIS http server on the same machine but not mule on port 8081.
Any clues would help.
I installed Mule Community Server on AWS cloud and it is functioning
properly. When I use http end point and invoke Mule services from browser
on my Amazon EC2 machine they work. When I access them from outside, the
request timeout. The end points are not bound to local host but mapped to
0.0.0.0:8081. I have checked all firewall settings using amaozon security
group and set permission for all. Yet it doesnt work. I am able to access
the Windows IIS http server on the same machine but not mule on port 8081.
Any clues would help.
How to create a .dat file in xcode if even possible ?
How to create a .dat file in xcode if even possible ?
I'm doing some augmented reality with the vuforia SDK. So far no probs,
everything works fine for me , but there is this strange .dat file that is
used to for augmented reality to show on what the 3D models etc. are
presented.
When I open this file win-zip there are just config.feat , config.info,
config.src,"name of the picture".kpts and a .png.
Can someone explain me what are all these files where are they from which
language . And if someone please say how to make one of these .dat files
that would be grate !!
Thanks for help and fast answer !!
I'm doing some augmented reality with the vuforia SDK. So far no probs,
everything works fine for me , but there is this strange .dat file that is
used to for augmented reality to show on what the 3D models etc. are
presented.
When I open this file win-zip there are just config.feat , config.info,
config.src,"name of the picture".kpts and a .png.
Can someone explain me what are all these files where are they from which
language . And if someone please say how to make one of these .dat files
that would be grate !!
Thanks for help and fast answer !!
Tuesday, 10 September 2013
Trying to fit carouFredSel in a variable-width container
Trying to fit carouFredSel in a variable-width container
I am trying to create a site using the Responsive Grid System. The width
of the columns depends on the width of the browser window. Within these
columns, I'm putting a carouFredSel slideshow. The intent is to have an
image that fills the width of the column, and use carouFredSel to
crossfade between images.
The problem is that my images aren't showing up at the right size; the
left and right edges are getting clipped off. When I use Chrome to
inspect, it reports that my main column (.span_5_of_10) is 613px wide, as
it should be, and that carouFredSel's wrapper div is the same size, but
the posterCarousel div is 661px wide. I can't figure out why.
I can set the width of the images in the CSS to 661px and that fixes
everything, but then my design won't be responsive. How can I get
carouFredSel to fit in a variable-width container?
Here's my HTML:
<div class="col span_5_of_10">
<div class="posterCarousel">
<img src="img/The-World-Needs-Heroes---Superman.png">
<img src="img/The-World-Needs-Heroes---Knight.png">
<img src="img/The-World-Needs-Heroes---Swashbuckler.png">
</div>
</div>
JavaScript at the bottom of the document:
<script type="text/javascript">
$(document).ready(function() {
/* CarouFredSel: a circular, responsive jQuery carousel.
Configuration created by the "Configuration Robot"
at caroufredsel.dev7studios.com
*/
$(".posterCarousel").carouFredSel({
width: "100%",
items: {
width: "100%"
},
scroll: {
fx: "crossfade",
pauseonhover: true
},
auto: 3000
});
});
</script>
And the CSS controlling my images:
.posterCarousel img {
width: 100%;
z-index: 0;
position: relative;
margin: 0;
}
I am trying to create a site using the Responsive Grid System. The width
of the columns depends on the width of the browser window. Within these
columns, I'm putting a carouFredSel slideshow. The intent is to have an
image that fills the width of the column, and use carouFredSel to
crossfade between images.
The problem is that my images aren't showing up at the right size; the
left and right edges are getting clipped off. When I use Chrome to
inspect, it reports that my main column (.span_5_of_10) is 613px wide, as
it should be, and that carouFredSel's wrapper div is the same size, but
the posterCarousel div is 661px wide. I can't figure out why.
I can set the width of the images in the CSS to 661px and that fixes
everything, but then my design won't be responsive. How can I get
carouFredSel to fit in a variable-width container?
Here's my HTML:
<div class="col span_5_of_10">
<div class="posterCarousel">
<img src="img/The-World-Needs-Heroes---Superman.png">
<img src="img/The-World-Needs-Heroes---Knight.png">
<img src="img/The-World-Needs-Heroes---Swashbuckler.png">
</div>
</div>
JavaScript at the bottom of the document:
<script type="text/javascript">
$(document).ready(function() {
/* CarouFredSel: a circular, responsive jQuery carousel.
Configuration created by the "Configuration Robot"
at caroufredsel.dev7studios.com
*/
$(".posterCarousel").carouFredSel({
width: "100%",
items: {
width: "100%"
},
scroll: {
fx: "crossfade",
pauseonhover: true
},
auto: 3000
});
});
</script>
And the CSS controlling my images:
.posterCarousel img {
width: 100%;
z-index: 0;
position: relative;
margin: 0;
}
How to serialize all li#id within an ul with jquery.serialize()?
How to serialize all li#id within an ul with jquery.serialize()?
First of all, I am not using the jQuery-UI, only latest jQuery!
I have following list:
<ul id="audio_list">
<li id="trackid_1"></li>
<li id="trackid_5"></li>
<li id="trackid_2"></li>
<li id="trackid_4"></li>
<li id="trackid_3"></li>
</ul>
Now I'd like to serialize this list and save it as an array in a variable,
like:
var myaudiotracks = jQuery('#audio_list').serialize();
All I get is an empty string, of course, because I am missing something or
it is not possible to serialize lists with jQuery only.
What I am trying to accomplish is to send this variable as an array to a
PHP script, the result when posting the variable should be:
trackid[] 1
trackid[] 5
trackid[] 2
trackid[] 4
trackid[] 3
Any ideas how I can get to this result?
First of all, I am not using the jQuery-UI, only latest jQuery!
I have following list:
<ul id="audio_list">
<li id="trackid_1"></li>
<li id="trackid_5"></li>
<li id="trackid_2"></li>
<li id="trackid_4"></li>
<li id="trackid_3"></li>
</ul>
Now I'd like to serialize this list and save it as an array in a variable,
like:
var myaudiotracks = jQuery('#audio_list').serialize();
All I get is an empty string, of course, because I am missing something or
it is not possible to serialize lists with jQuery only.
What I am trying to accomplish is to send this variable as an array to a
PHP script, the result when posting the variable should be:
trackid[] 1
trackid[] 5
trackid[] 2
trackid[] 4
trackid[] 3
Any ideas how I can get to this result?
Responsive sliders like on Humble Bundle?
Responsive sliders like on Humble Bundle?
I'm looking for something like sliders used on Humble Bundle to choose the
amount of money you distribute to each charity.
Any ideas?
I'm looking for something like sliders used on Humble Bundle to choose the
amount of money you distribute to each charity.
Any ideas?
hibernate. many-to-many. bidirectional association. What does mean the owner?
hibernate. many-to-many. bidirectional association. What does mean the owner?
I know that in many-to-many bidirectional association are owner and
dependent entity. What do I know about owner and dependent for writing my
application? What differencies are between them?
I know that in many-to-many bidirectional association are owner and
dependent entity. What do I know about owner and dependent for writing my
application? What differencies are between them?
SVNKit Checkout Slow on linux
SVNKit Checkout Slow on linux
From a webapplication (ran in Tomcat/Jetty) I do a svn checkout to the
localhost with SVNKit as follows:
final SvnOperationFactory svnOperationFactory = new
SvnOperationFactory();
try {
svnOperationFactory.setAuthenticationManager(authManager);
final SvnCheckout checkout = svnOperationFactory.createCheckout();
//options
checkout.setSingleTarget(SvnTarget.fromFile(outputDir));
checkout.setSource(SvnTarget.fromURL(sourceURL));
checkout.setRevision(SVNRevision.HEAD);
//run
checkout.run();
} finally {
svnOperationFactory.dispose();
}
When I run this code on my Windows 7 laptop the directory (about 100 kb)
is checked out in a few seconds. When I run this on a Red Hat Linux server
(same Tomcat, same Java version) this takes more than 5 minutes (gets
longer every checkout). During the checkout the java process consumes 100%
cpu.
My question is why is this working so slow on the Linux server and how can
I debug this?
From a webapplication (ran in Tomcat/Jetty) I do a svn checkout to the
localhost with SVNKit as follows:
final SvnOperationFactory svnOperationFactory = new
SvnOperationFactory();
try {
svnOperationFactory.setAuthenticationManager(authManager);
final SvnCheckout checkout = svnOperationFactory.createCheckout();
//options
checkout.setSingleTarget(SvnTarget.fromFile(outputDir));
checkout.setSource(SvnTarget.fromURL(sourceURL));
checkout.setRevision(SVNRevision.HEAD);
//run
checkout.run();
} finally {
svnOperationFactory.dispose();
}
When I run this code on my Windows 7 laptop the directory (about 100 kb)
is checked out in a few seconds. When I run this on a Red Hat Linux server
(same Tomcat, same Java version) this takes more than 5 minutes (gets
longer every checkout). During the checkout the java process consumes 100%
cpu.
My question is why is this working so slow on the Linux server and how can
I debug this?
Initialise Language Selection
Initialise Language Selection
I'm trying to get a simple language initialisation working, below are the
clauses. Have a missed any possible situations where a user wouldn't have
either a default language set or a selected language set?!
If lang is POSTed the assign it to the $_SESSION
If lang is not POSTed the see if $_SESSION doesn't exist and assign default
Otherwise do nothing as $_SESSION is already set with selected language
and populated.
if(isset($_POST['lang'])) { $_SESSION['lang'] = $_POST['lang']; } else {
if(!isset($_SESSION['lang'])) { $_SESSION['lang'] = 'en_uk'; } }
I'm trying to get a simple language initialisation working, below are the
clauses. Have a missed any possible situations where a user wouldn't have
either a default language set or a selected language set?!
If lang is POSTed the assign it to the $_SESSION
If lang is not POSTed the see if $_SESSION doesn't exist and assign default
Otherwise do nothing as $_SESSION is already set with selected language
and populated.
if(isset($_POST['lang'])) { $_SESSION['lang'] = $_POST['lang']; } else {
if(!isset($_SESSION['lang'])) { $_SESSION['lang'] = 'en_uk'; } }
telerik textbox selectAll() property does not work
telerik textbox selectAll() property does not work
I want to select textbox's text when it got focus. I have found many
links/ answers about "selectAll()" property and it does work. but the
problem is that I have three inputs (a textbox, then combo box, then
textbox) and i want to set selectAll() on 3rd input (means on 2nd textbox)
when i come to that textbox through combobox, it does work but if i make
comboBox disabled, it doesnot work, it just focuses there but does not
select whole text.
I don't know why its happening? Any kind of help will be appreciated.
I want to select textbox's text when it got focus. I have found many
links/ answers about "selectAll()" property and it does work. but the
problem is that I have three inputs (a textbox, then combo box, then
textbox) and i want to set selectAll() on 3rd input (means on 2nd textbox)
when i come to that textbox through combobox, it does work but if i make
comboBox disabled, it doesnot work, it just focuses there but does not
select whole text.
I don't know why its happening? Any kind of help will be appreciated.
Monday, 9 September 2013
Concatenating Two Different List in C#
Concatenating Two Different List in C#
For example I have this two lists:
List<string> firstName = new List<string>();
List<string> lastName = new List<string>();
How can I concatenate firstName[0] and lastName[0], firstName[1] and
lastName[1], etc and put it in a new list?
For example I have this two lists:
List<string> firstName = new List<string>();
List<string> lastName = new List<string>();
How can I concatenate firstName[0] and lastName[0], firstName[1] and
lastName[1], etc and put it in a new list?
Hadoop RawLocalFileSystem and getPos
Hadoop RawLocalFileSystem and getPos
I've found that the getPos in the RawLocalFileSystem's input stream can
throw a null pointer exception if its underlying stream is closed.
I discovered this when playing with a custom record reader.
to patch it, I simply check if a call to "stream.available()" throws an
exception, and if so, I return 0 in the getPos() function.
The existing getPos() implementation is found here:
https://svn.apache.org/repos/asf/hadoop/common/branches/branch-0.20/src/examples/org/apache/hadoop/examples/MultiFileWordCount.java
What should be the correct behaviour of getPos() in the RecordReader?
I've found that the getPos in the RawLocalFileSystem's input stream can
throw a null pointer exception if its underlying stream is closed.
I discovered this when playing with a custom record reader.
to patch it, I simply check if a call to "stream.available()" throws an
exception, and if so, I return 0 in the getPos() function.
The existing getPos() implementation is found here:
https://svn.apache.org/repos/asf/hadoop/common/branches/branch-0.20/src/examples/org/apache/hadoop/examples/MultiFileWordCount.java
What should be the correct behaviour of getPos() in the RecordReader?
Use Where iEnumerable extension with reflection
Use Where iEnumerable extension with reflection
I have a list of items on a datagrid, the items type are only known at
runtime, so my datagrid is filled by an iEnumerable< object >, and I need
to find a certain register on this datagrid by using the Where Extension
method of iEnumerable< T >. But when the Where extension is invoked
through reflection, it throws an InvalidCastException
My code :
var items = dataGrid.ItemsSource;
var method = this.GetType().GetMethod("GenerateExpressionEqualsValue");
var genericMethod = method.MakeGenericMethod(registroAtual);
//resultExpression is set to (param_0 => param_0.fieldOftable ==
textloc);
var resultExpression = genericMethod.Invoke(this, new object[] {
regSel, textloc });
var whereMethodFound = typeof(System.Linq.Enumerable)
.GetMethods(BindingFlags.Static | BindingFlags.Public)
.Where(mi => mi.Name == "Where")[0];
var whereMethod = whereMethodFound.MakeGenericMethod(registroAtual);
//Exception is thrown here saying i cannot convert from
'System.Linq.Enumerable+<CastIterator>d__b1`1[System.Object]' To
'System.Collections.Generic.IEnumerable`1[Model.TableX]'.
var ret = whereMethod.Invoke(items, new object[] {items, resultExpression });
I have a list of items on a datagrid, the items type are only known at
runtime, so my datagrid is filled by an iEnumerable< object >, and I need
to find a certain register on this datagrid by using the Where Extension
method of iEnumerable< T >. But when the Where extension is invoked
through reflection, it throws an InvalidCastException
My code :
var items = dataGrid.ItemsSource;
var method = this.GetType().GetMethod("GenerateExpressionEqualsValue");
var genericMethod = method.MakeGenericMethod(registroAtual);
//resultExpression is set to (param_0 => param_0.fieldOftable ==
textloc);
var resultExpression = genericMethod.Invoke(this, new object[] {
regSel, textloc });
var whereMethodFound = typeof(System.Linq.Enumerable)
.GetMethods(BindingFlags.Static | BindingFlags.Public)
.Where(mi => mi.Name == "Where")[0];
var whereMethod = whereMethodFound.MakeGenericMethod(registroAtual);
//Exception is thrown here saying i cannot convert from
'System.Linq.Enumerable+<CastIterator>d__b1`1[System.Object]' To
'System.Collections.Generic.IEnumerable`1[Model.TableX]'.
var ret = whereMethod.Invoke(items, new object[] {items, resultExpression });
Python Socket, No Data Recieved after Initial Transmission
Python Socket, No Data Recieved after Initial Transmission
I'm looking to make a very basic remote desktop application. Right now I
am able to capture the screen data using the python win32 API, and I am
able to send one image over the socket connection, and rebuild it
correctly on the receiving end. The problem I am having is when I try to
send a second image. Basically it seems like the second set of data is not
arriving on the other end. Here is my code:
Client Side:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('localhost', 8888))
imgLength = sys.getsizeof(bmpstr) ## bmpstr is the pixel data
prefix = str(imgLength) # message length
prefixSize = sys.getsizeof(prefix)
if prefixSize < 30:
prefix = ('0' * (30 - prefixSize)) + prefix
prefix = "5" + "1" + prefix ## BLOCK LOCATION
s.send(prefix.encode("UTF-8"))
totalSent = 0
while totalSent < imgLength:
totalSent += 4096
if (totalSent >= imgLength):
s.send(bmpstr[totalSent :])
break
else:
s.send(bmpstr[totalSent : totalSent + 4096])
Right now I simply run this twice, sending the prefix and pixel data the
same way. Its literally copy and paste. I don't close socket s, I use the
same connection for both images. I'm wondering if maybe that is my
problem? I am hoping to have a somewhat realtime transmission of data,
maybe 3-4 FPS, so I would like to do this as efficiently as possible.
Server Side:
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.bind(('localhost', 8888))
serversocket.listen(5)
transmission = clientsocket.recv(4096)
transmissionMetaData = decode_meta_data(transmission)
transmissionLength = transmissionMetaData[0]
blockX = transmissionMetaData[1]
blockY = transmissionMetaData[2]
while 1:
thisData = clientsocket.recv(4096)
data += thisData
if len(data) >= transmissionLength or not(thisData):
break
## rebuild the image...
## here is the problem, I am trying to receive the prefix data which will
contain
# the size of the second transmission. But for some reason this never gets
any data
# it works just fine when i do it above.
while 1:
thisData = clientsocket.recv(4096)
if thisData == "":
print "WTF"
if sys.getsizeof(transmission) >= 32:
transmissionMetaData = transmission[0:11]
break
transmissionMetaData = decode_meta_data(transmission)
transmissionLength = transmissionMetaData[0]
blockX = transmissionMetaData[1]
blockY = transmissionMetaData[2]
So I am either crashing when I call decode_meta_data because transmission
is empty (i.e. no data was received), or I am sitting printing out "WTF" a
million times. On the client side I print out the data that is being sent
so I know that it is is at least calling s.send(...). But the server is
not receiving anything. I am not sure what is going on, any ideas?
I'm looking to make a very basic remote desktop application. Right now I
am able to capture the screen data using the python win32 API, and I am
able to send one image over the socket connection, and rebuild it
correctly on the receiving end. The problem I am having is when I try to
send a second image. Basically it seems like the second set of data is not
arriving on the other end. Here is my code:
Client Side:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('localhost', 8888))
imgLength = sys.getsizeof(bmpstr) ## bmpstr is the pixel data
prefix = str(imgLength) # message length
prefixSize = sys.getsizeof(prefix)
if prefixSize < 30:
prefix = ('0' * (30 - prefixSize)) + prefix
prefix = "5" + "1" + prefix ## BLOCK LOCATION
s.send(prefix.encode("UTF-8"))
totalSent = 0
while totalSent < imgLength:
totalSent += 4096
if (totalSent >= imgLength):
s.send(bmpstr[totalSent :])
break
else:
s.send(bmpstr[totalSent : totalSent + 4096])
Right now I simply run this twice, sending the prefix and pixel data the
same way. Its literally copy and paste. I don't close socket s, I use the
same connection for both images. I'm wondering if maybe that is my
problem? I am hoping to have a somewhat realtime transmission of data,
maybe 3-4 FPS, so I would like to do this as efficiently as possible.
Server Side:
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.bind(('localhost', 8888))
serversocket.listen(5)
transmission = clientsocket.recv(4096)
transmissionMetaData = decode_meta_data(transmission)
transmissionLength = transmissionMetaData[0]
blockX = transmissionMetaData[1]
blockY = transmissionMetaData[2]
while 1:
thisData = clientsocket.recv(4096)
data += thisData
if len(data) >= transmissionLength or not(thisData):
break
## rebuild the image...
## here is the problem, I am trying to receive the prefix data which will
contain
# the size of the second transmission. But for some reason this never gets
any data
# it works just fine when i do it above.
while 1:
thisData = clientsocket.recv(4096)
if thisData == "":
print "WTF"
if sys.getsizeof(transmission) >= 32:
transmissionMetaData = transmission[0:11]
break
transmissionMetaData = decode_meta_data(transmission)
transmissionLength = transmissionMetaData[0]
blockX = transmissionMetaData[1]
blockY = transmissionMetaData[2]
So I am either crashing when I call decode_meta_data because transmission
is empty (i.e. no data was received), or I am sitting printing out "WTF" a
million times. On the client side I print out the data that is being sent
so I know that it is is at least calling s.send(...). But the server is
not receiving anything. I am not sure what is going on, any ideas?
Subscribe to:
Comments (Atom)