Why is there no "remainder" in multiplication
With division, you can have a remainder (such as $5/2=2$ remainder $1$).
Now my six year old son has asked me "Why is there no remainder with
multiplication"? The obvious answer is "because it wouldn't make sense" or
just "because". Somewhat I have the feeling that prime numbers are a bit
like the remainders as you can never reach them with multiplication.
Is there a good answer to the question? (Other than the trivial ones?)
Monday, 30 September 2013
How much has Magnetic North shifted in the last few years and would this affect aeronautics=?iso-8859-1?Q?=3F_=96_skeptics.stackexchange.com?=
How much has Magnetic North shifted in the last few years and would this
affect aeronautics? – skeptics.stackexchange.com
I was talking to a contractor at a major U.S. airport, a Project Manager
who told that they were moving the runways due to the shifting of
'Magnetic North'. I have heard that the poles have shifted …
affect aeronautics? – skeptics.stackexchange.com
I was talking to a contractor at a major U.S. airport, a Project Manager
who told that they were moving the runways due to the shifting of
'Magnetic North'. I have heard that the poles have shifted …
Load Tweets in random places in Wordpress posts loop
Load Tweets in random places in Wordpress posts loop
I am trying to incorporate tweets in a masonry layout in random places. I
don't know how to incorporate it into a Wordpress loop without breaking
the loop though... Here is a fiddle of the code I am using (code too long
for here). For reference, here is the code for the query.
<?php
define('WP_USE_THEMES', false);
require('wp-load.php');
query_posts('cat=technology');
if ( have_posts() ) : while ( have_posts() ) : the_post();
$feat_image = wp_get_attachment_url(
get_post_thumbnail_id($post->ID) );
?>
<div class="masonryImage" style="width: 300px; height:250px;">
<img width="300" height="250" src= "<? echo $feat_image ?>" alt="<?
echo the_title(); ?>" />
</div>
<?php endwhile; endif; ?>
Any ideas how to put tweets in between posts in a Wordpress loop? Here is
an example of what I am ultimately trying to achieve.
I am trying to incorporate tweets in a masonry layout in random places. I
don't know how to incorporate it into a Wordpress loop without breaking
the loop though... Here is a fiddle of the code I am using (code too long
for here). For reference, here is the code for the query.
<?php
define('WP_USE_THEMES', false);
require('wp-load.php');
query_posts('cat=technology');
if ( have_posts() ) : while ( have_posts() ) : the_post();
$feat_image = wp_get_attachment_url(
get_post_thumbnail_id($post->ID) );
?>
<div class="masonryImage" style="width: 300px; height:250px;">
<img width="300" height="250" src= "<? echo $feat_image ?>" alt="<?
echo the_title(); ?>" />
</div>
<?php endwhile; endif; ?>
Any ideas how to put tweets in between posts in a Wordpress loop? Here is
an example of what I am ultimately trying to achieve.
What could be causing my app google engine cron job not to work?
What could be causing my app google engine cron job not to work?
I've the following in cron.xml on my WEB-INF directory:
?xml version="1.0" encoding="UTF-8"?>
<cronentries>
<cron>
<url>/?brtyuioacdwer</url>
<description>Load datastore</description>
<schedule>every monday 06:17</schedule>
<timezone>America/New_York</timezone>
</cron>
</cronentries>
But when the time comes to execute the shown URL nothing seems to happen
as my datastore keeps the same, of course I've tested to call the URL from
browser and it does its work nicely and I've uploaded new version of the
app several minutes before it should be automatically executing. I don't
know if there might be some problems with cron jobs when they try to write
on datastore or if they are not the default version af the web
application, so I'm asking for some guide.
Thanks for your attention.
I've the following in cron.xml on my WEB-INF directory:
?xml version="1.0" encoding="UTF-8"?>
<cronentries>
<cron>
<url>/?brtyuioacdwer</url>
<description>Load datastore</description>
<schedule>every monday 06:17</schedule>
<timezone>America/New_York</timezone>
</cron>
</cronentries>
But when the time comes to execute the shown URL nothing seems to happen
as my datastore keeps the same, of course I've tested to call the URL from
browser and it does its work nicely and I've uploaded new version of the
app several minutes before it should be automatically executing. I don't
know if there might be some problems with cron jobs when they try to write
on datastore or if they are not the default version af the web
application, so I'm asking for some guide.
Thanks for your attention.
Sunday, 29 September 2013
Building PHP soapClient array not working
Building PHP soapClient array not working
I have a successful soapClient that generates content from the following
XML sample
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Header>
<ActivityId
xmlns="http://schemas.microsoft.com/2004/09/ServiceModel/Diagnostics"
CorrelationId="f62a50bd-af24-4719-acca-fcfb8770028d">ebc35110-673d-4d15-aacd-020e14a8d62b</ActivityId>
</s:Header>
<s:Body>
<GMDataResponse xmlns="http://xx.com/xx">
<GMDataResult xmlns:a="http://xx.com/xx/GMData"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<a:Users>
<a:MData.UserData>
<a:ProjectId>37199</a:ProjectId>
<a:Name>Hilda Smith</a:Name>
<a:Number>101</a:Number>
<a:First>Hilda</a:First>
</a:MData.UserData>
<a:MData.UserData>
<a:ProjectId>37199</a:ProjectId>
<a:Name>John Smith</a:Name>
<a:Number>102</a:Number>
<a:First>John</a:First>
</a:MData.UserData>
I use the following to build the loop and it works:
$UsersAr = is_array( $res->GMDataResult->Users )
? $res->GMDataResult->Users
: array( $res->GMDataResult->Users );
foreach ($UsersAr as $Users) {
foreach($Users as $UserSet) {
foreach($UserSet as $u) {
echo $u->Name ."<br>";
}
}
}
I try:
foreach ($UsersAr as $users) {
$user = $users->MBData.UserData;
echo $user->Name;
}
and it fails (Notice: Undefined property: stdClass::$MBData) Seems like
the period in MBData.UserData is throwing an error? I'd like the cleanest
code since this is a high volume process.
I have a successful soapClient that generates content from the following
XML sample
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Header>
<ActivityId
xmlns="http://schemas.microsoft.com/2004/09/ServiceModel/Diagnostics"
CorrelationId="f62a50bd-af24-4719-acca-fcfb8770028d">ebc35110-673d-4d15-aacd-020e14a8d62b</ActivityId>
</s:Header>
<s:Body>
<GMDataResponse xmlns="http://xx.com/xx">
<GMDataResult xmlns:a="http://xx.com/xx/GMData"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<a:Users>
<a:MData.UserData>
<a:ProjectId>37199</a:ProjectId>
<a:Name>Hilda Smith</a:Name>
<a:Number>101</a:Number>
<a:First>Hilda</a:First>
</a:MData.UserData>
<a:MData.UserData>
<a:ProjectId>37199</a:ProjectId>
<a:Name>John Smith</a:Name>
<a:Number>102</a:Number>
<a:First>John</a:First>
</a:MData.UserData>
I use the following to build the loop and it works:
$UsersAr = is_array( $res->GMDataResult->Users )
? $res->GMDataResult->Users
: array( $res->GMDataResult->Users );
foreach ($UsersAr as $Users) {
foreach($Users as $UserSet) {
foreach($UserSet as $u) {
echo $u->Name ."<br>";
}
}
}
I try:
foreach ($UsersAr as $users) {
$user = $users->MBData.UserData;
echo $user->Name;
}
and it fails (Notice: Undefined property: stdClass::$MBData) Seems like
the period in MBData.UserData is throwing an error? I'd like the cleanest
code since this is a high volume process.
Removing Image Timestamp from Rails
Removing Image Timestamp from Rails
How do I stop images from being timestamped in my production environment?
http://example.com/assets/facebook-048d1c29fef2f06316fac3fff8f6ecf5.png
Coming from
<%= link_to image_tag("facebook.png", :class => "socialFacebook", :alt =>
"Facebook"), "http://www.facebook.com", target: "_blank" %>
I'm on Rails 4.
Thanks!
How do I stop images from being timestamped in my production environment?
http://example.com/assets/facebook-048d1c29fef2f06316fac3fff8f6ecf5.png
Coming from
<%= link_to image_tag("facebook.png", :class => "socialFacebook", :alt =>
"Facebook"), "http://www.facebook.com", target: "_blank" %>
I'm on Rails 4.
Thanks!
Set 1st image of old published posts as featured image
Set 1st image of old published posts as featured image
I am moving my WordPress website to a new theme and the new theme uses
featured images where as old one didnt hence my old posts dont have any
featured images. Now there are over 3000 posts in my website and obviously
setting featured images for them manually is kind of impossible.
So can you guys help me make an SQL query or link me to some plugin which
can do this?
There are a few requirements if these can be fulfilled easily. First of
all, I want the first image of the post to be set as featured not the
first 'attached' images. Secondly, the query or plugin shouldnt do
anything to posts which already have featured images.
Thanks,
I am moving my WordPress website to a new theme and the new theme uses
featured images where as old one didnt hence my old posts dont have any
featured images. Now there are over 3000 posts in my website and obviously
setting featured images for them manually is kind of impossible.
So can you guys help me make an SQL query or link me to some plugin which
can do this?
There are a few requirements if these can be fulfilled easily. First of
all, I want the first image of the post to be set as featured not the
first 'attached' images. Secondly, the query or plugin shouldnt do
anything to posts which already have featured images.
Thanks,
Splitting number and string using linq
Splitting number and string using linq
I have a string which its first part is a string and last one is a number,
like this:
ahde7394
so what I would like to obtain is:
ahde
7394
I have thought to first extract the string and then from the last position
of the character obtain the number until the end of the string so I think
using indexers can be done somehow:
var stringQuery = NameComp.Select((str,index) => new {myStr=str,
position=index})
.Where(c =>
!Char.IsDigit(c.myStr)).Select((ch,pos)
=> new { newStr=ch,
pos=pos} );
then I could do:
1) To obtain the string: stringQuery.newStr
2) To obtain the number: stringQuery.Skip(stringQuery.pos).Select(d => d);
but it is not working, after obtaining stringQuery I cannot access to its
items as it is an anonymous type....
Any ideas?
I have a string which its first part is a string and last one is a number,
like this:
ahde7394
so what I would like to obtain is:
ahde
7394
I have thought to first extract the string and then from the last position
of the character obtain the number until the end of the string so I think
using indexers can be done somehow:
var stringQuery = NameComp.Select((str,index) => new {myStr=str,
position=index})
.Where(c =>
!Char.IsDigit(c.myStr)).Select((ch,pos)
=> new { newStr=ch,
pos=pos} );
then I could do:
1) To obtain the string: stringQuery.newStr
2) To obtain the number: stringQuery.Skip(stringQuery.pos).Select(d => d);
but it is not working, after obtaining stringQuery I cannot access to its
items as it is an anonymous type....
Any ideas?
Saturday, 28 September 2013
Determining the maximum common value form a single row in MySQL
Determining the maximum common value form a single row in MySQL
I have a table like this:
-----+--------+--------+-----+-----+-----+-----+-----+-----+-----+-----+------------
r_id | r_user| module | q_1 | q_2 | q_3 | q_4 | q_5 | q_6 | q_7 | q_8 | q_9
-----+--------+--------+-----+-----+-----+-----+-----+-----+-----+-----+------------
1 | test | 1 | g | r | r | y | g | g | y | r | g
-----+--------+--------+-----+-----+-----+-----+-----+-----+-----+-----+------------
2 | test-2| 1 | r | r | g | r | r | y | y | r | g
Is there any way to determine the maximum common value for each row? For
example, the first row should result "g" and the second row should result
"r".
I can't figure it out how to do that in MYSQL. Any help on that?
I have a table like this:
-----+--------+--------+-----+-----+-----+-----+-----+-----+-----+-----+------------
r_id | r_user| module | q_1 | q_2 | q_3 | q_4 | q_5 | q_6 | q_7 | q_8 | q_9
-----+--------+--------+-----+-----+-----+-----+-----+-----+-----+-----+------------
1 | test | 1 | g | r | r | y | g | g | y | r | g
-----+--------+--------+-----+-----+-----+-----+-----+-----+-----+-----+------------
2 | test-2| 1 | r | r | g | r | r | y | y | r | g
Is there any way to determine the maximum common value for each row? For
example, the first row should result "g" and the second row should result
"r".
I can't figure it out how to do that in MYSQL. Any help on that?
String obtained from file decryption not complete
String obtained from file decryption not complete
I have made something that can successfully write an encrypted string to a
file, although unfortunately when the file is decrypted, the string is
incomplete and incorrectly formed.
The string I write to the file is:
"This should be written to the file and read perfectly. There should be no
limit to the length of a string."
The string I recieve from the file is:
"g.is should be written to the file and read perfectly. There should be no
limit to the length of a strin"
Note the "g." at the end of "string" is instead at the start, and the "th"
is missing from "this".
The methods I use to encrypt/decrypt files can be found below. I will be
very grateful for any help.
private Cipher getCipher(int nMode){
String sKey = "f94mg1hs8802tk5h";
try{
DESKeySpec oKeySpec = new DESKeySpec(sKey.getBytes());
SecretKeyFactory oKeyFactory = SecretKeyFactory.getInstance("DES");
SecretKey oSecretKey = oKeyFactory.generateSecret(oKeySpec);
Cipher oCipher = Cipher.getInstance("DES");
if(nMode == 1) oCipher.init(Cipher.ENCRYPT_MODE, oSecretKey);
else oCipher.init(Cipher.DECRYPT_MODE, oSecretKey);
return oCipher;
} catch(Exception e){
errorReport("Failed getting cipher",
"main.tools.Utils.getCipher()", "", e);
}
return null;
}
public boolean writeEncryptedFile(String sFile, String[] aContent){
boolean bSuccess = false;
if(aContent.length > 0){
String[] aContentToWrite = new String[aContent.length];
try{
Cipher oCipher = getCipher(1);
if(oCipher == null){
errorReport("Failed writing encrypted data to file: \"" +
sFile + "\"", "main.tools.Utils.writeEncodedFile()",
"Cipher was null.", null);
return false;
}
String sFileLocation = getClass().getResource(sFileDir +
sFile).toString();
sFileLocation = sFileLocation.replace("file:/", "");
FileOutputStream oOutputStream = new
FileOutputStream(sFileLocation);
CipherOutputStream oCipherStream = new
CipherOutputStream(oOutputStream, oCipher);
byte[] oContent = new byte[512];
for(int nLine = 0; nLine < aContent.length; nLine++){
System.out.println("Writing \"" + aContent[nLine] + "\" to
file.");
oContent = aContent[nLine].getBytes();
oCipherStream.write(oContent);
}
oCipherStream.flush();
oCipherStream.close();
bSuccess = true;
} catch(Exception e){
errorReport("Failed writing encrypted data to file: \"" +
sFile + "\"", "main.tools.Utils.writeEncodedFile()", "Check
file path.", e);
}
}
return bSuccess;
}
public String[] readEncryptedFile(String sFile){
Stack<String> oLines = new Stack<String>();
String[] aReadLines = null;
try{
Cipher oCipher = getCipher(0);
String sFileLocation = getClass().getResource(sFileDir +
sFile).toString();
sFileLocation = sFileLocation.replace("file:/", "");
FileInputStream oInputStream = new FileInputStream(sFileLocation);
CipherInputStream oCipherStream = new
CipherInputStream(oInputStream, oCipher);
int nBytes;
byte[] oBytes = new byte[512];
while((nBytes = oCipherStream.read(oBytes)) != -1){
oLines.push(new String(oBytes, "UTF8"));
}
if(oLines.size() > 0){
aReadLines = new String[oLines.size()];
//TESTING//
//System.out.println("====================");
//System.out.println("Writing to file: " + sFile);
//System.out.println("--------------------");
//TESTING//
for(int nLine = 0; nLine < oLines.size(); nLine++){
aReadLines[nLine] = oLines.elementAt(nLine);
}
//TESTING//
//System.out.println(aReadLines[0]);
//System.out.println("====================");
//TESTING//
}
if(aReadLines.length > 0) return aReadLines;
oCipherStream.close();
} catch(Exception e){
errorReport("Failed reading encrypted data in file: \"" + sFile +
"\"", "main.tools.Utils.readEncryptedFile()", "Check file path.",
e);
}
return null;
}
I have made something that can successfully write an encrypted string to a
file, although unfortunately when the file is decrypted, the string is
incomplete and incorrectly formed.
The string I write to the file is:
"This should be written to the file and read perfectly. There should be no
limit to the length of a string."
The string I recieve from the file is:
"g.is should be written to the file and read perfectly. There should be no
limit to the length of a strin"
Note the "g." at the end of "string" is instead at the start, and the "th"
is missing from "this".
The methods I use to encrypt/decrypt files can be found below. I will be
very grateful for any help.
private Cipher getCipher(int nMode){
String sKey = "f94mg1hs8802tk5h";
try{
DESKeySpec oKeySpec = new DESKeySpec(sKey.getBytes());
SecretKeyFactory oKeyFactory = SecretKeyFactory.getInstance("DES");
SecretKey oSecretKey = oKeyFactory.generateSecret(oKeySpec);
Cipher oCipher = Cipher.getInstance("DES");
if(nMode == 1) oCipher.init(Cipher.ENCRYPT_MODE, oSecretKey);
else oCipher.init(Cipher.DECRYPT_MODE, oSecretKey);
return oCipher;
} catch(Exception e){
errorReport("Failed getting cipher",
"main.tools.Utils.getCipher()", "", e);
}
return null;
}
public boolean writeEncryptedFile(String sFile, String[] aContent){
boolean bSuccess = false;
if(aContent.length > 0){
String[] aContentToWrite = new String[aContent.length];
try{
Cipher oCipher = getCipher(1);
if(oCipher == null){
errorReport("Failed writing encrypted data to file: \"" +
sFile + "\"", "main.tools.Utils.writeEncodedFile()",
"Cipher was null.", null);
return false;
}
String sFileLocation = getClass().getResource(sFileDir +
sFile).toString();
sFileLocation = sFileLocation.replace("file:/", "");
FileOutputStream oOutputStream = new
FileOutputStream(sFileLocation);
CipherOutputStream oCipherStream = new
CipherOutputStream(oOutputStream, oCipher);
byte[] oContent = new byte[512];
for(int nLine = 0; nLine < aContent.length; nLine++){
System.out.println("Writing \"" + aContent[nLine] + "\" to
file.");
oContent = aContent[nLine].getBytes();
oCipherStream.write(oContent);
}
oCipherStream.flush();
oCipherStream.close();
bSuccess = true;
} catch(Exception e){
errorReport("Failed writing encrypted data to file: \"" +
sFile + "\"", "main.tools.Utils.writeEncodedFile()", "Check
file path.", e);
}
}
return bSuccess;
}
public String[] readEncryptedFile(String sFile){
Stack<String> oLines = new Stack<String>();
String[] aReadLines = null;
try{
Cipher oCipher = getCipher(0);
String sFileLocation = getClass().getResource(sFileDir +
sFile).toString();
sFileLocation = sFileLocation.replace("file:/", "");
FileInputStream oInputStream = new FileInputStream(sFileLocation);
CipherInputStream oCipherStream = new
CipherInputStream(oInputStream, oCipher);
int nBytes;
byte[] oBytes = new byte[512];
while((nBytes = oCipherStream.read(oBytes)) != -1){
oLines.push(new String(oBytes, "UTF8"));
}
if(oLines.size() > 0){
aReadLines = new String[oLines.size()];
//TESTING//
//System.out.println("====================");
//System.out.println("Writing to file: " + sFile);
//System.out.println("--------------------");
//TESTING//
for(int nLine = 0; nLine < oLines.size(); nLine++){
aReadLines[nLine] = oLines.elementAt(nLine);
}
//TESTING//
//System.out.println(aReadLines[0]);
//System.out.println("====================");
//TESTING//
}
if(aReadLines.length > 0) return aReadLines;
oCipherStream.close();
} catch(Exception e){
errorReport("Failed reading encrypted data in file: \"" + sFile +
"\"", "main.tools.Utils.readEncryptedFile()", "Check file path.",
e);
}
return null;
}
Detecting request without using document.domain
Detecting request without using document.domain
I have a script placed in a website.
<script>
var domain = document.domain;
/* script related to website...*/
</script>
This returns the website domain to my site using some script. Now, how can
we detect the domain name without using document.domain. I cannot use
document.domain as part of variable as it can easily be changed by anyone
and script is no more secure. How can I check whether my script is placed
in designated website.I am having list of website names in database? I am
using cakephp framework.
I have a script placed in a website.
<script>
var domain = document.domain;
/* script related to website...*/
</script>
This returns the website domain to my site using some script. Now, how can
we detect the domain name without using document.domain. I cannot use
document.domain as part of variable as it can easily be changed by anyone
and script is no more secure. How can I check whether my script is placed
in designated website.I am having list of website names in database? I am
using cakephp framework.
C# Connecting 2 Projects
C# Connecting 2 Projects
I downloaded a Sudoku game in C# and I am trying to connect that game with
my project but when I try to connect it with :
private void button4_Click(object sender, EventArgs e)
{
Sudoku.SudokuMainForm a = new Sudoku.SudokuMainForm();
a.Show();
Hide();
}
It tells me that Sudoku is a namespace but is used like a type.
Here is the part where I have problems with.
namespace Sudoku
{
public class SudokuMainForm : System.Windows.Forms.Form
}
Sudoku _newGame = new Sudoku();
private void btnAnswer_Click(object sender, System.EventArgs e)
{
_showAnswer = false;
ShowAnswer();
timer1.Enabled = true;
}
Tried the whole day to fix it,but can't find the solution for my problem.
Hope that you guys have an idea. Thanks
I downloaded a Sudoku game in C# and I am trying to connect that game with
my project but when I try to connect it with :
private void button4_Click(object sender, EventArgs e)
{
Sudoku.SudokuMainForm a = new Sudoku.SudokuMainForm();
a.Show();
Hide();
}
It tells me that Sudoku is a namespace but is used like a type.
Here is the part where I have problems with.
namespace Sudoku
{
public class SudokuMainForm : System.Windows.Forms.Form
}
Sudoku _newGame = new Sudoku();
private void btnAnswer_Click(object sender, System.EventArgs e)
{
_showAnswer = false;
ShowAnswer();
timer1.Enabled = true;
}
Tried the whole day to fix it,but can't find the solution for my problem.
Hope that you guys have an idea. Thanks
Friday, 27 September 2013
Gruntfile.js with "require" function and passing parameters
Gruntfile.js with "require" function and passing parameters
I have a Grunt file (Gruntfile.js) to build an angularjs component. I use
an external javascript file (build.config.js) to define the required files
and output directories.
module.exports = {
build_dir: 'build',
app_files: {
src: ['src/**/*.js','!src/**/*.spec.js'],
//...
},
vendor_files: {
js: [ /* vendor files like jquery, bootstrap, etc... */ ]
}
}
And my Gruntfile.js calling it like this
module.exports = function(grunt) {
/* some code */
var userConfig = require('./build.config.js');
var taskConfig = {
pkg: grunt.file.readJSON("package.json"),
/* more code */
},
/* yet more code */
}
In my package.json, I specify a locale variable for i18n purposes that I
can use inside the taskConfig section by putting it like '<%= pkg.locale
%>'. Now there are some javascript files specified in build.config.js that
I need to load depending on the locale specified, but I don't know how to
get this variable since in build.config.js there is no grunt object to
read the package.json file. Therefore, I can't do something like this in
build.config.js:
vendor_files: {
js: [ 'vendor/foo/bar.<%= pkg.locale %>.js' ]
Is there any way I can accomplish this without putting everything from
build.config.js back in Gruntfile.js?
I have a Grunt file (Gruntfile.js) to build an angularjs component. I use
an external javascript file (build.config.js) to define the required files
and output directories.
module.exports = {
build_dir: 'build',
app_files: {
src: ['src/**/*.js','!src/**/*.spec.js'],
//...
},
vendor_files: {
js: [ /* vendor files like jquery, bootstrap, etc... */ ]
}
}
And my Gruntfile.js calling it like this
module.exports = function(grunt) {
/* some code */
var userConfig = require('./build.config.js');
var taskConfig = {
pkg: grunt.file.readJSON("package.json"),
/* more code */
},
/* yet more code */
}
In my package.json, I specify a locale variable for i18n purposes that I
can use inside the taskConfig section by putting it like '<%= pkg.locale
%>'. Now there are some javascript files specified in build.config.js that
I need to load depending on the locale specified, but I don't know how to
get this variable since in build.config.js there is no grunt object to
read the package.json file. Therefore, I can't do something like this in
build.config.js:
vendor_files: {
js: [ 'vendor/foo/bar.<%= pkg.locale %>.js' ]
Is there any way I can accomplish this without putting everything from
build.config.js back in Gruntfile.js?
c# asp.net empty web application imagebutton1.Location not working
c# asp.net empty web application imagebutton1.Location not working
I'm trying to make an image slideshow for this task so far i have 2
buttons left arrow and right arrow and between them one imagebutton.
I want to move the imagebutton by pressing the left/right arrow buttons
But the ImageButton1.Location property is not working why?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
Are my libraries.
I'm trying to make an image slideshow for this task so far i have 2
buttons left arrow and right arrow and between them one imagebutton.
I want to move the imagebutton by pressing the left/right arrow buttons
But the ImageButton1.Location property is not working why?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
Are my libraries.
How to split specific string by delimiter
How to split specific string by delimiter
i am having problems with splitting string with this name inside:
Aix-en-Provence
String possibilities are:
Aix-en-Provence-Test2 Test2-Aix-en-Provence
I would like to split string dynamically with delmiter ('-') to get
Aix-en-Provence and Test2 seperated.
How to? I was trying with Regex.execute with different patterns but
unsuccessful. I am parsing data in Javascript.
Thanks in advance.
Best regards
i am having problems with splitting string with this name inside:
Aix-en-Provence
String possibilities are:
Aix-en-Provence-Test2 Test2-Aix-en-Provence
I would like to split string dynamically with delmiter ('-') to get
Aix-en-Provence and Test2 seperated.
How to? I was trying with Regex.execute with different patterns but
unsuccessful. I am parsing data in Javascript.
Thanks in advance.
Best regards
How to access rule tree (ANTLR 4)
How to access rule tree (ANTLR 4)
I get rule tree info by
VP.BuildParseTree=true ;
ParserRuleContext tree = VP.source_text();
VP is my parser instance, rule name: source_text
How can i loop over N rules ? how can i use rule-name like this
ParserRuleContext tree = VP.rulename
thanks
I get rule tree info by
VP.BuildParseTree=true ;
ParserRuleContext tree = VP.source_text();
VP is my parser instance, rule name: source_text
How can i loop over N rules ? how can i use rule-name like this
ParserRuleContext tree = VP.rulename
thanks
Extracting raw data from bytes object
Extracting raw data from bytes object
Using Boost Python, is there a better way to get the raw data out of a
Python 3 bytes object than this fairly nasty way?
py::object raw = <a bytes object>
int n = py::len(raw);
char *r = new char[n];
for(int i=0; i<n; ++i)
r[i] = py::extract<int>(raw[i]);
(Boost 1.48 with Python 3.2)
Using Boost Python, is there a better way to get the raw data out of a
Python 3 bytes object than this fairly nasty way?
py::object raw = <a bytes object>
int n = py::len(raw);
char *r = new char[n];
for(int i=0; i<n; ++i)
r[i] = py::extract<int>(raw[i]);
(Boost 1.48 with Python 3.2)
Sort ArrayList by any column and "print" result
Sort ArrayList by any column and "print" result
I filled array list with values. Each row is item with properties. Now I
would like to sort items by one of properties and "print" them to
textview.
ArrayList<String[]> arrayList = new ArrayList<String[]>();
final String[] rowToArray = new String[7];
rowToArray[0] = itemName;
rowToArray[1] = itemProperties1;
rowToArray[2] = itemProperties2;
rowToArray[3] = itemProperties3;
rowToArray[4] = itemProperties4;
rowToArray[5] = itemProperties5;
rowToArray[6] = itemProperties6;
arrayList.add(rowToArray);
Could you please help me to sort it by properties and then show me how to
print item one by one with properties.
Thank you in advance.
I filled array list with values. Each row is item with properties. Now I
would like to sort items by one of properties and "print" them to
textview.
ArrayList<String[]> arrayList = new ArrayList<String[]>();
final String[] rowToArray = new String[7];
rowToArray[0] = itemName;
rowToArray[1] = itemProperties1;
rowToArray[2] = itemProperties2;
rowToArray[3] = itemProperties3;
rowToArray[4] = itemProperties4;
rowToArray[5] = itemProperties5;
rowToArray[6] = itemProperties6;
arrayList.add(rowToArray);
Could you please help me to sort it by properties and then show me how to
print item one by one with properties.
Thank you in advance.
Button event touch not firing method from selector in IOS 7?
Button event touch not firing method from selector in IOS 7?
I have a strange behavior for a button in ios 7, not detecting touches but
in ios 6 works fine. The button it's loaded from a custom xib in which I
set an outlet for the button. The view with button it's initialized into
controller in which I set for button an action programmatic, after this
view it's added to a table like a subview. The code which I used:
viewWithButton = [[CustomView alloc] initWithFrame:CGRectMake(0, 64,
self.tableView.bounds.size.width, 44)];
[self.tableView addSubview:viewWithButton];
[viewWithButton.btn addTarget:self action:@selector(test)
forControlEvents:UIControlEventTouchUpInside];
And in custom view I have:
@property (nonatomic) IBOutlet UIButton *btn;
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self)
{
[[NSBundle mainBundle] loadNibNamed:@"viewWithButton" owner:self
options:nil];
self.view.frame = frame;
[self addSubview:self.view];
}
return self;}
The custom view it's displayed in tableview but I can't interact nohow
with button and this just in ios 7, in ios 6 works great and method(test)
it's called.
Any thoughts? (sorry for misspellings).
Thanks in advance for any help.
I have a strange behavior for a button in ios 7, not detecting touches but
in ios 6 works fine. The button it's loaded from a custom xib in which I
set an outlet for the button. The view with button it's initialized into
controller in which I set for button an action programmatic, after this
view it's added to a table like a subview. The code which I used:
viewWithButton = [[CustomView alloc] initWithFrame:CGRectMake(0, 64,
self.tableView.bounds.size.width, 44)];
[self.tableView addSubview:viewWithButton];
[viewWithButton.btn addTarget:self action:@selector(test)
forControlEvents:UIControlEventTouchUpInside];
And in custom view I have:
@property (nonatomic) IBOutlet UIButton *btn;
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self)
{
[[NSBundle mainBundle] loadNibNamed:@"viewWithButton" owner:self
options:nil];
self.view.frame = frame;
[self addSubview:self.view];
}
return self;}
The custom view it's displayed in tableview but I can't interact nohow
with button and this just in ios 7, in ios 6 works great and method(test)
it's called.
Any thoughts? (sorry for misspellings).
Thanks in advance for any help.
Thursday, 26 September 2013
How to change default mail address for installing apps in windows 8 web store app
How to change default mail address for installing apps in windows 8 web
store app
Can any one help "How to change default mail address for access windows
store apps in windows 8 web store app". I didn't find any option "Sign in
with different user".
Please see the image to understand...(Sorry i don't have points to post
image) http://i.stack.imgur.com/B0egx.png
Thanks
Satish
store app
Can any one help "How to change default mail address for access windows
store apps in windows 8 web store app". I didn't find any option "Sign in
with different user".
Please see the image to understand...(Sorry i don't have points to post
image) http://i.stack.imgur.com/B0egx.png
Thanks
Satish
Wednesday, 25 September 2013
Split the array varible
Split the array varible
i have an array like this.
(
2right, 1, 3, 4
)
i want it to seprete out right. Like this
(
2, 1, 3, 4
)
i tried out this one but not working.
NSMutableArray * array=[self.AnswerDic objectForKey:@"first"];
NSLog(@"%@",array);
optionA.text=[[[array
objectAtIndex:0]componentsSeparatedByString:@"right"]objectAtIndex:0];
optionB.text=[[[array
objectAtIndex:1]componentsSeparatedByString:@"right"]objectAtIndex:1];
optionC.text=[[[array
objectAtIndex:2]componentsSeparatedByString:@"right"]objectAtIndex:2];
optionD.text=[[[array
objectAtIndex:3]componentsSeparatedByString:@"right"]objectAtIndex:3];
give me warning. how may i seprate out the string.
i have an array like this.
(
2right, 1, 3, 4
)
i want it to seprete out right. Like this
(
2, 1, 3, 4
)
i tried out this one but not working.
NSMutableArray * array=[self.AnswerDic objectForKey:@"first"];
NSLog(@"%@",array);
optionA.text=[[[array
objectAtIndex:0]componentsSeparatedByString:@"right"]objectAtIndex:0];
optionB.text=[[[array
objectAtIndex:1]componentsSeparatedByString:@"right"]objectAtIndex:1];
optionC.text=[[[array
objectAtIndex:2]componentsSeparatedByString:@"right"]objectAtIndex:2];
optionD.text=[[[array
objectAtIndex:3]componentsSeparatedByString:@"right"]objectAtIndex:3];
give me warning. how may i seprate out the string.
Thursday, 19 September 2013
memcached setup for max memory and expire
memcached setup for max memory and expire
What is the optimum setup for memcached ? for example, how many MB memory
we should assign ? And also how long should we kept before it expires ? I
tried setting memcached to expire in 1 hour. The first day it's running
okay. But the next day, the server running very slow like it's running out
of memory. So I delete all cache and retry with expiration down to 10
minutes.
Is there a way to tell memcached to flush if the memory used is full ? So
not too make the whole website becoming very slow ?
What is the optimum setup for memcached ? for example, how many MB memory
we should assign ? And also how long should we kept before it expires ? I
tried setting memcached to expire in 1 hour. The first day it's running
okay. But the next day, the server running very slow like it's running out
of memory. So I delete all cache and retry with expiration down to 10
minutes.
Is there a way to tell memcached to flush if the memory used is full ? So
not too make the whole website becoming very slow ?
Cannot post Tweets with Linq to Twitter using saved Oauth credentials
Cannot post Tweets with Linq to Twitter using saved Oauth credentials
I have no problems using the Linq to Twitter WebAuthorizer to post Tweets
to Twitter if my end-users are directed to Twitter's Oauth page and
returned to our site. Using WebAuthorizer in this manner works great.
However, if I try to store the end-user's Oauth credentials and use them
to Tweet, I get a 401 Unauthorized error:
LinqToTwitter.TwitterQueryException: Invalid or expired token --->
System.Net.WebException: The remote server returned an error: (401)
Unauthorized. at LinqToTwitter.TwitterExecute.PostToTwitter[T](String url,
IDictionary2 postData, Func2 getResult) --- End of inner exception stack
trace --- at LinqToTwitter.TwitterExecute.PostToTwitter[T](String url,
IDictionary2 postData, Func2 getResult) at
LinqToTwitter.StatusExtensions.UpdateStatus(TwitterContext ctx, String
status, Decimal latitude, Decimal longitude, String placeID, Boolean
displayCoordinates, String inReplyToStatusID, Boolean trimUser, Action`1
callback) at LinqToTwitter.StatusExtensions.UpdateStatus(TwitterContext
ctx, String status) at
External_WCPages_v12_Test_TwitterTest.StoredCredentialsSingleUserAuthorizer()
in
C:\TFS\SC\Weblink_Connect-Development\CWT\External\WCPages\v12\Test\TwitterTest.aspx.vb:line
177 at External_WCPages_v12_Test_TwitterTest.Page_Load(Object sender,
EventArgs e) in
C:\TFS\SC\Weblink_Connect-Development\CWT\External\WCPages\v12\Test\TwitterTest.aspx.vb:line
65
I am including the primary functions which handle the Linq to Twitter
requests. Please help, am I doing something wrong? I have tried releases
2.106, 2.107, 2.108 and the latest changesets as of 9/19/2013.
Private Sub BeginWebAuthorizer()
'Comment: Triggered on PostBack
mobj_WebAuthorizer = New WebAuthorizer
Dim objCredentials As IOAuthCredentials = New InMemoryCredentials()
objCredentials.ConsumerKey = Me.ConsumerKey
objCredentials.ConsumerSecret = Me.ConsumerSecret
mobj_WebAuthorizer.Credentials = objCredentials
mobj_WebAuthorizer.PerformRedirect = Sub(authUrl)
Response.Redirect(authUrl)
End Sub
mobj_WebAuthorizer.BeginAuthorization(Request.Url)
End Sub
Private Sub CompleteWebAuthorizer()
'Comment: Triggered on return from the Twitter authorization page
Dim objCredentials As IOAuthCredentials = New
SingleUserInMemoryCredentials
objCredentials.ConsumerKey = Me.ConsumerKey
objCredentials.ConsumerSecret = Me.ConsumerSecret
mobj_WebAuthorizer = New WebAuthorizer
mobj_WebAuthorizer.Credentials = objCredentials
Call mobj_WebAuthorizer.CompleteAuthorization(Request.Url)
mobj_TwitterContext = New TwitterContext(mobj_WebAuthorizer)
'Success: This posts a Tweet
mobj_TwitterContext.UpdateStatus("Test Tweet using LinqToTwitter
WebAuthorizer ( not using stored credentials ) : " &
Date.Now.Millisecond.ToString)
End Sub
Private Sub StoredCredentialsWebAuthorizer()
'Comment: Triggered on PostBack
Dim objCredentials As IOAuthCredentials = New InMemoryCredentials
'For Testing: Dim objCredentials As IOAuthCredentials = New
SingleUserInMemoryCredentials
'For Testing: Dim objCredentials As IOAuthCredentials = New
SessionStateCredentials
objCredentials.ConsumerKey = Me.ConsumerKey
objCredentials.ConsumerSecret = Me.ConsumerSecret
objCredentials.AccessToken = Me.SavedToken
objCredentials.OAuthToken = Me.SavedTokenSecret
mobj_WebAuthorizer = New WebAuthorizer
mobj_WebAuthorizer.Credentials = objCredentials
'For Testing: Call
mobj_WebAuthorizer.CompleteAuthorization(Request.Url)
mobj_TwitterContext = New TwitterContext(mobj_WebAuthorizer)
'BUG: SingleUserAuthorizer doesn't seem to work with the saved
credentials from database
mobj_TwitterContext.UpdateStatus("Test Tweet using LinqToTwitter
WebAuthorizer ( using stored credentials ) : " &
Date.Now.Millisecond.ToString)
End Sub
I have no problems using the Linq to Twitter WebAuthorizer to post Tweets
to Twitter if my end-users are directed to Twitter's Oauth page and
returned to our site. Using WebAuthorizer in this manner works great.
However, if I try to store the end-user's Oauth credentials and use them
to Tweet, I get a 401 Unauthorized error:
LinqToTwitter.TwitterQueryException: Invalid or expired token --->
System.Net.WebException: The remote server returned an error: (401)
Unauthorized. at LinqToTwitter.TwitterExecute.PostToTwitter[T](String url,
IDictionary2 postData, Func2 getResult) --- End of inner exception stack
trace --- at LinqToTwitter.TwitterExecute.PostToTwitter[T](String url,
IDictionary2 postData, Func2 getResult) at
LinqToTwitter.StatusExtensions.UpdateStatus(TwitterContext ctx, String
status, Decimal latitude, Decimal longitude, String placeID, Boolean
displayCoordinates, String inReplyToStatusID, Boolean trimUser, Action`1
callback) at LinqToTwitter.StatusExtensions.UpdateStatus(TwitterContext
ctx, String status) at
External_WCPages_v12_Test_TwitterTest.StoredCredentialsSingleUserAuthorizer()
in
C:\TFS\SC\Weblink_Connect-Development\CWT\External\WCPages\v12\Test\TwitterTest.aspx.vb:line
177 at External_WCPages_v12_Test_TwitterTest.Page_Load(Object sender,
EventArgs e) in
C:\TFS\SC\Weblink_Connect-Development\CWT\External\WCPages\v12\Test\TwitterTest.aspx.vb:line
65
I am including the primary functions which handle the Linq to Twitter
requests. Please help, am I doing something wrong? I have tried releases
2.106, 2.107, 2.108 and the latest changesets as of 9/19/2013.
Private Sub BeginWebAuthorizer()
'Comment: Triggered on PostBack
mobj_WebAuthorizer = New WebAuthorizer
Dim objCredentials As IOAuthCredentials = New InMemoryCredentials()
objCredentials.ConsumerKey = Me.ConsumerKey
objCredentials.ConsumerSecret = Me.ConsumerSecret
mobj_WebAuthorizer.Credentials = objCredentials
mobj_WebAuthorizer.PerformRedirect = Sub(authUrl)
Response.Redirect(authUrl)
End Sub
mobj_WebAuthorizer.BeginAuthorization(Request.Url)
End Sub
Private Sub CompleteWebAuthorizer()
'Comment: Triggered on return from the Twitter authorization page
Dim objCredentials As IOAuthCredentials = New
SingleUserInMemoryCredentials
objCredentials.ConsumerKey = Me.ConsumerKey
objCredentials.ConsumerSecret = Me.ConsumerSecret
mobj_WebAuthorizer = New WebAuthorizer
mobj_WebAuthorizer.Credentials = objCredentials
Call mobj_WebAuthorizer.CompleteAuthorization(Request.Url)
mobj_TwitterContext = New TwitterContext(mobj_WebAuthorizer)
'Success: This posts a Tweet
mobj_TwitterContext.UpdateStatus("Test Tweet using LinqToTwitter
WebAuthorizer ( not using stored credentials ) : " &
Date.Now.Millisecond.ToString)
End Sub
Private Sub StoredCredentialsWebAuthorizer()
'Comment: Triggered on PostBack
Dim objCredentials As IOAuthCredentials = New InMemoryCredentials
'For Testing: Dim objCredentials As IOAuthCredentials = New
SingleUserInMemoryCredentials
'For Testing: Dim objCredentials As IOAuthCredentials = New
SessionStateCredentials
objCredentials.ConsumerKey = Me.ConsumerKey
objCredentials.ConsumerSecret = Me.ConsumerSecret
objCredentials.AccessToken = Me.SavedToken
objCredentials.OAuthToken = Me.SavedTokenSecret
mobj_WebAuthorizer = New WebAuthorizer
mobj_WebAuthorizer.Credentials = objCredentials
'For Testing: Call
mobj_WebAuthorizer.CompleteAuthorization(Request.Url)
mobj_TwitterContext = New TwitterContext(mobj_WebAuthorizer)
'BUG: SingleUserAuthorizer doesn't seem to work with the saved
credentials from database
mobj_TwitterContext.UpdateStatus("Test Tweet using LinqToTwitter
WebAuthorizer ( using stored credentials ) : " &
Date.Now.Millisecond.ToString)
End Sub
Rails Block Helper similar to form_for with resource routine
Rails Block Helper similar to form_for with resource routine
Im struggling trying to make a helper class that works with blocks like
the form_for do |f|. I think I have it working but I cant seem to be able
to use routing. It seems the way I have it setup routing is unavailable in
the class, but I cant find any way to correct it.
I want to be able to do this
<%= nav_list do |nl| %>
<%= nl.link @model.name, @model %>
<% end %>
My helper file is setup like this:
module NavListHelper
class NavList
include ActionView::Helpers::TagHelper
include ActionView::Helpers::UrlHelper
def header(title)
content_tag :li, title, class: 'nav-header'
end
def link(title, path)
link_to title, path
end
end
def nav_list(&block)
new_block = Proc.new do
helper = NavList.new
block.call(helper)
end
content_tag :ul, capture(&new_block), class: 'nav nav-list'
end
end
The issue is being able to use link_to (and url_for) when I pass a model
object to it.
Im struggling trying to make a helper class that works with blocks like
the form_for do |f|. I think I have it working but I cant seem to be able
to use routing. It seems the way I have it setup routing is unavailable in
the class, but I cant find any way to correct it.
I want to be able to do this
<%= nav_list do |nl| %>
<%= nl.link @model.name, @model %>
<% end %>
My helper file is setup like this:
module NavListHelper
class NavList
include ActionView::Helpers::TagHelper
include ActionView::Helpers::UrlHelper
def header(title)
content_tag :li, title, class: 'nav-header'
end
def link(title, path)
link_to title, path
end
end
def nav_list(&block)
new_block = Proc.new do
helper = NavList.new
block.call(helper)
end
content_tag :ul, capture(&new_block), class: 'nav nav-list'
end
end
The issue is being able to use link_to (and url_for) when I pass a model
object to it.
Applying a % style binding with knockout via function not working
Applying a % style binding with knockout via function not working
I want to set the width of a div equal to a percentage calculated by a
javascript method. I can get knockout to apply the style binding properly
using this:
<div class="bar" data-bind="style: { width: '50%'}"></div>
but when I try to use a function to generate the output, it breaks:
<div class="bar" data-bind="style: { width: function(){return '50' +
'%';}}"></div>
I want to set the width of a div equal to a percentage calculated by a
javascript method. I can get knockout to apply the style binding properly
using this:
<div class="bar" data-bind="style: { width: '50%'}"></div>
but when I try to use a function to generate the output, it breaks:
<div class="bar" data-bind="style: { width: function(){return '50' +
'%';}}"></div>
IOS 7 status bar missing in older app
IOS 7 status bar missing in older app
We have an app that is currently having issues with the iOS 7 status bar,
throwing the entire layout off.
We found an answer to this issue, here: New iOS 7 statusBar leaves a range
20px in apps compiled in Xcode 5
The problem with the answer, in which the user states that you must set
the "Window's Y Paramter" to 20... is that I have no clue what they are
talking about, and am having no luck finding it on google!
Does anyone know where this parameter is at? Could someone give me general
directions? =D
We have an app that is currently having issues with the iOS 7 status bar,
throwing the entire layout off.
We found an answer to this issue, here: New iOS 7 statusBar leaves a range
20px in apps compiled in Xcode 5
The problem with the answer, in which the user states that you must set
the "Window's Y Paramter" to 20... is that I have no clue what they are
talking about, and am having no luck finding it on google!
Does anyone know where this parameter is at? Could someone give me general
directions? =D
How to I make check marks appear and disappear when I click multiple rows?
How to I make check marks appear and disappear when I click multiple rows?
I want a table which, when you click different rows, they gain or lose a
checkmark to show they are either selected or not selected.
Currently my tableview will let me select and deselect different rows. But
a checkmark will only appear once I have clicked one and then another. The
same happens when I deselect, I click a row with a checkmark then click
another row and the checkmark disappears.
Here is my code currently:
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString * exerciseChoiceSimpleTableIdentifier =
@"ExerciseChoiceSimpleTableIdentifier";
UITableViewCell * exerciseChoiceCell = [tableView
dequeueReusableCellWithIdentifier:exerciseChoiceSimpleTableIdentifier];
if (exerciseChoiceCell == nil) {
exerciseChoiceCell = [[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:exerciseChoiceSimpleTableIdentifier];
}
//Here we get each exercise we want to display
BExercise * exercise = [[_data getExerciseCompleteList]
objectAtIndex:indexPath.row];
//Name the cell after the exercises we want to display
exerciseChoiceCell.textLabel.text = exercise.name;
return exerciseChoiceCell;
}
-(void)tableView:(UITableView *)tableView
didDeselectRowAtIndexPath:(NSIndexPath *)indexPath {
if ([tableView cellForRowAtIndexPath:indexPath].accessoryType ==
UITableViewCellAccessoryNone)
{
// Uncheck the row
[tableView deselectRowAtIndexPath:indexPath animated:YES];
[tableView cellForRowAtIndexPath:indexPath].accessoryType =
UITableViewCellAccessoryCheckmark;
}
else
{
// Check the row
[tableView deselectRowAtIndexPath:indexPath animated:YES];
[tableView cellForRowAtIndexPath:indexPath].accessoryType =
UITableViewCellAccessoryNone;
}
}
I think the problem is to do with it being selected rather than touch up
inside and deselecting when the finger is released from the button.
I am expecting the answer to be quite straight forward but all the similar
questions on stackflow haven't dealt with the checkmarks delayed
appearance.
It would be great to understand the root of this problem and how to fix it.
I want a table which, when you click different rows, they gain or lose a
checkmark to show they are either selected or not selected.
Currently my tableview will let me select and deselect different rows. But
a checkmark will only appear once I have clicked one and then another. The
same happens when I deselect, I click a row with a checkmark then click
another row and the checkmark disappears.
Here is my code currently:
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString * exerciseChoiceSimpleTableIdentifier =
@"ExerciseChoiceSimpleTableIdentifier";
UITableViewCell * exerciseChoiceCell = [tableView
dequeueReusableCellWithIdentifier:exerciseChoiceSimpleTableIdentifier];
if (exerciseChoiceCell == nil) {
exerciseChoiceCell = [[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:exerciseChoiceSimpleTableIdentifier];
}
//Here we get each exercise we want to display
BExercise * exercise = [[_data getExerciseCompleteList]
objectAtIndex:indexPath.row];
//Name the cell after the exercises we want to display
exerciseChoiceCell.textLabel.text = exercise.name;
return exerciseChoiceCell;
}
-(void)tableView:(UITableView *)tableView
didDeselectRowAtIndexPath:(NSIndexPath *)indexPath {
if ([tableView cellForRowAtIndexPath:indexPath].accessoryType ==
UITableViewCellAccessoryNone)
{
// Uncheck the row
[tableView deselectRowAtIndexPath:indexPath animated:YES];
[tableView cellForRowAtIndexPath:indexPath].accessoryType =
UITableViewCellAccessoryCheckmark;
}
else
{
// Check the row
[tableView deselectRowAtIndexPath:indexPath animated:YES];
[tableView cellForRowAtIndexPath:indexPath].accessoryType =
UITableViewCellAccessoryNone;
}
}
I think the problem is to do with it being selected rather than touch up
inside and deselecting when the finger is released from the button.
I am expecting the answer to be quite straight forward but all the similar
questions on stackflow haven't dealt with the checkmarks delayed
appearance.
It would be great to understand the root of this problem and how to fix it.
CRC Craking knowing result
CRC Craking knowing result
I have a CRC code probably CRC-8 (or greater but truncated) because it is
1 byte long, but I don't know how it has been calculated. I also have the
data that possibly had been used to calculate it. Is there any way to
reverse or brute force the algorithm and the parameters? I tried several
solutions, without being able to find the polynomial used to calculate it.
Thank you very much, bye.
I have a CRC code probably CRC-8 (or greater but truncated) because it is
1 byte long, but I don't know how it has been calculated. I also have the
data that possibly had been used to calculate it. Is there any way to
reverse or brute force the algorithm and the parameters? I tried several
solutions, without being able to find the polynomial used to calculate it.
Thank you very much, bye.
Wednesday, 18 September 2013
using Prepared statements and dynamic param
using Prepared statements and dynamic param
I'm using a prepared statement and these functions are part of a mysqli
class .They work well for singl condition But do not right answer for
multiple condition like this:
SelectByOrderCondi('user','username=? AND name=? AND email=? ' , $Array )
Here's my functions :
public function SelectByOrderCondi($Table_Name, $Conditions=''
,$Array_Conditions_Limit=null, $OrderBy='', $Limit='',
$Selected_Fields='*')
{
$Query = "SELECT ".$Selected_Fields." FROM ".$Table_Name;
if(!empty($Conditions))
$Query .= " WHERE ".$Conditions;
if(!empty($OrderBy))
$Query .= " ORDER BY ".$OrderBy;
if(!empty($Limit))
$Query .= " LIMIT ".$Limit;
$Statment = $this->ConnectionResult->prepare($Query);
if(isset($Array_Conditions_Limit) )
{
$Statment = $this->DynamicBindVariables($Statment,
$Array_Conditions_Limit);
$Statment->execute();
return $Statment->get_result();
}
else
return false ;
}
This function product dynamic bind variables
private function DynamicBindVariables($Statment, $Params)
{
if (is_array($Params) && $Params != null)
{
// Generate the Type String (eg: 'issisd')
$Types = '';
foreach($Params as $Param)
{
if(is_int($Param)) //Int
$Types .= 'i';
elseif (is_float($Param)) // Double
$Types .= 'd';
elseif (is_string($Param)) // String
$Types .= 's';
else // Blob and Unknown
$Types .= 'b';
}
// Add the Type String as the first Parameter
$Bind_names[] = $Types;
// Loop thru the given Parameters
for ($i=0; $i<count($Params);$i++)
{
$Bind_name = 'bind' . $i;
// Add the Parameter to the variable
$$Bind_name = $Params[$i];
// Associate the Variable as an Element in the Array
$Bind_names[] = &$$Bind_name;
}
// Call the Function bind_param with dynamic Parameters
call_user_func_array(array($Statment,'bind_param'), $Bind_names);
}
else
{
$Types = '';
if(is_int($Params)) //Int
$Types .= 'i';
elseif (is_float($Params)) // Double
$Types .= 'd';
elseif (is_string($Params)) // String
$Types .= 's';
else // Blob and Unknown
$Types .= 'b';
$Statment->bind_param($Types ,$Params);
}
return $Statment;
}
I'm using a prepared statement and these functions are part of a mysqli
class .They work well for singl condition But do not right answer for
multiple condition like this:
SelectByOrderCondi('user','username=? AND name=? AND email=? ' , $Array )
Here's my functions :
public function SelectByOrderCondi($Table_Name, $Conditions=''
,$Array_Conditions_Limit=null, $OrderBy='', $Limit='',
$Selected_Fields='*')
{
$Query = "SELECT ".$Selected_Fields." FROM ".$Table_Name;
if(!empty($Conditions))
$Query .= " WHERE ".$Conditions;
if(!empty($OrderBy))
$Query .= " ORDER BY ".$OrderBy;
if(!empty($Limit))
$Query .= " LIMIT ".$Limit;
$Statment = $this->ConnectionResult->prepare($Query);
if(isset($Array_Conditions_Limit) )
{
$Statment = $this->DynamicBindVariables($Statment,
$Array_Conditions_Limit);
$Statment->execute();
return $Statment->get_result();
}
else
return false ;
}
This function product dynamic bind variables
private function DynamicBindVariables($Statment, $Params)
{
if (is_array($Params) && $Params != null)
{
// Generate the Type String (eg: 'issisd')
$Types = '';
foreach($Params as $Param)
{
if(is_int($Param)) //Int
$Types .= 'i';
elseif (is_float($Param)) // Double
$Types .= 'd';
elseif (is_string($Param)) // String
$Types .= 's';
else // Blob and Unknown
$Types .= 'b';
}
// Add the Type String as the first Parameter
$Bind_names[] = $Types;
// Loop thru the given Parameters
for ($i=0; $i<count($Params);$i++)
{
$Bind_name = 'bind' . $i;
// Add the Parameter to the variable
$$Bind_name = $Params[$i];
// Associate the Variable as an Element in the Array
$Bind_names[] = &$$Bind_name;
}
// Call the Function bind_param with dynamic Parameters
call_user_func_array(array($Statment,'bind_param'), $Bind_names);
}
else
{
$Types = '';
if(is_int($Params)) //Int
$Types .= 'i';
elseif (is_float($Params)) // Double
$Types .= 'd';
elseif (is_string($Params)) // String
$Types .= 's';
else // Blob and Unknown
$Types .= 'b';
$Statment->bind_param($Types ,$Params);
}
return $Statment;
}
How to put link in modal message box with a unique ID
How to put link in modal message box with a unique ID
I have this link before with normal confirmation to delete a user (a
common prompt that pop up in the browser)
function cancel() {
var msg = "Are you sure you want to cancel?";
var answer = confirm(msg);
if (answer){
document.frm.submit();
return false;
}
}
<td><a href="cancelations/cancelreservation.php?ip_cancelID=<?php echo
$iprow['ReserveID']; ?>" onclick="cancel(); return false"><img
src="../images/customerImages/cancel.png" style="width:80px;"/></a></td>
I have searched for some modal confirmation box to remove a user by its
unique ID and I changed my above code to this:
function removeUser(id){
var txt = 'Are you sure you want to remove this user?<input
type="hidden" id="userid" name="userid" value="'+ id +'" />';
$.prompt(txt,{
buttons:{Delete:true, Cancel:false},
close: function(e,v,m,f){
if(v){
var uid = f.userid;
//$.post('removeuser.php',{userid:f.userid},
callback:function(data){
// if(data == 'true'){
$('#userid'+uid).hide('slow', function(){
$(this).remove(); });
// }else{ $.prompt('An Error Occured while
removing this user'); }
//});
}
else{}
}
});
}
<td><a href="cancelations/cancelreservation.php?ica_cancelID=<?php echo
$icarow['ReserveID']; ?>" class="deleteuser" onclick="removeUser(1);"><img
src="../images/customerImages/cancel.png" style="width:80px;"/></a></td>
There is a problem inside the , the when I click it the modal shows but
the page loads and go to the link (the link is where the process of
deleting the user/data) without clicking any of the buttons in the modal
so I change it to this:
<td><a href="javascript:;"><img src="../images/customerImages/cancel.png"
style="width:80px;" class="deleteuser" onclick="removeUser(1);"/></a></td>
I got rid the link now the problem is how can I go to this link
"cancelations/cancelreservation.php"?ica_cancelID with this ID
$icarow['ReserveID']; in function removeUser(id) ???
Please help my mind is still dumb in javascript/jquery syntax and this is
my first time using modals
I have this link before with normal confirmation to delete a user (a
common prompt that pop up in the browser)
function cancel() {
var msg = "Are you sure you want to cancel?";
var answer = confirm(msg);
if (answer){
document.frm.submit();
return false;
}
}
<td><a href="cancelations/cancelreservation.php?ip_cancelID=<?php echo
$iprow['ReserveID']; ?>" onclick="cancel(); return false"><img
src="../images/customerImages/cancel.png" style="width:80px;"/></a></td>
I have searched for some modal confirmation box to remove a user by its
unique ID and I changed my above code to this:
function removeUser(id){
var txt = 'Are you sure you want to remove this user?<input
type="hidden" id="userid" name="userid" value="'+ id +'" />';
$.prompt(txt,{
buttons:{Delete:true, Cancel:false},
close: function(e,v,m,f){
if(v){
var uid = f.userid;
//$.post('removeuser.php',{userid:f.userid},
callback:function(data){
// if(data == 'true'){
$('#userid'+uid).hide('slow', function(){
$(this).remove(); });
// }else{ $.prompt('An Error Occured while
removing this user'); }
//});
}
else{}
}
});
}
<td><a href="cancelations/cancelreservation.php?ica_cancelID=<?php echo
$icarow['ReserveID']; ?>" class="deleteuser" onclick="removeUser(1);"><img
src="../images/customerImages/cancel.png" style="width:80px;"/></a></td>
There is a problem inside the , the when I click it the modal shows but
the page loads and go to the link (the link is where the process of
deleting the user/data) without clicking any of the buttons in the modal
so I change it to this:
<td><a href="javascript:;"><img src="../images/customerImages/cancel.png"
style="width:80px;" class="deleteuser" onclick="removeUser(1);"/></a></td>
I got rid the link now the problem is how can I go to this link
"cancelations/cancelreservation.php"?ica_cancelID with this ID
$icarow['ReserveID']; in function removeUser(id) ???
Please help my mind is still dumb in javascript/jquery syntax and this is
my first time using modals
local URLs in RichTextBox
local URLs in RichTextBox
I have a TextBox where I can send data to some RichTextBox. When I type
something like file:///FilePath1/FilePath2/FileName3.txt, send to
RichTextBox and click on the link (LinkClicked Event) it works and I can
open the file but if some FilePath has spaces (for exemple file:///File
Path1/FilePath 2/FileName3.txt) it doesn't works.
I tryed
string myString = myString.FileName;
myString = myString.Replace(" ", "%20"); // '%20' not accepted because it
// changes the
FileName
and
Uri myLink = new Uri(myString );
but it's still not working. Any sugestion?
I have a TextBox where I can send data to some RichTextBox. When I type
something like file:///FilePath1/FilePath2/FileName3.txt, send to
RichTextBox and click on the link (LinkClicked Event) it works and I can
open the file but if some FilePath has spaces (for exemple file:///File
Path1/FilePath 2/FileName3.txt) it doesn't works.
I tryed
string myString = myString.FileName;
myString = myString.Replace(" ", "%20"); // '%20' not accepted because it
// changes the
FileName
and
Uri myLink = new Uri(myString );
but it's still not working. Any sugestion?
php while loop not showing results
php while loop not showing results
Can someone please point out what I'm sure is a stupidly obvious error in
my code? The string "string" in my while loop is displaying the correct
amount of times but not the results in row[0].
if (!isset($_GET['city']) & !isset($_GET['county'])) {
$getResults = "SELECT DISTINCT region FROM `locations` WHERE country =
'England'";
echo "No region or county set";
if ($result = $mysqli->query($getResults)) {
echo "Found results";
while ($row = $result->fetch_assoc()) {
echo "string";
echo $row[0];
}
}
}
Can someone please point out what I'm sure is a stupidly obvious error in
my code? The string "string" in my while loop is displaying the correct
amount of times but not the results in row[0].
if (!isset($_GET['city']) & !isset($_GET['county'])) {
$getResults = "SELECT DISTINCT region FROM `locations` WHERE country =
'England'";
echo "No region or county set";
if ($result = $mysqli->query($getResults)) {
echo "Found results";
while ($row = $result->fetch_assoc()) {
echo "string";
echo $row[0];
}
}
}
Pyramid Script using PasteDeploy Pipeline not working
Pyramid Script using PasteDeploy Pipeline not working
Hello here's my new trouble... i'm using pyramid and i have created a
script to fill my db with initial data
I have a PasteDeploy configuration file (say development.ini) with this
syntax
###
# app configuration
#
http://docs.pylonsproject.org/projects/pyramid/en/latest/narr/environment.html
###
[app:shop_eshop]
use = egg:shop_eshop
pyramid.reload_templates = true
pyramid.debug_authorization = false
pyramid.debug_notfound = false
pyramid.debug_routematch = false
pyramid.default_locale_name = en
pyramid.includes =
pyramid_debugtoolbar
pyramid_tm
sqlalchemy.url = postgresql://eshop_db_user:testtest@localhost:5432/eshop_db
jinja2.directories = eshop:templates
ziggurat_foundations.model_locations.User = auth.models:User
# SESSION_BEAKER
session.type = file
session.data_dir = %(here)s/data/sessions/data
session.lock_dir = %(here)s/data/sessions/lock
session.key = s_key
session.secret = ...FBIRootAccessPW...
session.cookie_on_exception = true
[filter:fanstatic]
use = egg:fanstatic#fanstatic
recompute_hashes = false
versioning = true
bottom = True
publisher_signature = assets
compile = true
#in development
debug = true
[pipeline:main]
pipeline = fanstatic eshop
[server:main]
use = egg:waitress#main
host = 0.0.0.0
port = 6543
###
# logging configuration
# http://docs.pylonsproject.org/projects/pyramid/en/latest/narr/logging.html
###
[loggers]
keys = root, shop_eshop, sqlalchemy
[handlers]
keys = console
[formatters]
keys = generic
[logger_root]
level = INFO
handlers = console
[logger_shop_eshop]
level = DEBUG
handlers =
qualname = shop_eshop
[logger_sqlalchemy]
level = INFO
handlers =
qualname = sqlalchemy.engine
[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic
[formatter_generic]
format = %(asctime)s %(levelname)-5.5s [%(name)s][%(threadName)s] %(message)s
My script contains this piece of code that generates the error..
def main(argv=sys.argv):
if len(argv) < 2:
usage(argv)
config_uri = argv[1]
options = parse_vars(argv[2:])
setup_logging(config_uri)
settings = get_appsettings(config_uri, options=options)
engine = engine_from_config(settings, 'sqlalchemy.')
DBSession.configure(bind=engine)
with transaction.manager:
create_groups()
create_users()
The error is thrown by this line
engine = engine_from_config(settings, 'sqlalchemy.')
If i remove the pipeline everything works correctly, i can't find a way to
read the pipeline.
Any suggestion? Thank you!
Hello here's my new trouble... i'm using pyramid and i have created a
script to fill my db with initial data
I have a PasteDeploy configuration file (say development.ini) with this
syntax
###
# app configuration
#
http://docs.pylonsproject.org/projects/pyramid/en/latest/narr/environment.html
###
[app:shop_eshop]
use = egg:shop_eshop
pyramid.reload_templates = true
pyramid.debug_authorization = false
pyramid.debug_notfound = false
pyramid.debug_routematch = false
pyramid.default_locale_name = en
pyramid.includes =
pyramid_debugtoolbar
pyramid_tm
sqlalchemy.url = postgresql://eshop_db_user:testtest@localhost:5432/eshop_db
jinja2.directories = eshop:templates
ziggurat_foundations.model_locations.User = auth.models:User
# SESSION_BEAKER
session.type = file
session.data_dir = %(here)s/data/sessions/data
session.lock_dir = %(here)s/data/sessions/lock
session.key = s_key
session.secret = ...FBIRootAccessPW...
session.cookie_on_exception = true
[filter:fanstatic]
use = egg:fanstatic#fanstatic
recompute_hashes = false
versioning = true
bottom = True
publisher_signature = assets
compile = true
#in development
debug = true
[pipeline:main]
pipeline = fanstatic eshop
[server:main]
use = egg:waitress#main
host = 0.0.0.0
port = 6543
###
# logging configuration
# http://docs.pylonsproject.org/projects/pyramid/en/latest/narr/logging.html
###
[loggers]
keys = root, shop_eshop, sqlalchemy
[handlers]
keys = console
[formatters]
keys = generic
[logger_root]
level = INFO
handlers = console
[logger_shop_eshop]
level = DEBUG
handlers =
qualname = shop_eshop
[logger_sqlalchemy]
level = INFO
handlers =
qualname = sqlalchemy.engine
[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic
[formatter_generic]
format = %(asctime)s %(levelname)-5.5s [%(name)s][%(threadName)s] %(message)s
My script contains this piece of code that generates the error..
def main(argv=sys.argv):
if len(argv) < 2:
usage(argv)
config_uri = argv[1]
options = parse_vars(argv[2:])
setup_logging(config_uri)
settings = get_appsettings(config_uri, options=options)
engine = engine_from_config(settings, 'sqlalchemy.')
DBSession.configure(bind=engine)
with transaction.manager:
create_groups()
create_users()
The error is thrown by this line
engine = engine_from_config(settings, 'sqlalchemy.')
If i remove the pipeline everything works correctly, i can't find a way to
read the pipeline.
Any suggestion? Thank you!
Trouble on creating a JSON Object on Android
Trouble on creating a JSON Object on Android
I'm having a provblem on creating a JSON object on android app.
I's getting a JSON array like :
[{"estado":"1","longitude":"19.1714172","latitude":"-8.9477729"},{"estado":"1","longitude":"37.1714681","latitude":"-8.9476652"}]
from the server (using a servlet)!
But when i try to access the array objects on a for cicle like:
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
//the rest of code
}
my app gives some error, and simple stop (something like an ANR! i'm not
sure about this).
Can anyone help, please?!
I'm having a provblem on creating a JSON object on android app.
I's getting a JSON array like :
[{"estado":"1","longitude":"19.1714172","latitude":"-8.9477729"},{"estado":"1","longitude":"37.1714681","latitude":"-8.9476652"}]
from the server (using a servlet)!
But when i try to access the array objects on a for cicle like:
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
//the rest of code
}
my app gives some error, and simple stop (something like an ANR! i'm not
sure about this).
Can anyone help, please?!
Android> file vs SQLite
Android> file vs SQLite
I have to save my application's settings, but I don't know if I should use
a file or a table. I don't need to share them with other application and
these settings are just 3-4 booleans used to remember the application to
execute an action in a way or in another one. Is it a good idea to create
a table just for 3-4 values? Or should I use a file instead small?
I have to save my application's settings, but I don't know if I should use
a file or a table. I don't need to share them with other application and
these settings are just 3-4 booleans used to remember the application to
execute an action in a way or in another one. Is it a good idea to create
a table just for 3-4 values? Or should I use a file instead small?
Wordpress JW player not functioning correctly
Wordpress JW player not functioning correctly
I am trying to add a vimeo video using external media in wordpress and the
video link is http://vimeo.com/74626703 but its showing as Error loading
player: No media sources found so what should i do please help.
I am trying to add a vimeo video using external media in wordpress and the
video link is http://vimeo.com/74626703 but its showing as Error loading
player: No media sources found so what should i do please help.
Tuesday, 17 September 2013
iOS - Best way run repeated task while app is active
iOS - Best way run repeated task while app is active
I want to run a task in the background while app is active and running.
The task should be executed repeatedly in every 2 minutes or so. If the
application is inactive then the 'background repeated task' should be
paused and it should continue if the app is active again. What is the best
way to do this ? Please help.
I want to run a task in the background while app is active and running.
The task should be executed repeatedly in every 2 minutes or so. If the
application is inactive then the 'background repeated task' should be
paused and it should continue if the app is active again. What is the best
way to do this ? Please help.
How to update Aptana Eclipse Plug-in Pydev version?
How to update Aptana Eclipse Plug-in Pydev version?
I'm using Eclipse with Aptana Eclipse Plug-in version 3.4.2 but the Pydev
version that comes with the plug-in is an old version 2.7.0. When will
Aptana update Pydev version or is there a way I can update the Aptana
Eclipse Plug-in, Pydev version 2.8.2 myself ???
FYI: Eclipse check for updates does not update.
Thank you for any suggestions.
I'm using Eclipse with Aptana Eclipse Plug-in version 3.4.2 but the Pydev
version that comes with the plug-in is an old version 2.7.0. When will
Aptana update Pydev version or is there a way I can update the Aptana
Eclipse Plug-in, Pydev version 2.8.2 myself ???
FYI: Eclipse check for updates does not update.
Thank you for any suggestions.
Core Data Set Relationship from Inverse
Core Data Set Relationship from Inverse
I have a bunch of code that sets Core Data relationships via the inverse
instead of the "addWhateverObject" methods. This usually works well in all
of my applications, but I have one app where the relationships are being
lost when the NSManagedObject context is being saved.
My question is setting a relationship in Core Data via the relationship's
inverse valid or do you have to use the accessor methods to add objects to
the relationship?
Thanks!
I have a bunch of code that sets Core Data relationships via the inverse
instead of the "addWhateverObject" methods. This usually works well in all
of my applications, but I have one app where the relationships are being
lost when the NSManagedObject context is being saved.
My question is setting a relationship in Core Data via the relationship's
inverse valid or do you have to use the accessor methods to add objects to
the relationship?
Thanks!
How to get browser 's download dialog given the url of file
How to get browser 's download dialog given the url of file
My requirement is to download a file when "Download" button is clicked.
Service is giving me the url of the file. I used window.location but it is
replacing my page. I just want the default download dialog provided by
browser. How do I get that? I am getting a string (file location) from
service, not the file. I am using jQuery.
My requirement is to download a file when "Download" button is clicked.
Service is giving me the url of the file. I used window.location but it is
replacing my page. I just want the default download dialog provided by
browser. How do I get that? I am getting a string (file location) from
service, not the file. I am using jQuery.
How to delay successive iterations of a loop in MOAI?
How to delay successive iterations of a loop in MOAI?
I want to delay successive iteration of a loop in MOAI. I've tried using a
timer to delay calling the loop, and putting an empty loop inside my main
loop. In the latter case, it just goes through all iterations of the inner
loop before proceeding to the outer loop. The result is, it stops at the
first iteration of the main loop, then goes through the inner loop, and
then finally executes the the main loop. How do I stop it from happening?
I want to delay successive iteration of a loop in MOAI. I've tried using a
timer to delay calling the loop, and putting an empty loop inside my main
loop. In the latter case, it just goes through all iterations of the inner
loop before proceeding to the outer loop. The result is, it stops at the
first iteration of the main loop, then goes through the inner loop, and
then finally executes the the main loop. How do I stop it from happening?
Reading cross domain csv file using JSONP and AJAX
Reading cross domain csv file using JSONP and AJAX
Trying to read cross domain csv file
remote_url =
"http://www.example.com/buglist.cgi?bug_status=NEW&columnlist=bug_id%2Cshort_desc&query_format=advanced&ctype=csv";
$.ajax({
url:remote_url,
type:"get",
cache: false,
dataType: "jsonp",
success:function(data){
console.log(data);
},
error: function(data){
console.log(data);
}
});
Although getting 200 status from server, It always going into error
callback handler and logging javascript syntax error
SyntaxError: missing ; before statement 6230,"this is a ""short
description"", blah blah blah..
My csv file has two columns "bug_id" and "short_desc" with following
values bug_id = 6230 short_desc = this is a "short description", blah blah
blah..
I know the error is because of double quote in description, but I don't
know the solution. Tried "YQL" to convert csv to json but it returned null
as a result, may be because of error. Thanks,
Trying to read cross domain csv file
remote_url =
"http://www.example.com/buglist.cgi?bug_status=NEW&columnlist=bug_id%2Cshort_desc&query_format=advanced&ctype=csv";
$.ajax({
url:remote_url,
type:"get",
cache: false,
dataType: "jsonp",
success:function(data){
console.log(data);
},
error: function(data){
console.log(data);
}
});
Although getting 200 status from server, It always going into error
callback handler and logging javascript syntax error
SyntaxError: missing ; before statement 6230,"this is a ""short
description"", blah blah blah..
My csv file has two columns "bug_id" and "short_desc" with following
values bug_id = 6230 short_desc = this is a "short description", blah blah
blah..
I know the error is because of double quote in description, but I don't
know the solution. Tried "YQL" to convert csv to json but it returned null
as a result, may be because of error. Thanks,
Sunday, 15 September 2013
AutoHotKey (AHK) How to make wait for a command to finish before destroying GUI
AutoHotKey (AHK) How to make wait for a command to finish before
destroying GUI
Gui, Add, Button, w%buttonWidth% r%buttonHeight% gbutton1, &1. %var1%
button1:
WinActivate [title]
send %var1%
Gui Destroy
return
Currently when I press 1, the Gui is closed before it can type the
variable. How do I either get it to type fast enough that I don't need to
worry, or get it to wait for it to finish before closing?
destroying GUI
Gui, Add, Button, w%buttonWidth% r%buttonHeight% gbutton1, &1. %var1%
button1:
WinActivate [title]
send %var1%
Gui Destroy
return
Currently when I press 1, the Gui is closed before it can type the
variable. How do I either get it to type fast enough that I don't need to
worry, or get it to wait for it to finish before closing?
OCaml constructor error
OCaml constructor error
I am trying to create a function for object creation, and I am receiving a
very generic Error: Syntax error on the function. The class:
class dataframe csv_file =
object
val mutable csv = csv_file
end
The function to create the object:
let import_data dataframe_name filepath =
let dataframe_name = new dataframe (Csv.load file);;
note: (Csv.load file) returns the user defined type t : string list list
however I don't see this as being a problem since csv_file is polymorphic.
I am trying to create a function for object creation, and I am receiving a
very generic Error: Syntax error on the function. The class:
class dataframe csv_file =
object
val mutable csv = csv_file
end
The function to create the object:
let import_data dataframe_name filepath =
let dataframe_name = new dataframe (Csv.load file);;
note: (Csv.load file) returns the user defined type t : string list list
however I don't see this as being a problem since csv_file is polymorphic.
Convert contenteditable div's content to plaintext via javascript
Convert contenteditable div's content to plaintext via javascript
I'm trying to make custom lightweight rich text editor with just one
feature - adding links. I did some research and desided iframe is the best
choice. After some messing around it works with one exception - I need to
run some code on keyup event. I read everything I found on the internet
and nothing helped, still doesn't work...
iframe.document.designMode = 'On';
iframe.document.open();
iframe.document.write(someHTML);
iframe.document.close();
var keyupHandle = function() { /* some code */ };
var iframeDoc = document.getElementById('iframe').contentWindow.document;
if(iframeDoc.addEventListener) {
iframeDoc.addEventListener('keyup', keyupHandle(), true);
} else {
iframeDoc.attachEvent('onkeyup', keyupHandle());
}
I'm trying to make custom lightweight rich text editor with just one
feature - adding links. I did some research and desided iframe is the best
choice. After some messing around it works with one exception - I need to
run some code on keyup event. I read everything I found on the internet
and nothing helped, still doesn't work...
iframe.document.designMode = 'On';
iframe.document.open();
iframe.document.write(someHTML);
iframe.document.close();
var keyupHandle = function() { /* some code */ };
var iframeDoc = document.getElementById('iframe').contentWindow.document;
if(iframeDoc.addEventListener) {
iframeDoc.addEventListener('keyup', keyupHandle(), true);
} else {
iframeDoc.attachEvent('onkeyup', keyupHandle());
}
IndexError: string index out of range(str1[-1])
IndexError: string index out of range(str1[-1])
Here is my function:
def find_last(str1):
return str1[-1]
When i run it:
print find_last('aaaa')
I have the following error:
return str1[-1]
IndexError: string index out of range
How can I fix this?
Thanks.
Here is my function:
def find_last(str1):
return str1[-1]
When i run it:
print find_last('aaaa')
I have the following error:
return str1[-1]
IndexError: string index out of range
How can I fix this?
Thanks.
LineCommentPrefix doenst work (ScintillaNET)
LineCommentPrefix doenst work (ScintillaNET)
The LineCommentPrefix doenst work. Why?
editor.Lexing.Lexer = ScintillaNET.Lexer.Cpp;
editor.Lexing.Keywords[0] = "for while do stock public forward if
else return new break continue false true stock case enum switch
sizeof goto default";
editor.Lexing.Keywords[1] = "Float bool";
editor.Lexing.LineCommentPrefix = "//";
editor.Lexing.StreamCommentPrefix = "/*";
editor.Lexing.StreamCommentSufix = "*/";
editor.Styles[editor.Lexing.StyleNameMap["DOCUMENT_DEFAULT"]].ForeColor
= System.Drawing.Color.Black; // DEFAULT CHAR
editor.Styles[editor.Lexing.StyleNameMap["NUMBER"]].ForeColor =
System.Drawing.Color.SteelBlue; // NUMBER
editor.Styles[editor.Lexing.StyleNameMap["WORD"]].ForeColor =
System.Drawing.Color.Blue;
editor.Styles[editor.Lexing.StyleNameMap["WORD"]].Bold = true; //
new usw.
editor.Styles[editor.Lexing.StyleNameMap["WORD2"]].ForeColor =
System.Drawing.Color.Purple; // Flaot, Bool
editor.Styles[editor.Lexing.StyleNameMap["STRING"]].ForeColor =
System.Drawing.Color.Red; // String
editor.Styles[editor.Lexing.StyleNameMap["CHARACTER"]].ForeColor =
System.Drawing.Color.Red; // Char
editor.Styles[editor.Lexing.StyleNameMap["PREPROCESSOR"]].ForeColor
= System.Drawing.Color.Brown; // #define usw
editor.Styles[editor.Lexing.StyleNameMap["OPERATOR"]].ForeColor =
System.Drawing.Color.Black; // + - / *
editor.Styles[editor.Lexing.StyleNameMap["IDENTIFIER"]].ForeColor
= System.Drawing.Color.Black;
editor.Styles[editor.Lexing.StyleNameMap["COMMENT"]].ForeColor =
System.Drawing.Color.Green;
It dont't geht marked green. Please help me. - Timo
The LineCommentPrefix doenst work. Why?
editor.Lexing.Lexer = ScintillaNET.Lexer.Cpp;
editor.Lexing.Keywords[0] = "for while do stock public forward if
else return new break continue false true stock case enum switch
sizeof goto default";
editor.Lexing.Keywords[1] = "Float bool";
editor.Lexing.LineCommentPrefix = "//";
editor.Lexing.StreamCommentPrefix = "/*";
editor.Lexing.StreamCommentSufix = "*/";
editor.Styles[editor.Lexing.StyleNameMap["DOCUMENT_DEFAULT"]].ForeColor
= System.Drawing.Color.Black; // DEFAULT CHAR
editor.Styles[editor.Lexing.StyleNameMap["NUMBER"]].ForeColor =
System.Drawing.Color.SteelBlue; // NUMBER
editor.Styles[editor.Lexing.StyleNameMap["WORD"]].ForeColor =
System.Drawing.Color.Blue;
editor.Styles[editor.Lexing.StyleNameMap["WORD"]].Bold = true; //
new usw.
editor.Styles[editor.Lexing.StyleNameMap["WORD2"]].ForeColor =
System.Drawing.Color.Purple; // Flaot, Bool
editor.Styles[editor.Lexing.StyleNameMap["STRING"]].ForeColor =
System.Drawing.Color.Red; // String
editor.Styles[editor.Lexing.StyleNameMap["CHARACTER"]].ForeColor =
System.Drawing.Color.Red; // Char
editor.Styles[editor.Lexing.StyleNameMap["PREPROCESSOR"]].ForeColor
= System.Drawing.Color.Brown; // #define usw
editor.Styles[editor.Lexing.StyleNameMap["OPERATOR"]].ForeColor =
System.Drawing.Color.Black; // + - / *
editor.Styles[editor.Lexing.StyleNameMap["IDENTIFIER"]].ForeColor
= System.Drawing.Color.Black;
editor.Styles[editor.Lexing.StyleNameMap["COMMENT"]].ForeColor =
System.Drawing.Color.Green;
It dont't geht marked green. Please help me. - Timo
Invalid attempt to call MetaData when reader is closed exception
Invalid attempt to call MetaData when reader is closed exception
I am using Microsoft Practice Enterprice data to connect a WCF to
database(s). Notice that this exception is not thrown always. It's
happening inside the while statement. Then if I refresh the page (resubmit
the login details, MVC app that communicate with this WCF service), the
code execute without any problem. Can someone determine why the IDataRader
is closed while the stack execution is in the using statement? My code is:
public class LoginService : ILoginService
{
public Attendee CheckLoginCredentials(string username, string
password, int databaseId)
{
Database db = DataBaseConnection.GetDatabaseObject(eventId);
Attendee attendee = new Attendee();
try
{
DbCommand dbCommandWrapper =
db.GetStoredProcCommand("Check_login_WCF");
db.AddInParameter(dbCommandWrapper, "@Username",
DbType.String, username);
db.AddInParameter(dbCommandWrapper, "@Password",
DbType.String, password);
using (IDataReader dataReader =
db.ExecuteReader(dbCommandWrapper))
{
while (dataReader.Read())
{
if
(!dataReader.IsDBNull(dataReader.GetOrdinal("PersonId")))
attendee.PersonId =
dataReader.GetGuid(dataReader.GetOrdinal("PersonId"));
if
(!dataReader.IsDBNull(dataReader.GetOrdinal("CompanyId")))
attendee.CompanyId =
dataReader.GetGuid(dataReader.GetOrdinal("CompanyId"));
if
(!dataReader.IsDBNull(dataReader.GetOrdinal("FullName")))
attendee.FullName =
dataReader.GetString(dataReader.GetOrdinal("FullName"));
if
(!dataReader.IsDBNull(dataReader.GetOrdinal("UserName")))
attendee.UserName =
dataReader.GetString(dataReader.GetOrdinal("UserName"));
if
(!dataReader.IsDBNull(dataReader.GetOrdinal("IsValid")))
attendee.ValidCredentials =
dataReader.GetBoolean(dataReader.GetOrdinal("ValidCredentials"));
}
}
}
catch (Exception ex)
{
return null;
}
return attendee;
}
}
DataBaseConnection:
public static Database GetDatabaseObject(int databaseId)
{
string eventConnectionString = string.Empty;
eventConnectionString = EventDatabases.GetConnectionString(databaseId);
Database mydb = new
Microsoft.Practices.EnterpriseLibrary.Data.Sql.SqlDatabase(eventConnectionString);
return mydb;
}
I am using Microsoft Practice Enterprice data to connect a WCF to
database(s). Notice that this exception is not thrown always. It's
happening inside the while statement. Then if I refresh the page (resubmit
the login details, MVC app that communicate with this WCF service), the
code execute without any problem. Can someone determine why the IDataRader
is closed while the stack execution is in the using statement? My code is:
public class LoginService : ILoginService
{
public Attendee CheckLoginCredentials(string username, string
password, int databaseId)
{
Database db = DataBaseConnection.GetDatabaseObject(eventId);
Attendee attendee = new Attendee();
try
{
DbCommand dbCommandWrapper =
db.GetStoredProcCommand("Check_login_WCF");
db.AddInParameter(dbCommandWrapper, "@Username",
DbType.String, username);
db.AddInParameter(dbCommandWrapper, "@Password",
DbType.String, password);
using (IDataReader dataReader =
db.ExecuteReader(dbCommandWrapper))
{
while (dataReader.Read())
{
if
(!dataReader.IsDBNull(dataReader.GetOrdinal("PersonId")))
attendee.PersonId =
dataReader.GetGuid(dataReader.GetOrdinal("PersonId"));
if
(!dataReader.IsDBNull(dataReader.GetOrdinal("CompanyId")))
attendee.CompanyId =
dataReader.GetGuid(dataReader.GetOrdinal("CompanyId"));
if
(!dataReader.IsDBNull(dataReader.GetOrdinal("FullName")))
attendee.FullName =
dataReader.GetString(dataReader.GetOrdinal("FullName"));
if
(!dataReader.IsDBNull(dataReader.GetOrdinal("UserName")))
attendee.UserName =
dataReader.GetString(dataReader.GetOrdinal("UserName"));
if
(!dataReader.IsDBNull(dataReader.GetOrdinal("IsValid")))
attendee.ValidCredentials =
dataReader.GetBoolean(dataReader.GetOrdinal("ValidCredentials"));
}
}
}
catch (Exception ex)
{
return null;
}
return attendee;
}
}
DataBaseConnection:
public static Database GetDatabaseObject(int databaseId)
{
string eventConnectionString = string.Empty;
eventConnectionString = EventDatabases.GetConnectionString(databaseId);
Database mydb = new
Microsoft.Practices.EnterpriseLibrary.Data.Sql.SqlDatabase(eventConnectionString);
return mydb;
}
JavaME read an input from a textfild and display it in another textfield
JavaME read an input from a textfild and display it in another textfield
I have read a value from a text box and I wanted to display it in another
text box, how do I do it, a piece of code will be help ful.
One more thing is I want to do the same thing as above but via a button
Thankyou!
I have read a value from a text box and I wanted to display it in another
text box, how do I do it, a piece of code will be help ful.
One more thing is I want to do the same thing as above but via a button
Thankyou!
Saturday, 14 September 2013
Python - how to load Google Chrome or Chromium browser in the gtk.Window like webkit.WebView()?
Python - how to load Google Chrome or Chromium browser in the gtk.Window
like webkit.WebView()?
In Python (Linux), how can i load the Google chrome or Chromium browser
inside a gtk.Window()?
Where i am using now as webkit but instead of the webkit i need to use
Google Chrome/Chromium because of the Javscript engine and other update
issues.
$ apt-get install python-webkit
$ cat >> /var/tmp/browser.py << \EOF
#!/usr/bin/env python
import gtk
import webkit
import gobject
gobject.threads_init()
win = gtk.Window()
win.set_title("Python Browser")
bro = webkit.WebView()
bro.open("http://www.google.com")
win.add(bro)
win.show_all()
gtk.main()
EOF
$ python /var/tmp/browser.py
like webkit.WebView()?
In Python (Linux), how can i load the Google chrome or Chromium browser
inside a gtk.Window()?
Where i am using now as webkit but instead of the webkit i need to use
Google Chrome/Chromium because of the Javscript engine and other update
issues.
$ apt-get install python-webkit
$ cat >> /var/tmp/browser.py << \EOF
#!/usr/bin/env python
import gtk
import webkit
import gobject
gobject.threads_init()
win = gtk.Window()
win.set_title("Python Browser")
bro = webkit.WebView()
bro.open("http://www.google.com")
win.add(bro)
win.show_all()
gtk.main()
EOF
$ python /var/tmp/browser.py
Video player control panel ? JavaFX
Video player control panel ? JavaFX
I want to disappear video player control panel when the mouse is not
moved. I wrote the following codes for detecting the mouse movement but ý
did not applied on my control panel.
gp.setOnMouseDragOver(new EventHandler<MouseDragEvent>() {
@Override
public void handle(MouseDragEvent mouseDragEvent) {
FadeTransition f
= new FadeTransition(Duration.millis(5000),openButton );
f.setFromValue(0.0);
f.setFromValue(0);
f.play();
FadeTransition f1
= new FadeTransition(Duration.millis(5000),volLow );
f1.setFromValue(0.0);
f1.setFromValue(0);
f1.play();
FadeTransition f2
= new FadeTransition(Duration.millis(5000),volHigh );
f2.setFromValue(0.0);
f2.setFromValue(0);
f2.play();
FadeTransition f3
= new
FadeTransition(Duration.millis(5000),volumeSlider );
f3.setFromValue(0.0);
f3.setFromValue(0);
f3.play();
FadeTransition f4
= new
FadeTransition(Duration.millis(5000),controlPanel );
f4.setFromValue(0.0);
f4.setFromValue(0);
f4.play();
FadeTransition f5
= new FadeTransition(Duration.millis(5000),statusLabel );
f5.setFromValue(0.0);
f5.setFromValue(0);
f5.play();
FadeTransition f6
= new
FadeTransition(Duration.millis(5000),currentTimeLabel
);
f6.setFromValue(0.0);
f6.setFromValue(0);
f6.play();
FadeTransition f7
= new
FadeTransition(Duration.millis(5000),positionSlider );
f7.setFromValue(0.0);
f7.setFromValue(0);
f7.play();
FadeTransition f8
= new
FadeTransition(Duration.millis(5000),totalDurationLabel
);
f8.setFromValue(0.0);
f8.setFromValue(0);
f8.play();
FadeTransition f9
= new FadeTransition(Duration.millis(5000),eqButton );
f9.setFromValue(0.0);
f9.setFromValue(0);
f9.play();
}
});
gp.setOnMouseMoved(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent mouseEvent) {
FadeTransition f
= new FadeTransition(Duration.millis(3000),openButton);
f.setFromValue(9.0);
f.setToValue(0.0);
f.play();
FadeTransition f1
= new FadeTransition(Duration.millis(3000),volLow);
f1.setFromValue(9.0);
f1.setToValue(0.0);
f1.play();
FadeTransition f2
= new FadeTransition(Duration.millis(3000),volHigh);
f2.setFromValue(9.0);
f2.setToValue(0.0);
f2.play();
FadeTransition f3
= new FadeTransition(Duration.millis(3000),volumeSlider);
f3.setFromValue(9.0);
f3.setToValue(0.0);
f3.play();
FadeTransition f4
= new FadeTransition(Duration.millis(3000),controlPanel);
f4.setFromValue(9.0);
f4.setToValue(0.0);
f4.play();
FadeTransition f5
= new FadeTransition(Duration.millis(3000),statusLabel);
f5.setFromValue(9.0);
f5.setToValue(0.0);
f5.play();
FadeTransition f6
= new
FadeTransition(Duration.millis(3000),currentTimeLabel);
f6.setFromValue(9.0);
f6.setToValue(0.0);
f6.play();
FadeTransition f7
= new
FadeTransition(Duration.millis(3000),positionSlider);
f7.setFromValue(9.0);
f7.setToValue(0.0);
f7.play();
FadeTransition f8
= new
FadeTransition(Duration.millis(3000),totalDurationLabel);
f8.setFromValue(9.0);
f8.setToValue(0.0);
f8.play();
FadeTransition f9
= new FadeTransition(Duration.millis(3000),eqButton);
f9.setFromValue(9.0);
f9.setToValue(0.0);
f9.play();
}
});
return gp;
In order to Detecting mouse movements i wrote the following codes but how
can ý applied both codes together.
public class Mouse {
public static void main(String[] args) throws InterruptedException{
int posx1;
int posx2;
int posy1;
int posy2;
while(true){
Thread.sleep(1);
posx2=MouseInfo.getPointerInfo().getLocation().x;
posy2=MouseInfo.getPointerInfo().getLocation().y;
Thread.sleep(100);
posx1=MouseInfo.getPointerInfo().getLocation().x;
posy1=MouseInfo.getPointerInfo().getLocation().y;
if(posx1==posx2&&posy1==posy2){
System.out.println("mouse hareket etmedi");
}
else{
System.out.println("HAREKET VAR");
}
}
}
}
I want to disappear video player control panel when the mouse is not
moved. I wrote the following codes for detecting the mouse movement but ý
did not applied on my control panel.
gp.setOnMouseDragOver(new EventHandler<MouseDragEvent>() {
@Override
public void handle(MouseDragEvent mouseDragEvent) {
FadeTransition f
= new FadeTransition(Duration.millis(5000),openButton );
f.setFromValue(0.0);
f.setFromValue(0);
f.play();
FadeTransition f1
= new FadeTransition(Duration.millis(5000),volLow );
f1.setFromValue(0.0);
f1.setFromValue(0);
f1.play();
FadeTransition f2
= new FadeTransition(Duration.millis(5000),volHigh );
f2.setFromValue(0.0);
f2.setFromValue(0);
f2.play();
FadeTransition f3
= new
FadeTransition(Duration.millis(5000),volumeSlider );
f3.setFromValue(0.0);
f3.setFromValue(0);
f3.play();
FadeTransition f4
= new
FadeTransition(Duration.millis(5000),controlPanel );
f4.setFromValue(0.0);
f4.setFromValue(0);
f4.play();
FadeTransition f5
= new FadeTransition(Duration.millis(5000),statusLabel );
f5.setFromValue(0.0);
f5.setFromValue(0);
f5.play();
FadeTransition f6
= new
FadeTransition(Duration.millis(5000),currentTimeLabel
);
f6.setFromValue(0.0);
f6.setFromValue(0);
f6.play();
FadeTransition f7
= new
FadeTransition(Duration.millis(5000),positionSlider );
f7.setFromValue(0.0);
f7.setFromValue(0);
f7.play();
FadeTransition f8
= new
FadeTransition(Duration.millis(5000),totalDurationLabel
);
f8.setFromValue(0.0);
f8.setFromValue(0);
f8.play();
FadeTransition f9
= new FadeTransition(Duration.millis(5000),eqButton );
f9.setFromValue(0.0);
f9.setFromValue(0);
f9.play();
}
});
gp.setOnMouseMoved(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent mouseEvent) {
FadeTransition f
= new FadeTransition(Duration.millis(3000),openButton);
f.setFromValue(9.0);
f.setToValue(0.0);
f.play();
FadeTransition f1
= new FadeTransition(Duration.millis(3000),volLow);
f1.setFromValue(9.0);
f1.setToValue(0.0);
f1.play();
FadeTransition f2
= new FadeTransition(Duration.millis(3000),volHigh);
f2.setFromValue(9.0);
f2.setToValue(0.0);
f2.play();
FadeTransition f3
= new FadeTransition(Duration.millis(3000),volumeSlider);
f3.setFromValue(9.0);
f3.setToValue(0.0);
f3.play();
FadeTransition f4
= new FadeTransition(Duration.millis(3000),controlPanel);
f4.setFromValue(9.0);
f4.setToValue(0.0);
f4.play();
FadeTransition f5
= new FadeTransition(Duration.millis(3000),statusLabel);
f5.setFromValue(9.0);
f5.setToValue(0.0);
f5.play();
FadeTransition f6
= new
FadeTransition(Duration.millis(3000),currentTimeLabel);
f6.setFromValue(9.0);
f6.setToValue(0.0);
f6.play();
FadeTransition f7
= new
FadeTransition(Duration.millis(3000),positionSlider);
f7.setFromValue(9.0);
f7.setToValue(0.0);
f7.play();
FadeTransition f8
= new
FadeTransition(Duration.millis(3000),totalDurationLabel);
f8.setFromValue(9.0);
f8.setToValue(0.0);
f8.play();
FadeTransition f9
= new FadeTransition(Duration.millis(3000),eqButton);
f9.setFromValue(9.0);
f9.setToValue(0.0);
f9.play();
}
});
return gp;
In order to Detecting mouse movements i wrote the following codes but how
can ý applied both codes together.
public class Mouse {
public static void main(String[] args) throws InterruptedException{
int posx1;
int posx2;
int posy1;
int posy2;
while(true){
Thread.sleep(1);
posx2=MouseInfo.getPointerInfo().getLocation().x;
posy2=MouseInfo.getPointerInfo().getLocation().y;
Thread.sleep(100);
posx1=MouseInfo.getPointerInfo().getLocation().x;
posy1=MouseInfo.getPointerInfo().getLocation().y;
if(posx1==posx2&&posy1==posy2){
System.out.println("mouse hareket etmedi");
}
else{
System.out.println("HAREKET VAR");
}
}
}
}
How to set an invisible title on UIButton?
How to set an invisible title on UIButton?
I'm working on an Ipad application, and i need to set a title on a
'UIButton', in order to could use :
-(void)MyMethod:(id)sender
{
UIButton *resultButton = (UIButton *)sender;
if ([resultButton.currentTitle isEqualToString:@"TitleName"])
{
...
}
}
But when I use this sort of code :
[MyUibutton setTitle:@"TitleName" forState:UIControlStateNormal];
It appears "TitleName" behind the image of the 'UIButton'...
So, is it possible to fix it ?
Thanks !
I'm working on an Ipad application, and i need to set a title on a
'UIButton', in order to could use :
-(void)MyMethod:(id)sender
{
UIButton *resultButton = (UIButton *)sender;
if ([resultButton.currentTitle isEqualToString:@"TitleName"])
{
...
}
}
But when I use this sort of code :
[MyUibutton setTitle:@"TitleName" forState:UIControlStateNormal];
It appears "TitleName" behind the image of the 'UIButton'...
So, is it possible to fix it ?
Thanks !
java.lang.ClassCastException: Compare cannot be cast to java.applet.Applet
java.lang.ClassCastException: Compare cannot be cast to java.applet.Applet
I was trying an example taken from here:
http://12inchpianist.com/2010/07/30/line-smoothing-in-java/ because is
helpful for a project that I am doing for a course at Universiry.
The problem is that when I try to run it (I did not change anything in the
code) it returns me this error message:
java.lang.ClassCastException: Compare cannot be cast to java.applet.Applet
at sun.applet.AppletPanel.createApplet(Unknown Source)
at sun.applet.AppletPanel.runLoader(Unknown Source)
at sun.applet.AppletPanel.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
So my questions are:
if you guys try to run the same code, do you get the same message?
how can I solve this error in order to be able to run the program?
Thanks a lot in advance!
I was trying an example taken from here:
http://12inchpianist.com/2010/07/30/line-smoothing-in-java/ because is
helpful for a project that I am doing for a course at Universiry.
The problem is that when I try to run it (I did not change anything in the
code) it returns me this error message:
java.lang.ClassCastException: Compare cannot be cast to java.applet.Applet
at sun.applet.AppletPanel.createApplet(Unknown Source)
at sun.applet.AppletPanel.runLoader(Unknown Source)
at sun.applet.AppletPanel.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
So my questions are:
if you guys try to run the same code, do you get the same message?
how can I solve this error in order to be able to run the program?
Thanks a lot in advance!
How can I get the (video) activities of a user with the YouTube API v3 in Java
How can I get the (video) activities of a user with the YouTube API v3 in
Java
I am using Java to get the activities of an authenticated User (OAuth2.0).
The Problem is, I am not getting the result I want. If I am visiting
youtube.com and look at the activities
(http://www.youtube.com/feed/subscriptions) there are a lot of videos.
If I am fetching the videos with
YouTube.Activities.List request = youtube.activities().list("snippet");
request.setHome(true);
request.setMaxResults(50L);
I get videos that are more than 10 hours old, even if there were 10 new
videos in the last 2 hours. The feed I am getting is not very new... And I
am only getting 24 entries, even if the maximum setting is on 50. With the
old YouTube Api (v2) I am getting more than 100 responses.
Is this just buggy and not working, or am I making mistakes?
Thanks in advance! :)
Java
I am using Java to get the activities of an authenticated User (OAuth2.0).
The Problem is, I am not getting the result I want. If I am visiting
youtube.com and look at the activities
(http://www.youtube.com/feed/subscriptions) there are a lot of videos.
If I am fetching the videos with
YouTube.Activities.List request = youtube.activities().list("snippet");
request.setHome(true);
request.setMaxResults(50L);
I get videos that are more than 10 hours old, even if there were 10 new
videos in the last 2 hours. The feed I am getting is not very new... And I
am only getting 24 entries, even if the maximum setting is on 50. With the
old YouTube Api (v2) I am getting more than 100 responses.
Is this just buggy and not working, or am I making mistakes?
Thanks in advance! :)
"Press Any Key to Continue" function in C
"Press Any Key to Continue" function in C
How do I create a void function that will work as "Press Any Key to
Continue" in C Programming?
What I want to do is:
printf("Let the Battle Begin!\n");
printf("Press Any Key to Continue\n");
//The Void Function Here
//Then I will call the function that will start the game
How do I create a void function that will work as "Press Any Key to
Continue" in C Programming?
What I want to do is:
printf("Let the Battle Begin!\n");
printf("Press Any Key to Continue\n");
//The Void Function Here
//Then I will call the function that will start the game
Failed to load Widgetsets in maven project in eclipse
Failed to load Widgetsets in maven project in eclipse
I have created a vaadin web application using maven in eclipse. In
particular I have used the archetype vaadin-archetype-touchkit as
described in the book of vaadin (20.3.4). Without making any change on the
default generated code I have run it with maven with goals clean package.
Then I compiled the Widgetset. When I try to run it on Tomcat 7, I receive
the strange message from the webpage:
Failed to load the WidgetSet:
<WidgetSet Path>.DefaultWidgetSet.nocache.js
On the console I see also the error messages:
INFO: Requested resource [/VAADIN/themes/reindeer/styles.css] not found
from filesystem or through class loader. Add widgetset and/or theme JAR to
your classpath or add files to WebContent/VAADIN folder.
INFO: Requested resource
[/VAADIN/widgetsets/com.vaadin.DefaultWidgetSet/com.vaadin.DefaultWidgetSet.nocache.js]
not found from filesystem or through class loader. Add widgetset and/or
theme JAR to your classpath or add files to WebContent/VAADIN folder.
INFO: Requested resource [/VAADIN/themes/reindeer/styles.css] not found
from filesystem or through class loader. Add widgetset and/or theme JAR to
your classpath or add files to WebContent/VAADIN folder.
It has struck me maven has not created a web.xml file, although I have
read in the tutorial that it is no more necessary in vaadin 7. I have read
the similar question where it is proposed that an adjustment in web.xml
file should be done. Should I infer that I have also to create a web.xml
file manually?
I find strange as well, that when I tried the same procedure with the
archetype for a typical vaadin 7 application, it runs properly. Since I
have to develop a touchkit-application I would appreciate any
suggestion-idea abut what could be missing on my original attempt.
I have created a vaadin web application using maven in eclipse. In
particular I have used the archetype vaadin-archetype-touchkit as
described in the book of vaadin (20.3.4). Without making any change on the
default generated code I have run it with maven with goals clean package.
Then I compiled the Widgetset. When I try to run it on Tomcat 7, I receive
the strange message from the webpage:
Failed to load the WidgetSet:
<WidgetSet Path>.DefaultWidgetSet.nocache.js
On the console I see also the error messages:
INFO: Requested resource [/VAADIN/themes/reindeer/styles.css] not found
from filesystem or through class loader. Add widgetset and/or theme JAR to
your classpath or add files to WebContent/VAADIN folder.
INFO: Requested resource
[/VAADIN/widgetsets/com.vaadin.DefaultWidgetSet/com.vaadin.DefaultWidgetSet.nocache.js]
not found from filesystem or through class loader. Add widgetset and/or
theme JAR to your classpath or add files to WebContent/VAADIN folder.
INFO: Requested resource [/VAADIN/themes/reindeer/styles.css] not found
from filesystem or through class loader. Add widgetset and/or theme JAR to
your classpath or add files to WebContent/VAADIN folder.
It has struck me maven has not created a web.xml file, although I have
read in the tutorial that it is no more necessary in vaadin 7. I have read
the similar question where it is proposed that an adjustment in web.xml
file should be done. Should I infer that I have also to create a web.xml
file manually?
I find strange as well, that when I tried the same procedure with the
archetype for a typical vaadin 7 application, it runs properly. Since I
have to develop a touchkit-application I would appreciate any
suggestion-idea abut what could be missing on my original attempt.
Friday, 13 September 2013
How can I change (and then reset) permissions for the root folder of my website?
How can I change (and then reset) permissions for the root folder of my
website?
Here is my scenario...
1) Website is written in classic ASP with SQL database.
2) The owner can add/edit/delete pages via the CMS.
3) Not wanting to give write permissions to the root folder, I have
created a folder /pages/ with write permissions.
4) When a new page is added, a folder is created in /pages/ and a master
Index.asp file is copied to that new folder via javascript FSO.
This generates a URL like this: http://mydomain.com/pages/about_me/
What I would like to do is...
1) Change the permissions on the root folder, but not any child folders or
files in the root,
2) Move the "master" file to the root using javascript FSO renaming it to
the selected name (ie: about_me.asp),
3) Finally, reset the the permissions on the root folder.
Is this at all possible?
If not, any suggestions would be greatly appreciated.
website?
Here is my scenario...
1) Website is written in classic ASP with SQL database.
2) The owner can add/edit/delete pages via the CMS.
3) Not wanting to give write permissions to the root folder, I have
created a folder /pages/ with write permissions.
4) When a new page is added, a folder is created in /pages/ and a master
Index.asp file is copied to that new folder via javascript FSO.
This generates a URL like this: http://mydomain.com/pages/about_me/
What I would like to do is...
1) Change the permissions on the root folder, but not any child folders or
files in the root,
2) Move the "master" file to the root using javascript FSO renaming it to
the selected name (ie: about_me.asp),
3) Finally, reset the the permissions on the root folder.
Is this at all possible?
If not, any suggestions would be greatly appreciated.
Trouble outputting multiple forms in one template
Trouble outputting multiple forms in one template
I have a user settings page with multiple editable and non-editable
components. Each editable component has its own form. All of the
components are displayed in a table, with the contents coming from a dict
on the model. For example:
class MyUser(models.AbstractBaseUser):
def get_settings(self):
return [
('Email Address',
{'value': self.email, 'editable': True, 'section':
'email', 'form': 'email_form'}
),
('Password',
{'value': '', 'editable': True, 'section': 'password',
'form': 'password_form'})]
I then have a form defined for each item in the settings, such as:
class ChangeEmailForm(models.ModelForm):
class Meta:
fields = ['email']
model = models.MyUser
email = forms.EmailField(widget =
forms.TextInput(attrs={'placeholder': 'Email Address'}))
All of the forms are handled by one view, and in that view they are
assigned a name, which matches the name in the settings data on the model:
def edit_settings_view(request, user):
if request.POST:
if 'email_form' in request.POST:
if email_form.is_valid():
email_form.save()
return HttpResponseRedirect('/settings/')
else:
form_errors = email_form.errors
return render(request, 'settings.html', {'my_user'=user,
'email_form'=email_form, 'form_errors'=form_errors})
else:
email_form = ChangeEmailForm(instance=user)
return render(request, 'settings.html', {'my_user'=user,
'email_form'=email_form})
The trouble comes when trying to render the forms in the template. I
currently have:
{% for key, value in my_user.get_settings %}
<form action="{% url "edit_profile" %}" method="post">
{% csrf_token %}
<p>
{% for field in value.form %}
{{ field }}
{% endfor %}
<button type="submit" name=value.form>Save</button>
</p>
</form>
However, this just prints the name of the form, e.g 'email_form'. I
understand why that's happening, but I don't know how I can get the
template to display the form instead. Also, is there a better way of
handling the user settings? The code I've shown here is very cut down, but
it's basically repeated for each different setting, which isn't very DRY
I have a user settings page with multiple editable and non-editable
components. Each editable component has its own form. All of the
components are displayed in a table, with the contents coming from a dict
on the model. For example:
class MyUser(models.AbstractBaseUser):
def get_settings(self):
return [
('Email Address',
{'value': self.email, 'editable': True, 'section':
'email', 'form': 'email_form'}
),
('Password',
{'value': '', 'editable': True, 'section': 'password',
'form': 'password_form'})]
I then have a form defined for each item in the settings, such as:
class ChangeEmailForm(models.ModelForm):
class Meta:
fields = ['email']
model = models.MyUser
email = forms.EmailField(widget =
forms.TextInput(attrs={'placeholder': 'Email Address'}))
All of the forms are handled by one view, and in that view they are
assigned a name, which matches the name in the settings data on the model:
def edit_settings_view(request, user):
if request.POST:
if 'email_form' in request.POST:
if email_form.is_valid():
email_form.save()
return HttpResponseRedirect('/settings/')
else:
form_errors = email_form.errors
return render(request, 'settings.html', {'my_user'=user,
'email_form'=email_form, 'form_errors'=form_errors})
else:
email_form = ChangeEmailForm(instance=user)
return render(request, 'settings.html', {'my_user'=user,
'email_form'=email_form})
The trouble comes when trying to render the forms in the template. I
currently have:
{% for key, value in my_user.get_settings %}
<form action="{% url "edit_profile" %}" method="post">
{% csrf_token %}
<p>
{% for field in value.form %}
{{ field }}
{% endfor %}
<button type="submit" name=value.form>Save</button>
</p>
</form>
However, this just prints the name of the form, e.g 'email_form'. I
understand why that's happening, but I don't know how I can get the
template to display the form instead. Also, is there a better way of
handling the user settings? The code I've shown here is very cut down, but
it's basically repeated for each different setting, which isn't very DRY
python string unicode issue
python string unicode issue
Here is my code
result = " '{0}' is unicode or something: ".format(mongdb['field'])
UnicodeEncodeError: 'ascii' codec can't encode character u'\xb0' in
position 27: ordinal not in range(128)
It looks like a string I read from mongodb contains unicode. And it throws
this error. How to fix it to concatenate this unicde with custom string
'is unicode or something:' ?
Thanks in advance
Here is my code
result = " '{0}' is unicode or something: ".format(mongdb['field'])
UnicodeEncodeError: 'ascii' codec can't encode character u'\xb0' in
position 27: ordinal not in range(128)
It looks like a string I read from mongodb contains unicode. And it throws
this error. How to fix it to concatenate this unicde with custom string
'is unicode or something:' ?
Thanks in advance
How to get Python File Output to CSV
How to get Python File Output to CSV
I have the following script, and I am trying to move the output of the
script to a CSV file. The problem is I do not know where to start. I am
thinking of using import CSV, but I am not sure where to go from there.
This is Python 3 and I am not finding a lot of clear explanations and some
are really advanced, which I am not. This is my program that I currently
have. I tried to throw in a return at the end of the loop, but I get a out
of function error. I know I should use a break to end a loop, but then
where do I go from there?
String that is used
s = """10.0.1.2 - - [19/Apr/2010:06:36:15 -0700] "GET /feed/ HTTP/1.1" 200
16605 "-" "Apple-PubSub/65.12.1" C4nE4goAAQ4AAEP1Dh8AAAAA 3822005"""
Variables that are going to be used
inquote = False # You have to declare the state of inquote in order for
the iteration to properly switch. Changing this to True alters the results
newstring = '' # You are declaring newstring is equal to whitespace
Start of the for nested loop
for i in range(0,len(s)): # this is the start of the for loop. In this
portion you are going to look at each character one by one if s[i] == '"':
# Found a quote see if its the beg or end if inquote == False: # This is
the beginning state of s inquote = True
else:
inquote = False #This is changing the state to False. In
changing the state to False then it stops looking at the
quotations.
if s[i] == " ": # This section looks at s and the string to determine
quotation marks. If not in quotation marks then a comma is added to
whitespace. In turn this is iterated over and over
if not inquote:
newstring += ','
else:
newstring += s[i]
else:
newstring += s[i]
brack1=newstring.replace('[','')
brack2=brack1.replace(']','')
I have the following script, and I am trying to move the output of the
script to a CSV file. The problem is I do not know where to start. I am
thinking of using import CSV, but I am not sure where to go from there.
This is Python 3 and I am not finding a lot of clear explanations and some
are really advanced, which I am not. This is my program that I currently
have. I tried to throw in a return at the end of the loop, but I get a out
of function error. I know I should use a break to end a loop, but then
where do I go from there?
String that is used
s = """10.0.1.2 - - [19/Apr/2010:06:36:15 -0700] "GET /feed/ HTTP/1.1" 200
16605 "-" "Apple-PubSub/65.12.1" C4nE4goAAQ4AAEP1Dh8AAAAA 3822005"""
Variables that are going to be used
inquote = False # You have to declare the state of inquote in order for
the iteration to properly switch. Changing this to True alters the results
newstring = '' # You are declaring newstring is equal to whitespace
Start of the for nested loop
for i in range(0,len(s)): # this is the start of the for loop. In this
portion you are going to look at each character one by one if s[i] == '"':
# Found a quote see if its the beg or end if inquote == False: # This is
the beginning state of s inquote = True
else:
inquote = False #This is changing the state to False. In
changing the state to False then it stops looking at the
quotations.
if s[i] == " ": # This section looks at s and the string to determine
quotation marks. If not in quotation marks then a comma is added to
whitespace. In turn this is iterated over and over
if not inquote:
newstring += ','
else:
newstring += s[i]
else:
newstring += s[i]
brack1=newstring.replace('[','')
brack2=brack1.replace(']','')
Injecting a class and wrapping a function around strings with Mono.Cecil
Injecting a class and wrapping a function around strings with Mono.Cecil
I'm attempting to make an obfuscator and so far it's going well, right now
I'm trying to encode strings with base64 and then rot13 that just to make
it an extra bit unreadable and hide my sooper sekret strings.
This is what I have for encoding the strings on the obfuscator:
ILProcessor processor = method.Body.GetILProcessor();
foreach (Instruction instruction in processor.Body.Instructions)
{
if (instruction.OpCode == OpCodes.Ldstr)
{
instruction.Operand =
Enc.to64(Enc.Rot((String)instruction.Operand, 0x0D)); //0x0D = 13
}
}
So now what I need to do is inject my Enc class into the root namespace
and since the functions are static I'll be able to use them without
creating an instance of the class. Then what I'll need to do is wrap each
string in two of the functions in Enc to decode the string when the
program is actually used, making
string lel = "topkek";
into
string lel = Enc.from64(Enc.Rot((String)instruction.Operand, 0x0D));
I know how to do neither of these things, so there's where I need your help.
So to recap I need to know how to inject a class (with static functions)
into the root namespace and then wrap all strings in the program with two
functions from said class so that it's unreadable when reflected but
decoded when used.
I'm attempting to make an obfuscator and so far it's going well, right now
I'm trying to encode strings with base64 and then rot13 that just to make
it an extra bit unreadable and hide my sooper sekret strings.
This is what I have for encoding the strings on the obfuscator:
ILProcessor processor = method.Body.GetILProcessor();
foreach (Instruction instruction in processor.Body.Instructions)
{
if (instruction.OpCode == OpCodes.Ldstr)
{
instruction.Operand =
Enc.to64(Enc.Rot((String)instruction.Operand, 0x0D)); //0x0D = 13
}
}
So now what I need to do is inject my Enc class into the root namespace
and since the functions are static I'll be able to use them without
creating an instance of the class. Then what I'll need to do is wrap each
string in two of the functions in Enc to decode the string when the
program is actually used, making
string lel = "topkek";
into
string lel = Enc.from64(Enc.Rot((String)instruction.Operand, 0x0D));
I know how to do neither of these things, so there's where I need your help.
So to recap I need to know how to inject a class (with static functions)
into the root namespace and then wrap all strings in the program with two
functions from said class so that it's unreadable when reflected but
decoded when used.
Combining arrays with incremental key
Combining arrays with incremental key
I have the following structure:
products = array[2] {
[0] = array[12] = stdclass[108],
[1] = array[18] = stdclass[108],
}
There is one array contain two arrays, each array containing a stdclass
object. I want to combine these to arrays in order to achieve this:
products = array[2]{
0 => stdclass[108],
1 => stdclass[108],
.....
31 => stdclass[108]
}
I have the following structure:
products = array[2] {
[0] = array[12] = stdclass[108],
[1] = array[18] = stdclass[108],
}
There is one array contain two arrays, each array containing a stdclass
object. I want to combine these to arrays in order to achieve this:
products = array[2]{
0 => stdclass[108],
1 => stdclass[108],
.....
31 => stdclass[108]
}
Thursday, 12 September 2013
Over-ride one TimeSeries with another
Over-ride one TimeSeries with another
I'd like to over-ride the values of one time series with another. The
input series has values at all points. The over-ride time series will have
the same index (i.e. dates) but I would only want to over-ride the values
at some dates. The way I have thought of specifying this is to have a time
series with values where I want to over-ride to that value and NaN where I
don't want an over-ride applied. Perhaps best illustrated with a quick
example:
index ints orts outts
2013-04-01 1 NaN 1
2013-05-01 2 11 11
2013-06-01 3 NaN 3
2013-07-01 4 9 9
2013-08-01 2 97 97
As you can see from the example, I don't think the replace or where
methods would work as the values of replacement are index location
dependent and not input value dependent. Because I want to do this more
than once I've put it in a function and I do have a solution that works as
shown below:
def overridets(ts, orts):
tmp = pd.concat([ts, orts], join='outer', axis=1)
out = tmp.apply(lambda x: x[0] if pd.isnull(x[1]) else x[1], axis=1)
return out
The issue is that this runs relatively slowly: 20 - 30 ms for a 500 point
series in my environment. Multiplying two 500 point series takes ~200 us
so we're talking about 100 times slower. Any suggestions on how to pick up
the pace?
I'd like to over-ride the values of one time series with another. The
input series has values at all points. The over-ride time series will have
the same index (i.e. dates) but I would only want to over-ride the values
at some dates. The way I have thought of specifying this is to have a time
series with values where I want to over-ride to that value and NaN where I
don't want an over-ride applied. Perhaps best illustrated with a quick
example:
index ints orts outts
2013-04-01 1 NaN 1
2013-05-01 2 11 11
2013-06-01 3 NaN 3
2013-07-01 4 9 9
2013-08-01 2 97 97
As you can see from the example, I don't think the replace or where
methods would work as the values of replacement are index location
dependent and not input value dependent. Because I want to do this more
than once I've put it in a function and I do have a solution that works as
shown below:
def overridets(ts, orts):
tmp = pd.concat([ts, orts], join='outer', axis=1)
out = tmp.apply(lambda x: x[0] if pd.isnull(x[1]) else x[1], axis=1)
return out
The issue is that this runs relatively slowly: 20 - 30 ms for a 500 point
series in my environment. Multiplying two 500 point series takes ~200 us
so we're talking about 100 times slower. Any suggestions on how to pick up
the pace?
Android: How to change webview width before capturePicture to save the view
Android: How to change webview width before capturePicture to save the view
The webview on my application becomes quite long. I want the user to be
able to save the webview. It is working right now but the code generates a
long image. I want make the height\width propotional before saving e.g.
800\600 etc.
Not sure how to do it??
This is how I am saving the jpg:
Picture picture = webview.capturePicture();
Bitmap b = Bitmap.createBitmap(picture.getWidth(), picture.getHeight(),
Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
picture.draw(c);
FileOutputStream fos = null;
try {
File file = new File(pathName);
file.createNewFile();
fos = new FileOutputStream(file);
if (fos != null) {
b.compress(Bitmap.CompressFormat.JPEG, 90, fos);
fos.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
}
}
and the layout is like this:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:id="@+id/a_layout"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:id="@+id/fullscreen_content_controls"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true">
<Button
android:id="@+id/reload"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="@string/reload" />
</LinearLayout>
<WebView
android:layout_width="fill_parent"
android:id="@+id/webview"
android:layout_above="@id/fullscreen_content_controls"
android:layout_alignParentTop="true"
android:layout_height="fill_parent" />
</RelativeLayout>
The webview on my application becomes quite long. I want the user to be
able to save the webview. It is working right now but the code generates a
long image. I want make the height\width propotional before saving e.g.
800\600 etc.
Not sure how to do it??
This is how I am saving the jpg:
Picture picture = webview.capturePicture();
Bitmap b = Bitmap.createBitmap(picture.getWidth(), picture.getHeight(),
Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
picture.draw(c);
FileOutputStream fos = null;
try {
File file = new File(pathName);
file.createNewFile();
fos = new FileOutputStream(file);
if (fos != null) {
b.compress(Bitmap.CompressFormat.JPEG, 90, fos);
fos.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
}
}
and the layout is like this:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:id="@+id/a_layout"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:id="@+id/fullscreen_content_controls"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true">
<Button
android:id="@+id/reload"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="@string/reload" />
</LinearLayout>
<WebView
android:layout_width="fill_parent"
android:id="@+id/webview"
android:layout_above="@id/fullscreen_content_controls"
android:layout_alignParentTop="true"
android:layout_height="fill_parent" />
</RelativeLayout>
How can I replace window.confirm with custom code?
How can I replace window.confirm with custom code?
For accessibility reasons, for my Chrome extension, I need to be able to
replace all standard window.confirm popups with an in-page HTML
substitute. I know how to create a substitute skeleton, that's trivial.
And I know the basic idea here is window.confirm = {my substitute code}.
What I don't know how to do is grab the text and code from each confirm
window that a page issues, and channel it into my substitute, so that the
same message is shown as would be in the original popup and clicking my
substitute confirm and leave page (or whatever) buttons yield the same
result as the original popup.
How can this be done?
EXAMPLE:
You have my extension installed (don't ask what its purpose is, irrelevant).
You start writing a question on StackOverflow, then realize you already
know the answer and go to close the tab.
Normally, a confirmation window would come up asking if you're sure you
want to leave the page.
But because of my extension, instead, the whole page's HTML gets shoved
down a bit to make room for a temporary HTML confirmation box is shown
with the same text and the same two buttons that yield the same two
results when clicked, all in-page. No pop-up.
For accessibility reasons, for my Chrome extension, I need to be able to
replace all standard window.confirm popups with an in-page HTML
substitute. I know how to create a substitute skeleton, that's trivial.
And I know the basic idea here is window.confirm = {my substitute code}.
What I don't know how to do is grab the text and code from each confirm
window that a page issues, and channel it into my substitute, so that the
same message is shown as would be in the original popup and clicking my
substitute confirm and leave page (or whatever) buttons yield the same
result as the original popup.
How can this be done?
EXAMPLE:
You have my extension installed (don't ask what its purpose is, irrelevant).
You start writing a question on StackOverflow, then realize you already
know the answer and go to close the tab.
Normally, a confirmation window would come up asking if you're sure you
want to leave the page.
But because of my extension, instead, the whole page's HTML gets shoved
down a bit to make room for a temporary HTML confirmation box is shown
with the same text and the same two buttons that yield the same two
results when clicked, all in-page. No pop-up.
Java - how to create delays
Java - how to create delays
I'm wondering how can I make a Java program delay parts of code to prevent
spamming buttons/other things in the program. So let's just say I'm making
a program that displays the amount of times a user has clicked a button. I
would like there to be a delay to the user cannot click the button
rapidly. I heard that java timers could help me, but I can't find any
tutorial explaining what I need done.
public void ButtonActionPerformed(java.awt.event.ActionEvent evt) {
count+=1;
labelA.setText(Integer.toString(count));
}
This is just an example program, not what im actually working on. So can
someone please help me? I need to have a program create a delay so the
user cannot spam buttons. Thanks :) (this is a revised question from
before)
I'm wondering how can I make a Java program delay parts of code to prevent
spamming buttons/other things in the program. So let's just say I'm making
a program that displays the amount of times a user has clicked a button. I
would like there to be a delay to the user cannot click the button
rapidly. I heard that java timers could help me, but I can't find any
tutorial explaining what I need done.
public void ButtonActionPerformed(java.awt.event.ActionEvent evt) {
count+=1;
labelA.setText(Integer.toString(count));
}
This is just an example program, not what im actually working on. So can
someone please help me? I need to have a program create a delay so the
user cannot spam buttons. Thanks :) (this is a revised question from
before)
Rails 3: Getting CSRF Warning even though authenticity_token exists
Rails 3: Getting CSRF Warning even though authenticity_token exists
On multiple parts of my page I'm receiving WARNING: Can't verify CSRF
token authenticity in my log file, which is resetting my sessions.
However, I have the authenticity tokens:
Started POST "/check_out/shopping_cart_with_authenticated_user" for
10.189.254.5 at 2013-09-12 11:19:02 -0400
Processing by CheckOutController#shopping_cart_with_authenticated_user
as HTML
Parameters: {"utf8"=>"✓",
"authenticity_token"=>"rGcLQAR/s7zRNf2WEqkuD7ar8IXs0alt7szJKSfgLio="}
SESSION VARIABLES ARE: {}
WARNING: Can't verify CSRF token authenticity
and here:
Processing by SessionsController#create as HTML
Parameters: {"utf8"=>"✓",
"authenticity_token"=>"N1F53oN1fTv2Ysg/27biH14dDyTtkm2RinAUqSHwGAs=",
"user"=>{"email"=>"liz@nsdfsdfsdfsry.com",
"password"=>"[FILTERED]"}, "commit"=>"Sign in"}
SESSION VARIABLES ARE: {"current_cart_id"=>55175183,
"_csrf_token"=>"HzPm7DHLslbV76wJ3ahCqPkOO4bv5k5CkjKBe3C9WHE=",
"flash"=>#<ActionDispatch::Flash::FlashHash:0x00000005f1e028
@used=#<Set: {}>, @closed=false, @flashes={},
@now=#<ActionDispatch::Flash::FlashNow:0x00000005e81570
@flash=#<ActionDispatch::Flash::FlashHash:0x00000005f1e028 ...>>>,
"warden.user.user.key"=>["User", [358060],
"$2a$12$VcSeYjhwx6JkgERnlN0clu"], "logged_in_by_password"=>true,
"user_id"=>358060}
WARNING: Can't verify CSRF token authenticity
What's the deal? I'm using Rails generated forms. Here's an example of a
Devise form I'm using:
<%= form_for(resource, :as => resource_name, :url =>
session_path(resource_name)) do |f| %>
<%= token_tag form_authenticity_token %>
<div class="formField"><label for="email">Email
<span>example: jane@example.com</span></label>
<%= f.email_field :email, :autofocus => true, :id =>
"email", :class => "textfield col" %></div>
<div class="formField"><label for="password">Password
<span>is cAsE sEnSiTiVe</span></label>
<%= f.password_field :password, :class => "textfield col"
%></div>
<div><%= f.submit "Sign in", :disable_with => "Signing
in…".html_safe,:id => 'log_in', :class =>
'button-red-shiny full-width ' %></div>
<% end %>
On multiple parts of my page I'm receiving WARNING: Can't verify CSRF
token authenticity in my log file, which is resetting my sessions.
However, I have the authenticity tokens:
Started POST "/check_out/shopping_cart_with_authenticated_user" for
10.189.254.5 at 2013-09-12 11:19:02 -0400
Processing by CheckOutController#shopping_cart_with_authenticated_user
as HTML
Parameters: {"utf8"=>"✓",
"authenticity_token"=>"rGcLQAR/s7zRNf2WEqkuD7ar8IXs0alt7szJKSfgLio="}
SESSION VARIABLES ARE: {}
WARNING: Can't verify CSRF token authenticity
and here:
Processing by SessionsController#create as HTML
Parameters: {"utf8"=>"✓",
"authenticity_token"=>"N1F53oN1fTv2Ysg/27biH14dDyTtkm2RinAUqSHwGAs=",
"user"=>{"email"=>"liz@nsdfsdfsdfsry.com",
"password"=>"[FILTERED]"}, "commit"=>"Sign in"}
SESSION VARIABLES ARE: {"current_cart_id"=>55175183,
"_csrf_token"=>"HzPm7DHLslbV76wJ3ahCqPkOO4bv5k5CkjKBe3C9WHE=",
"flash"=>#<ActionDispatch::Flash::FlashHash:0x00000005f1e028
@used=#<Set: {}>, @closed=false, @flashes={},
@now=#<ActionDispatch::Flash::FlashNow:0x00000005e81570
@flash=#<ActionDispatch::Flash::FlashHash:0x00000005f1e028 ...>>>,
"warden.user.user.key"=>["User", [358060],
"$2a$12$VcSeYjhwx6JkgERnlN0clu"], "logged_in_by_password"=>true,
"user_id"=>358060}
WARNING: Can't verify CSRF token authenticity
What's the deal? I'm using Rails generated forms. Here's an example of a
Devise form I'm using:
<%= form_for(resource, :as => resource_name, :url =>
session_path(resource_name)) do |f| %>
<%= token_tag form_authenticity_token %>
<div class="formField"><label for="email">Email
<span>example: jane@example.com</span></label>
<%= f.email_field :email, :autofocus => true, :id =>
"email", :class => "textfield col" %></div>
<div class="formField"><label for="password">Password
<span>is cAsE sEnSiTiVe</span></label>
<%= f.password_field :password, :class => "textfield col"
%></div>
<div><%= f.submit "Sign in", :disable_with => "Signing
in…".html_safe,:id => 'log_in', :class =>
'button-red-shiny full-width ' %></div>
<% end %>
Replace in Html file
Replace in Html file
I am using following code. It displays only HTML file in list box I want
to replace Figure 1, Figure 1.2, Figure 2, Figure 2.1 so on ....... with
Figure 1 ........... in OutPut
please help me
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
FileInfo file = new FileInfo(textBox1.Text);
StreamReader stRead = file.OpenText();
while (!stRead.EndOfStream)
{
listBox1.Items.Add(stRead.ReadLine());
}
}
}
output
<html>
<head>
</head>
<body>
<div>
<p class="epigraph"> very Figure 1 But thanks to you, we won't do
it </p>
<p class="epigraph-right"> birthday Figure 1.1 Milton Friedman, November
8, 2002</p>
<p class="indent">Not Figure 2 able to take it any longer New York </p>
<p class="indent">Mr. Cutler Figure 2.1 of the parallel plunges</p>
</body>
</div>
</html>
I am using following code. It displays only HTML file in list box I want
to replace Figure 1, Figure 1.2, Figure 2, Figure 2.1 so on ....... with
Figure 1 ........... in OutPut
please help me
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
FileInfo file = new FileInfo(textBox1.Text);
StreamReader stRead = file.OpenText();
while (!stRead.EndOfStream)
{
listBox1.Items.Add(stRead.ReadLine());
}
}
}
output
<html>
<head>
</head>
<body>
<div>
<p class="epigraph"> very Figure 1 But thanks to you, we won't do
it </p>
<p class="epigraph-right"> birthday Figure 1.1 Milton Friedman, November
8, 2002</p>
<p class="indent">Not Figure 2 able to take it any longer New York </p>
<p class="indent">Mr. Cutler Figure 2.1 of the parallel plunges</p>
</body>
</div>
</html>
Wednesday, 11 September 2013
Maximum amount of entries in the histogram_bounds
Maximum amount of entries in the histogram_bounds
The default limit is presently 100 entries for histogram_bounds and
max_common_values fields in pg_stats view. Raising the limit might allow
to be made more accurate estimates scanned rows for postgresql planner.
Globally, this setting is set by default_statistics_target or can be set
on a column-by-column basis using the ALTER TABLE SET STATISTICS command.
What is the maximum value of this setting can be set?
The default limit is presently 100 entries for histogram_bounds and
max_common_values fields in pg_stats view. Raising the limit might allow
to be made more accurate estimates scanned rows for postgresql planner.
Globally, this setting is set by default_statistics_target or can be set
on a column-by-column basis using the ALTER TABLE SET STATISTICS command.
What is the maximum value of this setting can be set?
Blank string in c++
Blank string in c++
#include <iostream>
#include <string>
using namespace std;
int main()
{
int userInput;
string numberType;
cout << "Enter a number and I will Check to see if it is odd or even" <<
endl;
cin >> userInput;
if (userInput % 2 == 0)
{
string numberType = "Even";
}
else
{
string numberType = "Odd";
}
cout << "The number you input is " << numberType << endl;
return 0;
}
I'm trying to output the manipulated string value but the string that's
output in the last line comes out blank?
#include <iostream>
#include <string>
using namespace std;
int main()
{
int userInput;
string numberType;
cout << "Enter a number and I will Check to see if it is odd or even" <<
endl;
cin >> userInput;
if (userInput % 2 == 0)
{
string numberType = "Even";
}
else
{
string numberType = "Odd";
}
cout << "The number you input is " << numberType << endl;
return 0;
}
I'm trying to output the manipulated string value but the string that's
output in the last line comes out blank?
Converting from XIB to StoryBoard
Converting from XIB to StoryBoard
Can someone please advise me on how to convert this project from using XIB
files to ViewControllers.
I have tried everything and also contacted the developers to no avail.
Template File
Can someone please advise me on how to convert this project from using XIB
files to ViewControllers.
I have tried everything and also contacted the developers to no avail.
Template File
Change the highlighted page title text color
Change the highlighted page title text color
I have implemented the the ViewPager functionality in android
successfully, now I just wanted to change the highlighted page title text
color.
Is it possible to change the highlighted page title text color?
I have implemented the the ViewPager functionality in android
successfully, now I just wanted to change the highlighted page title text
color.
Is it possible to change the highlighted page title text color?
Angular JS observe on directive attribute
Angular JS observe on directive attribute
How can angular js watch attributes on custom directive in order to accept
angular values to be bind
Here is what I have so far:
app.directive('tile', [function(){ return { restrict: 'E', link:
function(scope, element, attrs) { var title = attrs.title;
attrs.$observe('dataValue', function(val) {
var data = val;
console.log(data);
var dom =
"<div>" +
"<p>" + title + "</p>" +
"<p>" + data + "</p>" +
"</div";
$(element).append($(dom.trim()));
});
}
};
}]);
but the observed value is coming back as undefined
How can angular js watch attributes on custom directive in order to accept
angular values to be bind
Here is what I have so far:
app.directive('tile', [function(){ return { restrict: 'E', link:
function(scope, element, attrs) { var title = attrs.title;
attrs.$observe('dataValue', function(val) {
var data = val;
console.log(data);
var dom =
"<div>" +
"<p>" + title + "</p>" +
"<p>" + data + "</p>" +
"</div";
$(element).append($(dom.trim()));
});
}
};
}]);
but the observed value is coming back as undefined
Rails Devise Password Reset Email allowing multiple submissions
Rails Devise Password Reset Email allowing multiple submissions
I have the following code that allows a user to request a password reset:
<%= form_for(resource, :as => resource_name, :url =>
password_path(resource_name), :html => { :method => :post }) do |f| %>
<%= devise_error_messages! %>
<div><%= f.label :email %><br />
<%= f.email_field :email %></div>
<div><%= f.submit "Send me reset password instructions" %></div>
<% end %>
This is allowing the behavior whereby if the user clicks the button
repeatedly, or presses "enter" repeatedly, before the server can provide a
response, a corresponding # of password reset emails are being sent.
The following is within devise/password_controller.rb
def create
self.resource =
resource_class.send_reset_password_instructions(resource_params)
if successfully_sent?(resource)
flash[:notice] = "You will receive an email with instructions about how
to reset your password in a few minutes."
respond_to do |format|
format.html #responds with default html file
format.js
end
else
respond_to do |format|
format.html #responds with default html file
format.js{ render :js => "$(\".deviseErrors\").html(\"<span
class='login-error'>Could not send reset instructions to that
address.</span>\");" } #this will be the javascript file we respond
with
end
end
end
Is there a way to only respond to the first submission?
Thanks
I have the following code that allows a user to request a password reset:
<%= form_for(resource, :as => resource_name, :url =>
password_path(resource_name), :html => { :method => :post }) do |f| %>
<%= devise_error_messages! %>
<div><%= f.label :email %><br />
<%= f.email_field :email %></div>
<div><%= f.submit "Send me reset password instructions" %></div>
<% end %>
This is allowing the behavior whereby if the user clicks the button
repeatedly, or presses "enter" repeatedly, before the server can provide a
response, a corresponding # of password reset emails are being sent.
The following is within devise/password_controller.rb
def create
self.resource =
resource_class.send_reset_password_instructions(resource_params)
if successfully_sent?(resource)
flash[:notice] = "You will receive an email with instructions about how
to reset your password in a few minutes."
respond_to do |format|
format.html #responds with default html file
format.js
end
else
respond_to do |format|
format.html #responds with default html file
format.js{ render :js => "$(\".deviseErrors\").html(\"<span
class='login-error'>Could not send reset instructions to that
address.</span>\");" } #this will be the javascript file we respond
with
end
end
end
Is there a way to only respond to the first submission?
Thanks
Collections.shuffle multiple times in a row
Collections.shuffle multiple times in a row
I got a little question about the Collections.shuffle() method.
Case:
I have 2 lists i need to shuffle, then union / merge them into one list,
then shuffle the new complete list. I have used the shuffle method with
the Random class - using system.nanoTime() as seed.
Code looks as below:
public List<PresentationArticle>
shuffleUnionShuffleLists(List<PresentationArticle> nykreditJobAdsList,
List<PresentationArticle> boxJobAdsList) {
shuffleList(nykreditJobAdsList);
shuffleList(boxJobAdsList);
List<PresentationArticle> resultList = //merge/union the two lists
shuffleList(resultList);
return resultList;
}
public void shuffleList(List<PresentationArticle> articleList) {
long seed = System.nanoTime();
Collections.shuffle(articleList, new Random(seed));
}
My question is: Will this be a proper random shuffling of the lists, when
the methods runs right after eachother, with a new Random object and a new
(but almost identical) seed?
The method shuffleUnionShuffleLists() will be run approximately every 3
minutes.
I got a little question about the Collections.shuffle() method.
Case:
I have 2 lists i need to shuffle, then union / merge them into one list,
then shuffle the new complete list. I have used the shuffle method with
the Random class - using system.nanoTime() as seed.
Code looks as below:
public List<PresentationArticle>
shuffleUnionShuffleLists(List<PresentationArticle> nykreditJobAdsList,
List<PresentationArticle> boxJobAdsList) {
shuffleList(nykreditJobAdsList);
shuffleList(boxJobAdsList);
List<PresentationArticle> resultList = //merge/union the two lists
shuffleList(resultList);
return resultList;
}
public void shuffleList(List<PresentationArticle> articleList) {
long seed = System.nanoTime();
Collections.shuffle(articleList, new Random(seed));
}
My question is: Will this be a proper random shuffling of the lists, when
the methods runs right after eachother, with a new Random object and a new
(but almost identical) seed?
The method shuffleUnionShuffleLists() will be run approximately every 3
minutes.
Unexpected results when calling resize() on an STL vector in C++
Unexpected results when calling resize() on an STL vector in C++
In the following code, if I call v.resize(n), the program will print out 0
0 0 0 0 0 0 0 0 0, which is not what I wanted to see. However, if I
comment the line containing v.resize(n) out, it will print out 0 1 2 3 4 5
6 7 8 9, which is what I wanted to see. Why is this the case? What's wrong
with my logic here?
#include <iostream>
#include <vector>
using namespace std;
int main( int argc , char ** argv )
{
int n = 10;
vector<int> v;
v.resize(n);
for( int i=0 ; i<n ; i++ )
{
v.push_back(i);
}
for( int i=0 ; i<n ; i++ )
{
cout << v[i] << " ";
}
cout << endl;
return 0;
}
In the following code, if I call v.resize(n), the program will print out 0
0 0 0 0 0 0 0 0 0, which is not what I wanted to see. However, if I
comment the line containing v.resize(n) out, it will print out 0 1 2 3 4 5
6 7 8 9, which is what I wanted to see. Why is this the case? What's wrong
with my logic here?
#include <iostream>
#include <vector>
using namespace std;
int main( int argc , char ** argv )
{
int n = 10;
vector<int> v;
v.resize(n);
for( int i=0 ; i<n ; i++ )
{
v.push_back(i);
}
for( int i=0 ; i<n ; i++ )
{
cout << v[i] << " ";
}
cout << endl;
return 0;
}
Tuesday, 10 September 2013
Data Driven testing using excel sheet for the content on different web pages using JAVA in Selenium Web Driver
Data Driven testing using excel sheet for the content on different web
pages using JAVA in Selenium Web Driver
I have a requirement to test the large list of webpages for specific
website and have to verify i) if the content on all provided webpages is
present or not? ii) the content is neither duplicated as well on that
particular page.
I need to automate this using selenium webdriver (Java). I want that I
just provide all the pages URL into an excel sheet (.csv file) and just
run the test through it and get back the results for my requirements.
Please help me in this.
Thanks in advance..
pages using JAVA in Selenium Web Driver
I have a requirement to test the large list of webpages for specific
website and have to verify i) if the content on all provided webpages is
present or not? ii) the content is neither duplicated as well on that
particular page.
I need to automate this using selenium webdriver (Java). I want that I
just provide all the pages URL into an excel sheet (.csv file) and just
run the test through it and get back the results for my requirements.
Please help me in this.
Thanks in advance..
How to create unlimited sub category in drop down list
How to create unlimited sub category in drop down list
Would you please guide me on how to create unlimited category and sub
category in a drop down list using php and mysql?
I was the sub category to have --- in front of them. For example, the
first sub category --- and the second level ----- and so on: I want to
achieve some thing like this:-
<select name="category">
<option value="1">Root</option>
<option value="3">- Sub </option>
<option value="4">- - Sub</option>
<option value="2">Root</option>
<option value="3">- Sub </option>
<option value="4">- - Sub</option>
</select>
Here is the code I got so far
function get_category($parentID = 0){
global $mysqli;
$html = '';
// Prepare the query
$stmt = $mysqli->prepare("SELECT CategoryID, Title
FROM category
WHERE ParentID =?");
// Execute the query
$stmt->bind_param('i', $parentID);
$stmt->execute();
// Store the result
$stmt->store_result();
// Bind the result
$stmt->bind_result($categoryID, $title);
while($stmt->fetch()){
$html .= "<option
value=\"$categoryID\">$title</option>";
$child = $mysqli->prepare("SELECT CategoryID
FROM category
WHERE ParentID =?");
// Execute the query
$child->bind_param('i', $categoryID);
$child->execute();
// Store the result
$child->store_result();
// Bind the result
$has_child = NULL;
$has_child = $child->num_rows;
if($has_child){
$html .= get_category($categoryID);
}
}
return $html;
}
echo '<select name="category">';
print(get_category());
echo '</select>';
Any help is appreciated
Would you please guide me on how to create unlimited category and sub
category in a drop down list using php and mysql?
I was the sub category to have --- in front of them. For example, the
first sub category --- and the second level ----- and so on: I want to
achieve some thing like this:-
<select name="category">
<option value="1">Root</option>
<option value="3">- Sub </option>
<option value="4">- - Sub</option>
<option value="2">Root</option>
<option value="3">- Sub </option>
<option value="4">- - Sub</option>
</select>
Here is the code I got so far
function get_category($parentID = 0){
global $mysqli;
$html = '';
// Prepare the query
$stmt = $mysqli->prepare("SELECT CategoryID, Title
FROM category
WHERE ParentID =?");
// Execute the query
$stmt->bind_param('i', $parentID);
$stmt->execute();
// Store the result
$stmt->store_result();
// Bind the result
$stmt->bind_result($categoryID, $title);
while($stmt->fetch()){
$html .= "<option
value=\"$categoryID\">$title</option>";
$child = $mysqli->prepare("SELECT CategoryID
FROM category
WHERE ParentID =?");
// Execute the query
$child->bind_param('i', $categoryID);
$child->execute();
// Store the result
$child->store_result();
// Bind the result
$has_child = NULL;
$has_child = $child->num_rows;
if($has_child){
$html .= get_category($categoryID);
}
}
return $html;
}
echo '<select name="category">';
print(get_category());
echo '</select>';
Any help is appreciated
Is there a temporary workaround for Google Docs "Script invoked too many times per second for this Google user account." Error
Is there a temporary workaround for Google Docs "Script invoked too many
times per second for this Google user account." Error
Background: Some friends and I have been using Google Docs spreadsheets to
do some data analysis and simulations as a fun way to learn some basic
Javascripting. It quickly got quite complex and out of hand, and since we
had been learning it at the time, almost nothing was done efficiently, and
all three of us used different programming conventions. (I know I know).
Fast forward over summer break, now that we know somewhat what we're
doing, we want to redo the whole spreadsheet from the ground up.
Unfortunately, we cant analyze what scripts stay or go or what some of the
more complex ones actually do, since there are so many function calls
throughout the document we get the "Script invoked too many times per
second for this Google user account." Error around several dozen times per
sheet.
I know that we can set up the scripts to output arrays directly into the
spreadsheet, and that doing that would really cut down on the load,
however i dont really want to reprogram the spreadsheet to reprogram the
spreadsheet.
So, finally, my question is: Is there some quick and dirty workaround I
can use to get all the scripts I need to run, so I can analyze them? I
already copied the doc, cut out everything not pertaining to the complex
ones, and its not quite enough. about 10% are still giving error messages.
Any help would be amazing.
times per second for this Google user account." Error
Background: Some friends and I have been using Google Docs spreadsheets to
do some data analysis and simulations as a fun way to learn some basic
Javascripting. It quickly got quite complex and out of hand, and since we
had been learning it at the time, almost nothing was done efficiently, and
all three of us used different programming conventions. (I know I know).
Fast forward over summer break, now that we know somewhat what we're
doing, we want to redo the whole spreadsheet from the ground up.
Unfortunately, we cant analyze what scripts stay or go or what some of the
more complex ones actually do, since there are so many function calls
throughout the document we get the "Script invoked too many times per
second for this Google user account." Error around several dozen times per
sheet.
I know that we can set up the scripts to output arrays directly into the
spreadsheet, and that doing that would really cut down on the load,
however i dont really want to reprogram the spreadsheet to reprogram the
spreadsheet.
So, finally, my question is: Is there some quick and dirty workaround I
can use to get all the scripts I need to run, so I can analyze them? I
already copied the doc, cut out everything not pertaining to the complex
ones, and its not quite enough. about 10% are still giving error messages.
Any help would be amazing.
How can I shorten and move my vertical divider lines in my NAV menu up?
How can I shorten and move my vertical divider lines in my NAV menu up?
The "|" divider lines on my navigation are going too far down, how can I
shorten them and move them up? I did try changing it to #nav li a (but
then it made an uneven edge at the top of it.
#nav li { border-right: 2px solid #0076a9; height: 10px }
The "|" divider lines on my navigation are going too far down, how can I
shorten them and move them up? I did try changing it to #nav li a (but
then it made an uneven edge at the top of it.
#nav li { border-right: 2px solid #0076a9; height: 10px }
jquery IF behaves differently if i put a alert
jquery IF behaves differently if i put a alert
i want to disable all elements of my class where my checkbox is not
checked. But even this is checked, my if returns false.
$('.myClass').each(function(i, obj) {
if (!$j('input[name='+obj.id+']').is(':checked')){
$j('#desc_'+obj.id).attr('disabled','disabled');
}
});
But if i put a alert inside the if, its works!
$('.myClass').each(function(i, obj) {
if (!$j('input[name='+obj.id+']').is(':checked')){
alert($j('input[name='+obj.id+']').is(':checked'));
$j('#desc_'+obj.id).attr('disabled','disabled');
}
});
Anyone knows why?
i want to disable all elements of my class where my checkbox is not
checked. But even this is checked, my if returns false.
$('.myClass').each(function(i, obj) {
if (!$j('input[name='+obj.id+']').is(':checked')){
$j('#desc_'+obj.id).attr('disabled','disabled');
}
});
But if i put a alert inside the if, its works!
$('.myClass').each(function(i, obj) {
if (!$j('input[name='+obj.id+']').is(':checked')){
alert($j('input[name='+obj.id+']').is(':checked'));
$j('#desc_'+obj.id).attr('disabled','disabled');
}
});
Anyone knows why?
error : JsonHttpResponseHandler cannot be resolved to a type
error : JsonHttpResponseHandler cannot be resolved to a type
Here is my code showing the above error
import org.json.*;
import com.loopj.android.http.*;
class TwitterRestClientUsage {
public void getPublicTimeline() throws JSONException {
TwitterRestClient.get("statuses/public_timeline.json", null, new
JsonHttpResponseHandler() {
@Override
public void onSuccess(JSONArray timeline) {
// Pull out the first event on the public timeline
JSONObject firstEvent = timeline.get(0);
String tweetText = firstEvent.getString("text");
// Do something with the response
System.out.println(tweetText);
}
});
}
}
in the get method i am getting this error,could you please suggest
suitable solution for this.
Here is my code showing the above error
import org.json.*;
import com.loopj.android.http.*;
class TwitterRestClientUsage {
public void getPublicTimeline() throws JSONException {
TwitterRestClient.get("statuses/public_timeline.json", null, new
JsonHttpResponseHandler() {
@Override
public void onSuccess(JSONArray timeline) {
// Pull out the first event on the public timeline
JSONObject firstEvent = timeline.get(0);
String tweetText = firstEvent.getString("text");
// Do something with the response
System.out.println(tweetText);
}
});
}
}
in the get method i am getting this error,could you please suggest
suitable solution for this.
Subscribe to:
Comments (Atom)