Saturday, 31 August 2013

Strange Stack Overflow Error in Sudoko Backtracker

Strange Stack Overflow Error in Sudoko Backtracker

(Disclaimer: There are maybe 20 different versions of this question on SO,
but a reading through most of them still hasn't solved my issue)
Hello all, (relatively) beginner programmer here. So I've been trying to
build a Sudoku backtracker that will fill in an incomplete puzzle. It
seems to works perfectly well even when 1-3 rows are completely empty
(i.e. filled in with 0's), but when more boxes start emptying
(specifically around the 7-8 column in the fourth row, where I stopped
writing in numbers) I get a Stack Overflow Error. Here's the code:
import java.util.ArrayList;
import java.util.HashSet;
public class Sudoku
{
public static int[][] puzzle = new int[9][9];
public static int filledIn = 0;
public static ArrayList<Integer> blankBoxes = new ArrayList<Integer>();
public static int currentIndex = 0;
public static int runs = 0;
/**
* Main method.
*/
public static void main(String args[])
{
//Manual input of the numbers
int[] completedNumbers = {0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,3,4,
8,9,1,2,3,4,5,6,7,
3,4,5,6,7,8,9,1,2,
6,7,8,9,1,2,3,4,5,
9,1,2,3,4,5,6,7,8};
//Adds the numbers manually to the puzzle array
ArrayList<Integer> completeArray = new ArrayList<>();
for(Integer number : completedNumbers) {
completeArray.add(number);
}
int counter = 0;
for(int i = 0; i < 9; i++) {
for(int j = 0; j < 9; j++) {
puzzle[i][j] = completeArray.get(counter);
counter++;
}
}
//Adds all the blank boxes to an ArrayList.
//The index is stored as 10*i + j, which can be retrieved
// via modulo and integer division.
boolean containsEmpty = false;
for(int i = 0; i < 9; i++) {
for(int j = 0; j < 9; j++) {
if(puzzle[i][j] == 0) {
blankBoxes.add(10*i + j);
containsEmpty = true;
}
}
}
filler(blankBoxes.get(currentIndex));
}
/**
* A general method for testing whether an array contains a
* duplicate, via a (relatively inefficient) sort.
* @param testArray The int[] that is being tested for duplicates
* @return True if there are NO duplicate, false if there
* are ANY duplicates.
*/
public static boolean checkDupl(int[] testArray) {
for(int i = 0; i < 8; i++) {
int num = testArray[i];
for(int j = i + 1; j < 9; j++) {
if(num == testArray[j] && num != 0) {
return false;
}
}
}
return true;
}
/**
* If the puzzle is not full, the filler will be run. The filler is my
attempt at a backtracker.
* It stores every (i,j) for which puzzle[i][j] == 0. It then adds 1
to it's value. If the value
* is already somewhere else, it adds another 1. If it is 9, and
that's already there, it loops to
* 0, and the index beforehand is rechecked.
*/
public static void filler(int indexOfBlank) {
//If the current index is equal to the size of blankBoxes, meaning
that we
//went through every index of blankBoxes, meaning the puzzle is
full and correct.
runs++;
if(currentIndex == blankBoxes.size()) {
System.out.println("The puzzle is full!" + "\n");
for(int i = 0; i < 9; i++) {
System.out.println();
for(int j = 0; j < 9; j++) {
System.out.print(puzzle[i][j]);
}
}
System.out.println("\n" + "The filler method was run " + runs
+ " times");
return;
}
//Assuming the puzzle isn't full, find the row/column of the
blankBoxes index.
int row = blankBoxes.get(currentIndex) / 10;
int column = blankBoxes.get(currentIndex) % 10;
//Adds one to the value of that box.
puzzle[row][column] = (puzzle[row][column] + 1);
//Just used as a breakpoint for a debugger.
if(row == 4 && column == 4){
int x = 0;
}
//If the value is 10, meaning it went through all the possible
values:
if(puzzle[row][column] == 10) {
//Do filler() on the previous box
puzzle[row][column] = 0;
currentIndex--;
filler(currentIndex);
}
//If the number is 1-9, but there are duplicates:
else if(!(checkSingleRow(row) && checkSingleColumn(column) &&
checkSingleBox(row, column))) {
//Do filler() on the same box.
filler(currentIndex);
}
//If the number is 1-9, and there is no duplicate:
else {
currentIndex++;
filler(currentIndex);
}
}
/**
* Used to check if a single row has any duplicates or not. This is
called by the
* filler method.
* @param row
* @return
*/
public static boolean checkSingleRow(int row) {
return checkDupl(puzzle[row]);
}
/**
* Used to check if a single column has any duplicates or not.
* filler method, as well as the checkColumns of the checker.
* @param column
* @return
*/
public static boolean checkSingleColumn(int column) {
int[] singleColumn = new int[9];
for(int i = 0; i < 9; i++) {
singleColumn[i] = puzzle[i][column];
}
return checkDupl(singleColumn);
}
public static boolean checkSingleBox(int row, int column) {
//Makes row and column be the first row and the first column of
the box in which
//this specific cell appears. So, for example, the box at
puzzle[3][7] will iterate
//through a box from rows 3-6 and columns 6-9 (exclusive).
row = (row / 3) * 3;
column = (column / 3) * 3;
//Iterates through the box
int[] newBox = new int[9];
int counter = 0;
for(int i = row; i < row + 3; i++) {
for(int j = row; j < row + 3; j++) {
newBox[counter] = puzzle[i][j];
counter++;
}
}
return checkDupl(newBox);
}
}
Why am I calling it a weird error? A few reasons:
The box that the error occurs on changes randomly (give or take a box).
The actual line of code that the error occurs on changes randomly (it
seems to always happen in the filler method, but that's probably just
because that's the biggest one.
Different compilers have different errors in different boxes (probably
related to 1)
What I assume is that I just wrote inefficient code, so though it's not an
actual infinite recursion, it's bad enough to call a Stack Overflow Error.
But if anyone that sees a glaring issue, I'd love to hear it. Thanks!

deprecated warnings in xcode and how to handle depracation

deprecated warnings in xcode and how to handle depracation

if ([self
respondsToSelector:@selector(dismissViewControllerAnimated:completion:)])
{[[self presentingViewController] dismissViewControllerAnimated:YES
completion:nil];} //post-iOS6.0
else {[self dismissModalViewControllerAnimated:YES];} //pre-iOS6.0
I'm doing the responds to selector (above) code to handle deprecated
methods. That way my app is compatible with older versions of iOS, but I'm
getting warnings in my code stating:
"'dismissModalViewControllerAnimated:' is deprecated: first deprecated in
iOS 6.0" I personally don't like any warning in my code, but more
importantly, I read somewhere that apple will complain about warnings in
your code.
1) Will Apple complain about warnings in your code?
2) Am I handling deprecated methods correctly?
3) Is there way to turn deprecated method method warnings off?

Select only specific patterns from a SQL column

Select only specific patterns from a SQL column

I have a need to select only a specific pattern from a SQL column. Its an
XML type column, however its not formatted as XML. Here's an example of
what might be contained in the column:
taSopDistribution
i 3
s W-13-I73516502
:d:
i 7
:d:
:d:
s 60-99-9999-99-20950-00
m 0
m 5.8800
s W-13
:d:
:d:
:d:
:d:
:d:
:d:
s 60-99-9999-00-60950-00
I need to be able to query this field and select only the pieces of data
that follow this pattern: ##-##-####-##-#####-##, and there will be
multiple matches.
For example, I need a query that returns the following values from the
example data field above:
60-99-9999-99-20950-00
60-99-9999-00-60950-00
Any help on this would be greatly appreciated! FYI, I'm using SQL Server 2012

Error rvm CLI may not be called from within /etc/rvmrc

Error rvm CLI may not be called from within /etc/rvmrc

After installing a multiuser (systemwide) RVM on Fedora 17 I get the
following error when logging in:
Error:
/etc/rvmrc is for rvm settings only.
rvm CLI may NOT be called from within /etc/rvmrc.
Skipping the loading of /etc/rvmrc
and the following when logging out:
bash: return: can only `return' from a function or sourced script
My /etc/rvmrc file is
umask u=rwx,g=rwx,o=rx
I've searched Google and SO for answers and all that I find do not appear
to be relevant to this case, they are mostly OSX.
Does anyone know the cause of this?

android: getView() calls items already deleted

android: getView() calls items already deleted

I have some troubles with my ListView. I've made my own Adapter to display
my custom item, with his getView() method. Basically i inserted a certain
number of items at the lunching of the app and then I made my own Thread
to load data from Internet, in order to update the old contents. The
problem is the follow: when i try to clear all the old items (to replace
them with the new data of the thread) then i got a null point exception,
probably caused by getView that call and already deleted item position (or
at least is my interpretation). Follow the code:
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.risultati);
myList = new ArrayList<RisultatiClass>();
populateList();
populateListView();
}
private void populateListView() {
// TODO Auto-generated method stub
adapter = new MyListAdapter();
myListView = (ListView) findViewById(R.id.listViewRisultati);
myListView.setAdapter(adapter);
}
private void populateList() {
Thread thread = new Thread()
{
@Override
public void run() {
String str = ConnectionOperations.getUrlHtml("http://gradio...");
String[] colonne = str.split("!");
String[] sq1 = colonne[0].split(",");
String[] sq2 = colonne[1].split(",");
String[] gf1 = colonne[2].split(",");
String[] gf2 = colonne[3].split(",");
String[] ts = colonne[4].split(",");
Log.w("myApp", ""+myList.size()+"");
myList.clear();
adapter.notifyDataSetChanged();
Log.w("myApp", ""+myList.size()+"");
for (int i=0; i<sq1.length; i++){
myList.add(i,new
RisultatiClass(sq1[i],sq2[i],gf1[i],gf2[i],ts[i]));
}
}
};
thread.start();
// TODO Auto-generated method stub
myList.add(new RisultatiClass("Roma AA","Lazio","2","3","Mag 21:00"));
myList.add(new RisultatiClass("Napoli AA","Milan","0","5","Mag 21:00"));
myList.add(new RisultatiClass("Napoli","Milan","0","5",""));
myList.add(new RisultatiClass("Napoli","Milan","0","5",""));
myList.add(new RisultatiClass("Napoli","Milan","0","5",""));
myList.add(new RisultatiClass("Napoli","Milan","0","5",""));
}
//definisco l'adapter
private class MyListAdapter extends ArrayAdapter<RisultatiClass>{
public MyListAdapter(){
super(Risultati.this,R.layout.risultati_row,myList);
}
@Override
public View getView(int position,View convertView,ViewGroup parent){
//make sure we have a view to work with
View itemView = convertView;
if(itemView==null){
itemView = getLayoutInflater().inflate(R.layout.risultati_row,
parent,false);
}
//find the items
RisultatiClass currentItem = myList.get(position);
//fill the view
TextView sq1 = (TextView) itemView.findViewById(R.id.risultatiSq1);
sq1.setText(currentItem.getSq1());
TextView sq2 = (TextView) itemView.findViewById(R.id.risultatiSq2);
sq2.setText(currentItem.getSq2());
TextView ris1 = (TextView) itemView.findViewById(R.id.risultatiRis1);
ris1.setText(currentItem.getRis1());
TextView ris2 = (TextView) itemView.findViewById(R.id.risultatiRis2);
ris2.setText(currentItem.getRis2());
TextView timeStamp = (TextView)
itemView.findViewById(R.id.risultatiTimeStamp);
timeStamp.setText(currentItem.getTimeStamp());
return itemView;
}
Do you guys see any error? this is the log: 08-31 19:00:57.620:
E/AndroidRuntime(1416): java.lang.IndexOutOfBoundsException: Invalid index
3, size is 3 08-31 19:00:57.620: E/AndroidRuntime(1416): at
java.util.ArrayList.get(ArrayList.java:308)

jQuery UI Drag n Drop failed to lock

jQuery UI Drag n Drop failed to lock

Basically I have an image (droppable) and text (draggable). They are
matched by the data-pair attribute I've set on them. However, when I try
to console.log($(this).data('pair')) inside the drop callback, it gives
undefined. This is my code.
function handleDrop(event, ui, cb) {
console.log( $(this).data('pair') );
console.log( $(this).attr('data-pair') );
console.log( ui.draggable.data('pair') );
var dropped = $(this).data('pair');
var dragged = ui.draggable.data('pair');
var match = false;
if(dragged === dropped) {
//Match - Lock in place and increment found
match = true;
$(this).droppable( 'disable' );
ui.draggable.addClass( 'correct' );
ui.draggable.draggable( 'disable' );
ui.draggable.draggable( 'option', 'revert', false );
ui.draggable.position({
of: $(this),
my: 'left top',
at: 'left top'
});
} else {
ui.draggable.draggable( 'option', 'revert', true );
}
cb(match);
}
//Create Droppables (image + droppable div)
//imgContainer = #imgWrapper
var tempImgContainer = $('<div id="imgContainer' + i + '"></div>');
$('<img id="img' + i + '" src="' + key + '">').appendTo(tempImgContainer);
$('<div id="textForImg' + i + '" data-pair="' + i + '"></div>').droppable({
accept: '#textWrapper div',
hoverClass: 'hovered',
drop: function(event, ui) {
handleDrop(event, ui, callback);
}
}).appendTo(tempImgContainer);
$(imgContainer).append(tempImgContainer);
//Create Draggable
//textContainer = #textWrapper
var tempTextContainer = $('<div id="textContainer' + i + '" data-pair="' +
i + '">' + val + '</div>').draggable({
//quizContainer is a wrapper for both imgWrapper and textWrapper.
Example #quizContainer1
containment: quizContainer,
stack: '#textWrapper div',
cursor: 'move',
revert: true,
snap: true
});
$(textContainer).append(tempTextContainer);
i += 1;

Unable to cast String to DateTime

Unable to cast String to DateTime

I've following TextBox with ajax calender extender and on TextChanged
event I am calling "txtFromDate_TextChanged" function.
asp code:
<asp:TextBox ID="txtFromDate" runat="server" AutoPostBack="True"
ontextchanged="txtFromDate_TextChanged"></asp:TextBox>
asp:CalendarExtender ID="txtFromDate_CalendarExtender"
Format="dd/MM/yyyy" runat="server" Enabled="True"
TargetControlID="txtFromDate">
</asp:CalendarExtender>
c# code:
protected void txtFromDate_TextChanged(object sender, EventArgs e)
{
if (txtFromDate.Text != "")
{
DateTime fromdate = Convert.ToDateTime(txtFromDate.Text);
Query = Query + "And CONVERT(DATETIME, FLOOR(CONVERT(FLOAT,
ord_del_date))) >= '" + fromdate.ToString("yyyy'-'MM'-'dd") + "'";
}
}
This code is working all fine when i debug through visual studio and even
when I host the site on my local IIS server. The problem is that when I
host the site on my online hosting server and when I pick a date from
calender and calls a textchanged event it gives following error:
Error:
String was not recognized as a valid DateTime.
I know it is giving error because of line:
DateTime fromdate = Convert.ToDateTime(txtFromDate.Text);
But I am not finding anything wrong in this code. This code is working
perfectly fine from visual studio or when hosted on IIS but I am totally
confused why it isn't working when hosted on hosting server. I am totally
confused. Please help me out.

Friday, 30 August 2013

Value from Grails controller breaking javascript in gsp

Value from Grails controller breaking javascript in gsp

I am passing XML string from grails controller to gsp and need to use it
in the javascript function.
My controller code is
render(view: "list",model: [dataXML: callXML.getXmlString()])
The javascript function in gsp code is
function parseXML(){
alert("in parseXML");
xmlStr = "${dataXML}";
}
As soon as the ${dataXML} comes in function it breaks the code. I tried
without quotes, still same problem. What is that I am doing wrong?
Thanks in advance.

Thursday, 29 August 2013

Improve performance of Perl search file script

Improve performance of Perl search file script

I have recently noticed that a quick script I had written in Perl that was
designed to be used on sub 10MB files has been modified, re-tasked and
used in 40MB+ text files with significant performance issues in a batch
environment.
The jobs have been running for about 12 hours per run when encountering a
large text file and I am wondering how do I improve the perfomance of the
code? Should I slurp the file into memory and if I do it will break the
jobs reliance on the line numbers in the file. Any constructive thought
would be greatly appreciated, I know the job is looping through the file
too many times but how to reduce that?
#!/usr/bin/perl
use strict;
use warnings;
my $filename = "$ARGV[0]"; # This is needed for regular batch use
my $cancfile = "$ARGV[1]"; # This is needed for regular batch use
my @num =();
open(FILE, "<", "$filename") || error("Cannot open file ($!)");
while (<FILE>)
{
push (@num, $.) if (/^P\|/)
}
close FILE;
my $start;
my $end;
my $loop = scalar(@num);
my $counter =1;
my $test;
open (OUTCANC, ">>$cancfile") || error ("Could not open file: ($!)");
#Lets print out the letters minus the CANCEL letters
for ( 1 .. $loop )
{
$start = shift(@num) if ( ! $start );
$end = shift(@num);
my $next = $end;
$end--;
my $exclude = "FALSE";
open(FILE, "<", "$filename") || error("Cannot open file ($!)");
while (<FILE>)
{
my $line = $_;
$test = $. if ( eof );
if ( $. == $start && $line =~
/^P\|[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]\|1I\|IR\|/)
{
print OUTCANC "$line";
$exclude = "TRUECANC";
next;
}
if ( $. >= $start && $. <= $end && $exclude =~ "TRUECANC")
{
print OUTCANC "$line";
} elsif ( $. >= $start && $. <= $end && $exclude =~ "FALSE"){
print $_;
}
}
close FILE;
$end = ++$test if ( $end < $start );
$start = $next if ($next);
}
#Lets print the last letter in the file
my $exclude = "FALSE";
open(FILE, "<", "$filename") || error("Cannot open file ($!)");
while (<FILE>)
{
my $line = $_;
if ( $. == $start && $line =~
/^P\|[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]\|1I\|IR\|/)
{
$exclude = "TRUECANC";
next;
}
if ( $. >= $start && $. <= $end && $exclude =~ "TRUECANC")
{
print OUTCANC "$line";
} elsif ( $. >= $start && $. <= $end && $exclude =~ "FALSE"){
print $_;
}
}
close FILE;
close OUTCANC;
#----------------------------------------------------------------
sub message
{
my $m = shift or return;
print("$m\n");
}
sub error
{
my $e = shift || 'unknown error';
print("$0: $e\n");
exit 0;
}

Wednesday, 28 August 2013

Still show div when textarea/input onblur / loses focus

Still show div when textarea/input onblur / loses focus

so I try to hide/show a div element with using onfocus and onblur:
<textarea
onfocus="document.getElementById('divID1').style.display='block';"
onblur="document.getElementById('divID1').style.display='none';"></textarea>
<div id="divID1">
This works fine, but the problem is that the div hides again when the
textarea/input doesn't have focus anymore.
This is the whole code: JSFIDDLE link.
You can see that you can't check the Checkbox or select text.
What can I do to still display the div element when the textarea lost
focus or to make the textarea still having focus when I clicked on the
div?
Sorry, but I'm new to Javascript.
Thanks in advance,
Philipp

Simple MySQL Issue

Simple MySQL Issue

OK I have a column with a W or L to designate a win or loss. I want to
count all the wins and losses, and get a win percentage.
SELECT banner_name, count(win_loss) as wins
FROM drop_log
where win_loss = 'W'
group by banner_name
This gives me all the teams and how many wins they have. How would I tweak
this to have another column for losses and another one for ratio. MySQL
appears to have different syntax rules than SQL Server 2008.

Facebook api login success but not return success paper

Facebook api login success but not return success paper

i am writing a windows phone game with facebook integrated. I have a problem.
After I logged in with right username/password. It showed: "... would like
to access your public profile...". And i press Ok. Then another message:
".... would like to post on your behalf". And OK. It navigated to
"m.facebook.com/dialog/oauth/write" - a blank paper. No success paper or
access token returned. Then i debugged again. After logged in, It
navigated to Success paper and access token.
My question is why?? Are there some way to skip ".... would like to post
on your behalf" message.
Thanks for reading my question :D

Cisco Ip Phone not working on D link setup

Cisco Ip Phone not working on D link setup

User has a home network setup using Cisco Router and D link Ethernet Kid
setup. I send him a Cisco IP phone 7965 which was configured to work thru
VPN connection. User is not able to get the phone to work when connecting
thru Dlink. I did some troubleshooting and from IP address that he has on
the phone looks like phone is not getting connection. I ask him to plug in
the phone direclty to Cisco Router. He did and phone workded perfectly
fine!
the problem is that his office is setup on 2nd floor but his Router is
setup on the 1st floor. and he using Dlink to pull the signal from the 1st
to 2nd floor. Is any one familiar with Dlink setup? Is there any
configuration that I can do remotely on Dlink to allow connection to the
IP phone? What is my other option??
Urgent please.
Any information will be appriciated. Thank you, Serge

How to retrieve data on button and move to Next button?

How to retrieve data on button and move to Next button?

Welcome! I am working on Android quiz . I Have create my database with one
question and four option
and difficulty level. i created a layout with one text to display the
question and four button .Now problem is how to connect my database with
question and four button.so, when i click on right button it goes to next
question and when i click on wrong button it gives error and exist.
MyCode In XML
enter cod<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:gravity="center_horizontal"
android:background="@drawable/background">
<LinearLayout android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="110dp"
android:paddingTop="5dip" android:paddingBottom="5dip"
android:gravity="center_horizontal">
<ImageView
android:id="@+id/logo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingBottom="1dip"
android:paddingTop="1dip"
android:src="@drawable/logo2" />
</LinearLayout>
<LinearLayout android:orientation="horizontal"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:paddingTop="5dip" android:paddingBottom="5dip"
android:gravity="center_horizontal">
<RadioGroup android:layout_width="fill_parent"
android:layout_height="wrap_content" android:orientation="vertical"
android:background="#99CCFF"
android:id="@+id/group1">
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#0000CC"
android:textStyle="bold" android:id="@+id/question"/>
<Button android:onClick="false" android:id="@+id/answer1"
android:layout_width="150dip" />
<Button android:onClick="false" android:id="@+id/answer2"
android:layout_width="150dip" />
<Button android:onClick="false" android:id="@+id/answer3"
android:layout_width="150dip"/>
<Button android:onClick="false" android:id="@+id/answer4"
android:layout_width="150dip" />
</RadioGroup>
</LinearLayout>
MY DBHelper.java
public class DBHelper extends SQLiteOpenHelper{
//The Android's default system path of your application database.
private static String DB_PATH = "/data/data/com.starchazer.cyk/databases/";
private static String DB_NAME = "questionsDb";
private SQLiteDatabase myDataBase;
private final Context myContext;
/**
* Constructor
* Takes and keeps a reference of the passed context in order to access to
the application assets and resources.
* @param context
*/
public DBHelper(Context context) {
super(context, DB_NAME, null, 1);
this.myContext = context;
}
/**
* Creates a empty database on the system and rewrites it with your own
database.
* */
public void createDataBase() throws IOException{
boolean dbExist = checkDataBase();
if(!dbExist)
{
//By calling this method and empty database will be created into
the default system path
//of your application so we are gonna be able to overwrite that
database with our database.
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
/**
* Check if the database already exist to avoid re-copying the file each
time you open the application.
* @return true if it exists, false if it doesn't
*/
private boolean checkDataBase(){
SQLiteDatabase checkDB = null;
try{
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READONLY);
}catch(SQLiteException e){
//database does't exist yet.
}
if(checkDB != null){
checkDB.close();
}
return checkDB != null ? true : false;
}
/**
* Copies your database from your local assets-folder to the just created
empty database in the
* system folder, from where it can be accessed and handled.
* This is done by transfering bytestream.
* */
private void copyDataBase() throws IOException{
//Open your local db as the input stream
InputStream myInput = myContext.getAssets().open(DB_NAME);
// Path to the just created empty db
String outFileName = DB_PATH + DB_NAME;
//Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
//transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer))>0){
myOutput.write(buffer, 0, length);
}
//Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
public void openDataBase() throws SQLException{
//Open the database
String myPath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READONLY);
}
@Override
public synchronized void close() {
if(myDataBase != null)
myDataBase.close();
super.close();
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
// Add your public helper methods to access and get content from the
database.
// You could return cursors by doing "return myDataBase.query(....)" so
it'd be easy
// to you to create adapters for your views.
public List<Question> getQuestionSet(int difficulty, int numQ){
List<Question> questionSet = new ArrayList<Question>();
Cursor c = myDataBase.rawQuery("SELECT * FROM QUESTIONS WHERE
DIFFICULTY=" + difficulty +
" ORDER BY RANDOM() LIMIT " + numQ, null);
while (c.moveToNext()){
//Log.d("QUESTION", "Question Found in DB: " + c.getString(1));
Question q = new Question();
q.setQuestion(c.getString(1));
q.setAnswer(c.getString(2));
q.setOption1(c.getString(3));
q.setOption2(c.getString(4));
q.setOption3(c.getString(5));
q.setRating(difficulty);
questionSet.add(q);
}
return questionSet;
}
}

How to get location names nearby my current location using api v2 in android

How to get location names nearby my current location using api v2 in android

I am developing an application in which I have to fetch all the location
names nearby my current location(lat/long) and all location should come
under 1000meter radius.
Right now I am hitting below API URL for this:
https://maps.googleapis.com/maps/api/place/search/json?&location=22.724376,75.879668&radius=1000&sensor=false&key=AIzaSyD6Lqfrfx5AEINisuSToz-poqXnwsWSYTY
And I am getting response every time:
{
"debug_info" : [],
"html_attributions" : [],
"results" : [],
"status" : "REQUEST_DENIED"
}
My code:
private String makeUrl(double latitude, double longitude,String place)
{
StringBuilder urlString = new
StringBuilder("https://maps.googleapis.com/maps/api/place
/search/json?");
if (place.equals("")) {
urlString.append("&location=");
urlString.append(Double.toString(latitude));
urlString.append(",");
urlString.append(Double.toString(longitude));
urlString.append("&radius=1000");
//urlString.append("&types="+place);
urlString.append("&sensor=false&key=" + API_KEY);
} else {
urlString.append("&location=");
urlString.append(Double.toString(latitude));
urlString.append(",");
urlString.append(Double.toString(longitude));
urlString.append("&radius=1000");
//urlString.append("&types="+place);
urlString.append("&sensor=false&key=" + API_KEY);
}
return urlString.toString();
}
private String getUrlContents(String theUrl)
{
StringBuilder content = new StringBuilder();
try {
URL url = new URL(theUrl);
URLConnection urlConnection = url.openConnection();
BufferedReader bufferedReader = new BufferedReader(new
InputStreamReader(urlConnection.getInputStream()), 8);
String line;
while ((line = bufferedReader.readLine()) != null)
{
content.append(line + "\n");
}
bufferedReader.close();
}
catch (Exception e)
{
e.printStackTrace();
}
return content.toString();
}

Tuesday, 27 August 2013

How to fetch a server's hostname in a LAN

How to fetch a server's hostname in a LAN

i have a server in a LAN EX:ip http://192.168.12.8:8080/server/ <--- i
want this HostName
i used iPhone/iPad: How to get my IP address programmatically?
its all ok,i can fetch my iphone LAN ip:http://192.168.12.2
and i fetch LAN HostName use GCD
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0),
^{
NSString *iphoneLANIP = [self localIPAddress];//192.168.12.2
int i = [iphoneLANIP length];
NSRange range = NSMakeRange(8, i-8);//192.168. ---
NSString *aString = [iphoneLANIP substringWithRange:range];
NSString *deleteString = [aString substringFromIndex:[aString
rangeOfString:@"."].location+1];
int deleteI = [deleteString length];
//newIP = 192.168.12.
NSString *newIP = [iphoneLANIP substringToIndex:iphoneLANIP.length -
deleteI];
for (int x = 1 ; x <= 255 ; x ++){
NSURL *url = [NSURL URLWithString:[NSString
stringWithFormat:@"http://%@%d:8080/server/",newIP,x]];
NSString *urlString = [NSString stringWithContentsOfURL:url
encoding:NSUTF8StringEncoding error:nil];
if (urlString != nil){
NSLog(@"hostname ok %@",url);
break;
}else{
NSLog(@"hostname no %@",url);
}
}
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"IP OK");
});
});
i can find my server address :http://192.168.12.8:8080/server/
but I found that I need to use 5 minutes, or longer
how to faster fetch a server's hostname in a LAN?

Saved to Server, Want it to Update JSON File

Saved to Server, Want it to Update JSON File

Using BackgridJS.com for this project, and I want to be able to update
text in a cell, and have it automatically update the corresponding JSON
file. (The cell's original text is pulled from a JSON file"
From the BackgridJS website:
How do I save my row changes to the server immediately?
var MyModel = Backbone.Model.extend({
initialize: function () {
Backbone.Model.prototype.initialize.apply(this, arguments);
this.on("change", function (model, options) {
if (options && options.save === false) return;
model.save();
});
}
});
This works on my site, because when I update the cell, it POSTs
successfully. It posts like this:
city: "Example"
country: "Example"
type: "Example"
url: "http://example.com"
year: "Example"
I am using MAMP. How would I be able to update the JSON file when I update
the cell?

Navigation drawer using fragments showing errors.

Navigation drawer using fragments showing errors.

Here is the code.. I have tried importing import
"android.support.v4.app.Fragment", but the error pops up in
"getFragmentManager().beginTransaction().add(R.id.MAIN, details).commit()"
part.
I have no idea, what step I should take, I have been working on this
problem for a while. Any help is appreciated. Or is it possible to
implement navigation drawer without any fragment, but not using sliding
drawer??
`
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class FragmentTwo extends Activity{
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
if(savedInstanceState == null){
DetailsFragment details = new DetailsFragment();
details.setArguments(getIntent().getExtras());
getFragmentManager().beginTransaction().add(R.id.MAIN,
details).commit();
}
}
public static class DetailsFragment extends Fragment{
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState){
return inflater.inflate(R.layout.fragment_two, container, false);
}
}
}`

Adding directory to classpath in IntelliJ 12

Adding directory to classpath in IntelliJ 12

I know this has been addressed before here but this solution doesn't work
for me, and I don't know why.
I follow the given steps, but at 5 there is no dialog that comes up. I am
trying to add mp3plugin.jar to my dependencies, but after following this
process, I still get an UnsupportedAudioFileException at runtime.
What am I doing wrong?
Here is a screencast of what I am doing: http://www.screenr.com/G70H

Split google maps route in few equal segments

Split google maps route in few equal segments

I'm trying to find a way to split google distance route in few segments
and get points of it. Main idea is to get places(from google places
service) in between two points. But not for all route, just for few points
in between.
I was thinking about RouteBoxer (Link), but it might be cases, when "box"
is very large.
maybe you have any ideas how, after summing route distance, get point in
route after some distance? Let say, I have a route that is 1000km in
total. And then how to get point on the route in 200km? 500km? 700km? It
would be perfect for me. Thanks in advance.

How to set music files which are not in Media Store as ringtone

How to set music files which are not in Media Store as ringtone

Before Jelly Bean level 18 I can use music files which are not in Media
store (for example, a private .mp3 file in a folder contains .nomedia
file, so Media Scanner does not scan this folder and does not know about
this file) but from Android 4.3 (tested on Nexus 4) I can not do that, it
only works for music files which are already scanned by Media Scanner.
The real reason of this problem is I cannot insert ContentValues with
MediaColumns.DATA is a absolute path of a file not scanned by Media
Scanner, insert method always return null.
Uri newUri = getCR().insert(uri, contentValues); // returns null in
Android 4.3
Does anyone have a workaround to use a private file (not scanned and not
recognized by Media Scanner) as ringtone?

output of prefix postfix expressions in C/C++

output of prefix postfix expressions in C/C++

Following is an example code:
#include<stdio.h>
void main(){
int i=0;
printf("%d,%d,%d", i++, i, ++i);
return 0;
}
Are questions like these compiler dependent or they have undefined
behavior? I am not able to devise a proper procedure for solving such
questions, it works for some but I get incorrect output for others.
More examples:
printf("%d,%d,%d", ++i, ++i, i++);
printf("%d,%d,%d", i, ++i, i++);
Is there a certain rule which GCC uses to solve such questions? Or this
has undefined behavior?

Monday, 26 August 2013

How can we sort images by date in PHP?

How can we sort images by date in PHP?

I have to sort images like the new iOS 7 Photos App.
I know how to sort them by date using exif_read_data or the date it was
uploaded however I would like to keep images grouped:
For example, if I take 20 pictures at a party between august 27 11pm and
august 28 1am, they will not be separated in two days but instead they
will display august 27 - 28
How can I achieve this in PHP?
Thank you!

Retrieve 10 random lines from a file

Retrieve 10 random lines from a file

I have a text file which is 10k long and I need to build a function to
extract 10 random lines each time from this file. I already found how to
generate random numbers in Python with numpy and also how to open a file
but I don't know how to mix it all together. Please help.

What's a good algorithm for finding if two objects are connected in a 2D grid?

What's a good algorithm for finding if two objects are connected in a 2D
grid?

I'm currently in the early stages of developing a game in which players
build spaceships by placing individual systems (cargo bay, weapon
controls, crew quarters, etc.) on a 2D grid. The "root" part of the ship
is the bridge where the captain sits and orders people around. What I need
is an algorithm that can check to make sure that every part is connected
to the bridge, either directly or by connecting to another series of parts
that can be traced back to the bridge. Naturally, a part will be deleted
it it isn't somehow connected to the bridge. Anyone know of an algorithm
that can do this?

Developing Android App | Should I set minSdkVersion to 10?

Developing Android App | Should I set minSdkVersion to 10?

Via http://developer.android.com/about/dashboards/index.html I still see
that API 10 (2.3.3) still has a large usage, and it would seem to be good
to support it; however, I do see that API 16+ (4.1+) are increasing in
usage pretty fast. It looks like it is doing so by reducing usage of API
10.
I have been wanting to see a chart that could have showed be the usage of
API 10 over the years and see the RATE at which it is being reduced by. I
have looked at Google's Cached version, but that only take me back a week.
I have looked at Wayback Machine's version
(http://web.archive.org/web/20130408124813/http://developer.android.com/about/dashboards/index.html),
but they don't contain the pictures anymore!!
I know that API 10 (basically all of Gingerbread) is being used less and
less, and I am just trying to figure out how long from now (based on
trajectories) when API 10 will be basically a real question if it should
be built for or not...right now it kind of is a necessity (33%).
Is it worth the time and money to implement API 10 if in 6 months (or 1
year) from now that percentage is only 5 - 10%??

Associate specific SLF4J logger with Jetty embedded

Associate specific SLF4J logger with Jetty embedded

I'm trying to assign a specific SLF4J logger instance to my Jetty embedded
server using the following lines of code:
Logger myLogger = LoggerFactory.getLogger("Web Server");
Log.setLog((org.eclipse.jetty.util.log.Logger) myLogger)
where myLogger is an instance of org.slf4j.Logger. This returns a
ClassCastException since
org.slf4j.impl.Log4jLoggerAdapter cannot be cast to
org.eclipse.jetty.util.log.Logger`
How then can I go about this process?

PyQt4: Use a heat map as a background for a QTableWidget

PyQt4: Use a heat map as a background for a QTableWidget

I use PyQt4 and I have a QTableWidget, at each cell I have a float. I
would like to use background colors, to order visually the values that are
the most similar in each row. I thougt about a heatmap but I don't know
how to do it.
Any idea?
Thanks

Silently ignore unavailable data source at application start up

Silently ignore unavailable data source at application start up

I have an EJB application which uses JPA 2.0 on Glassfish 3.1.2 (provider
is EclipseLink). When the database is down the application does not start.
This is because EclipseLink does some initial verification.
Is there a way that the application starts even if the database is down?
Background: The resource being unavailable comes not into play until the
first business function is called which accesses the database. From
application startup till the first business function call there is a time
window where the database may be started.

How can I read X509 Subject Alternative Name from .NET

How can I read X509 Subject Alternative Name from .NET

Recently a site I shoot up some data to moved to a CDN and now their SSL
certificate Subject, instead of site name, contains generic
'sslserver43552' info. Their domain name now exists under "Subject
Alternative Name" (among other things).
So previously I had
ServicePointManager.ServerCertificateValidationCallback = ((sender1, cert,
chain, errors) => Cert.Subject.Contains("blah"));
Ideally I'd like to replace Subject with SubjectAlternativeName in above
code. How do I do it?

Account Sync option In Contacts

Account Sync option In Contacts

I want my application to be seen in contacts synchronization option.. I
have added account and it works well using this.
I can add account as well synchronize my contacts But My application is
not showing in "Display Option" .. Please help me out with this problem.
Thanks in advance.. :)
I tried this

Sunday, 25 August 2013

How to get rid of multiple sets of parentheses in an array

How to get rid of multiple sets of parentheses in an array

I'm using RESTKit to do some object mapping for a JSON and I'm mapping an
array. The JSON that I'm mapping looks like this:
"parameters":[{"parameter_value":["Smith"]}, {"parameter_value":[66211]}]
The array that I'm getting looks like this:
Parameter Value: (
(
Smith
),
(
66211
)
)
When I try to convert the array to a string via this code: NSString
*nameidvalue = [[parameterValueArray valueForKey:@"description"]
componentsJoinedByString:@""]; The string nameidvalue turns into this:
(
Smith
)(
66211
)
How exactly do I get rid of the parentheses so what I'm left with is
Smith, 66211

Object of class mysqli_result could not be converted to int

Object of class mysqli_result could not be converted to int

i'm trying to create a php countdown for my automated watering, i'm going
to have crontab run this every minute and turn of the watering
automatically. the code is as follows
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
include 'php_serial.class.php';
require_once 'login.php';
//connect to server
$con = mysqli_connect($server,$username,$password);
if(!$con){
die("Failed to connect:" . mysqli_connect_error());
}
else {
//check database connection
$open_db = mysqli_select_db($con,$db);
if(!$open_db){
die("Cannot connect to vatten database" . mysqli_error());
}
}
//check time_left
$sql = "SELECT time_left FROM `info`";
$time_left = mysqli_query($con,$sql);
$sql2 = "SELECT last_sent FROM `info`";
$last_sent = mysqli_query($con,$sql2);
if(!$time_left) {
die("Database access failed" . mysqli_error($con));
}
if($time_left >0) { // Error 1 here
$time_left = $time_left-1; // Error 2 here
mysqli_query($con, "UPDATE info SET time_left=$time_left");
}
elseif($time_left <1 && $last_sent !== "[LOOOOOO]") {
$serial = new phpSerial;
$serial->deviceSet("/dev/ttyUSB0");
$serial->confBaudRate(1200);
$serial->confParity("none");
$serial->confCharacterLength(8);
$serial->confStopBits(1);
$serial->deviceOpen();
$serial->sendMessage("[LOOOOOO]");
mysqli_query($con, "UPDATE info SET time_left=$time_left");
}
mysqli_close($con);
?>
So the error i'm getting is Notice: Object of class mysqli_result could
not be converted to int in /var/www/vatten/check.php on line 27
and another one like that but for line 28.
And apart from that it resets the "time_left" in the database to 0
Any help would be appreciated!

opencv function implementation

opencv function implementation

I wonder how does opencv do operations on Matrices. For example, when I
write code for
cv::add (Mat mat1, Mat mat2, Mat &result)
using two for loops, it takes around 120-130 ms for 1000x750 image. But
using opencv add function it takes 6-7 ms. Does anyone know what is their
trick? I want to learn it to be able to write functions that opencv
doesn't have.
I have searched inside opencv and find this two .cpp files(first, second)
but I dont know if I'm looking at correct place.
I just want to know how to use this power. Could somebody help me?
Thanks,

What is the reason for this output?

What is the reason for this output?

I have the following code.
int x=80;
int &y=x;
x++;
cout<<x<<" "<<--y;
The output comes out to be 80 80. And I don't understand how. I thought
the output of x would be 81 although I don't know anything about y. How is
the reference variable affected by the decrement operator. Can someone
please explain?

Saturday, 24 August 2013

Change desktop Google Drive account without permission to access old account

Change desktop Google Drive account without permission to access old account

I used my home computer for desktop Google Drive with my work email
account. Once I left the company, they changed the password on the
account. I would now like to use Google Drive desktop with my personal
email address. I am not able to access preferences to disable the old
account since I don't know the new password they established for that
account. How can I disable desktop Drive with that account and initiate
desktop Drive with my personal account, without knowing the password for
the work account?
Thank you!

Having trouble with PhoneGap iOS app

Having trouble with PhoneGap iOS app

I'm new to PhoneGap Build, and I'm trying to start creating an app in PG
Build. I tried just moving everything over, but I'm having trouble, so I
started by trying to make a simple app that just shows an alert box. This
is still not working, so I thought I'd post my code and see if I can get
some help. I have tried multiple different pieces of code, but they don't
seem to be working.
I'm testing on an iPad mini, and I have the Apple developer account. The
app loads fine-the only problem is that the alert box doesn't
show...here's the code:
index.html
<!DOCTYPE html>
<html>
<head>
<title>Notification Example</title>
<script src="phonegap.js"></script>
<script type="text/javascript" charset="utf-8">
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
//Empty
}
function alertDismissed() {
//Do something
}
function showAlert() {
navigator.notification.alert(
'You are the winner!',
alertDismissed,
'Game Over',
'Done'
);
}
</script>
</head>
<body>
<p><a href="#" onclick="showAlert(); return false;">Show Alert</a></p>
</body>
</html>
config.xml
(stripped irrelevant code for ease of reading)
....
<feature name="http://api.phonegap.com/1.0/battery"/>
<feature name="http://api.phonegap.com/1.0/camera"/>
<feature name="http://api.phonegap.com/1.0/contacts"/>
<feature name="http://api.phonegap.com/1.0/file"/>
<feature name="http://api.phonegap.com/1.0/geolocation"/>
<feature name="http://api.phonegap.com/1.0/media"/>
<feature name="http://api.phonegap.com/1.0/network"/>
<feature name="http://api.phonegap.com/1.0/notification"/>
....
Can anyone help? Like I said, I'm new to PG, so I'd really appreciate and
help I can get! Thanks!

((((((((((((( __ READ __ BEFORE ___ DELETED ___ BY ___ MODS ___ ))))))))))))))

((((((((((((( __ READ __ BEFORE ___ DELETED ___ BY ___ MODS ___
))))))))))))))

You are about to be provided with information to
start your own Google.
Some people posted comments and said this can not
be done because google has 1 million servers and we do not.
The truth is, google has those many servers for trolling
purposes (e.g. google +, google finance, youtube the bandwidth consuming
no-profit making web site, etc ).
all for trolling purposes.
if you wanted to start your own search engine...
you need to know few things.
1: you need to know how beautiful mysql is.
2: you need to not listen to people that tell you to use a framework
with python, and simply use mod-wsgi.
3: you need to cache popular searches when your search engine is running.
4: you need to connect numbers to words. maybe even something like..
numbers to numbers to words.
in other words let's say in the past 24 hours people searched for
some phrases over and over again.. you cache those and assign numbers
to them, this way you are matching numbers with numbers in mysql.
not words with words.
in other words let's say google uses 1/2 their servers for trolling
and 1/2 for search engine.
we need technology and ideas so that you can run a search engine
on 1 or 2 dedicated servers that cost no more than $100/month each.
once you make money, you can begin buying more and more servers.
after you make lots of money.. you probably gonna turn into a troll
too like google inc.
because god is brutal.
god is void-state
it keeps singing you songs when you are sleeping and says
"nothing matters, there is simply no meaning"
but of course to start this search engine, you need a jump start.
if you notice google constantly links to other web sites with a
trackable way when people click on search results.
this means google knows which web sites are becoming popular
are popular, etc. they can see what is rising before it rises.
it's like being able to see the future.
the computer tells them " you better get in touch with this guy
before he becomes rich and becomes un-stopable "
sometimes they send cops onto people. etc.
AMAZON INC however..

will provide you with the top 1 million web sites in the world.
updated daily in a csv file.
downloadable at alexa.com
simply click on 'top sites' and then you will see the downloadable
file on the right side.
everyday they update it. and it is being given away for free.
google would never do this.
amazon does this.
this list you can use to ensure you show the top sites first in your
search engine .
this makes your search engine look 'credible'
in other words as you start making money, you first display things
in a "Generic" way but at the same time not in a "questionable" way
by displaying them based on "rank"
of course amazon only gives you URLS of the web sites.
you need to grab the title and etc from the web sites.
the truth is, to get started you do not need everything from web sites.
a title and some tags is all you need.
simple.
basic.
functional
will get peoples attention.
i always ask questions on SO but most questions get deleted. here's
something that did not get deleted..
How do I ensure that re.findall() stops at the right place?
use python, skrew php, php is no good.
do not use python frameworks, it's all lies and b.s. use mod-wsgi
use memcache to cache the templates and thus no need for a template engine.

always look at russian dedicated servers, and so on.
do not put your trust in america.
it has all turned into a mafia.

google can file a report, fbi can send cops onto you, and next thing you know
they frame you as a criminal, thug, mentally ill, bipolar, peadophile, and
so on.
all you can do is bleed to death behind bars.
do not give into the lies of AMERICA.
find russian dedicated servers.
i tried signing up with pw-service.com but i couldn't do it due to
restrictions with their russian payment systems and so on..
again, amazon's web site alexa.com provides you with downloadable
top 1 mil web sites in the form of a csv file.
use it.
again, do not give into python programmers suggesting frameworks for python.
it's all b.s. use mod_wsgi with memcache.
again, american corporations can ruin you with lies and all you can do is
bleed to death behind bars
again, a basic search engine needs : url, title, tags, and popular searches
can be "cached" and words can be connected to "numbers" within the mysql.
mysql has capabilities to cache things as well.
cache once, cache twice, and you will not need 1 million servers in order
to troll.
if you need some xdotool commands to deal with people calling you a troll
here it is;
xdotool key ctrl+c
xdotool key Tab Tab Tab Return
xdotool type '@'
xdotool key ctrl+v
xdotool type --clearmodifiers ', there can not be such thing as a `troll`
unless compared to a stationary point, if you are complaining, you are not
stationary. which means you are the one that is trolling.'
xdotool key Tab Return
create an application launcher on your gnome-panel, and then select the
username in the comments section that called you a 'troll' and click the
shortcut on the gnome-panel.
it will copy the selected username to the clipboard and then hit TAB TAB
TAB RETURN
which opens the comment typing box. and then it will type @ + username +
comma, and then the rest. ..........................................
............................... -----------------------------------

Merging n Dictionary instances & execute action on duplicate keys

Merging n Dictionary instances & execute action on duplicate keys

I want to merge an arbitrary amount of Dictionary instances, if a key
occurs multiple times I want to execute an action, e.g. currentResultValue
+= newFoundValue.
Sample context: Map/Reduce pattern, reduce step, I counted the occurences
of words in a really big text and had 10 mappings, each returning a
Dictionary<string, int>. In the reduce call I now want to merge all those
dictionaries into one.
Example input:
Dictionary 1:
"key1" -> 5
"key2" -> 3
Dictionary 2:
"key2" -> 1
Dictionary 3:
"key1" -> 2
"key3" -> 17
Expected result:
"key1" -> 7
"key2" -> 4
"key3" -> 17
I'd prefer a LINQ-based solution, e.g. something like:
IEnumerable<IDictionary<string, int>> myDictionaries = ...;
myDictionaries.Reduce((curValue, newValue) => curValue + newValue);
Do I have to write my extension method myself or is something like that
already existing?

JQuery speed vs javascript speed

JQuery speed vs javascript speed

I know Jquery is just a library of javascript.
is Jquery animation and events slower then javascript? If so, how much
slower.
i am trying to decide if i should rewrite my site in native javascript.

undo or delete lines one by one on a QgraphicsScene

undo or delete lines one by one on a QgraphicsScene

I have a QGraphicsView subclass that load an image and user draw some line
on that image by click like this:
void TabView::mousePressEvent(QMouseEvent *event){
if (event->button() == Qt::LeftButton) {
scene->addLine(line);
}
}
now i have to add undo. so I add a QList like this:
void TabView::mousePressEvent(QMouseEvent *event){
if (event->button() == Qt::LeftButton) {
lineList<<line;
scene->addLine(lineList.last());
}
}
and for undo by Delete press
void TabView::keyPressEvent(QKeyEvent * event){
int key = event->key();
switch(key){
case Qt::Key_Delete:
{
lineList.removeLast();
foreach(QLineF line, lineList){
scene->addLine(line);
}
scene->update();
break;
}
}
}
nothing happen, I've tried this
case Qt::Key_Delete:
QGraphicsLineItem *item = new QGraphicsLineItem(lineList.last());
scene->removeItem(item);
scene->update();
break;
still nothing.
how I can undo or just delete items one by one on a QgraphicsScene? any
idea is well appreciated.

how can i remove duplicate values by using distinct keyword

how can i remove duplicate values by using distinct keyword

I've a table with records like this
*************************** 1. row *************************
did: 98
brand_name: Aarther P (100+500)
generic: Paracetamol, Aceclofenac
tradename: Aarther P (100+500)
manfactured: Rekvina Pharmaceuticals
unit: 500mg/100mg
type: Tablet
quantity: 10Tablet
price: 27.9
*************************** 2. row *************************
did: 99
brand_name: Aarther-P
generic: Aceclofenac, Paracetamol
tradename: Aarther-P
manfactured: Rekvina Pharmaceuticals
unit: 100mg/500mg
type: Tablet
quantity: 10Tablet
price: 27.9
*************************** 3. row ************************
did: 100
brand_name: Aarticef (1000mg)
generic: NULL
tradename: Aarticef (1000mg)
manfactured: Alpic Remedies Ltd
unit: 1000mg/vial
type: Injection
quantity: 1Vial
price: 96
I want to eliminate duplicate manfactured names,for that i have executed
the following query
select brand_name,generic,manfactured from drugs_info group by manfactured;
but it displaying 1st and 3rd records only like follow, but i want 2nd record
*************************** 1. row *************************
did: 98
brand_name: Aarther P (100+500)
generic: Paracetamol, Aceclofenac
tradename: Aarther P (100+500)
manfactured: Rekvina Pharmaceuticals
unit: 500mg/100mg
type: Tablet
quantity: 10Tablet
price: 27.9
*************************** 3. row ************************
did: 100
brand_name: Aarticef (1000mg)
generic: NULL
tradename: Aarticef (1000mg)
manfactured: Alpic Remedies Ltd
unit: 1000mg/vial
type: Injection
quantity: 1Vial
price: 96
how can i write select query for my requirement.please help me..

Friday, 23 August 2013

bash indirect reference by reference

bash indirect reference by reference

A lot of similar questions, but hadn't found one for using a variable in
the name this way:
#!/bin/bash
# $1 should be 'dev' or 'stg'
dev_path="/path/to/dev"
stg_path="/path/to/stg"
# Use $1 as input to determine which path to 'execute' to execute
${!\$1'_path'}/bin/execute
Using $1, I want to be able to reference either $dev_path or $stg_path ($1
== 'dev' or $1 == 'stg')
I've tried various iterations of using ! and \$ in various places from
other posts, but no luck

Is there a way to load a json file along with all the other js files?

Is there a way to load a json file along with all the other js files?

I"m wondering if there's a way to load a JSON file without having to use
AJAX with jQuery. I already have the json file in the folder, so it would
seem a bit wasteful to load the file after everything else is loaded with
AJAX. My folders look like this:
css/
font/
html/
img/
config.json
So I would like to have the data available as soon as the js is available
instead of having to use jQuery or another method to fetch it later.
Thanks in advance.

PHP timezone from php.ini not being applied

PHP timezone from php.ini not being applied

For some reason the date() function is not outputting the
timezone-adjusted date/time. In debugging this, I found a weird disparity.
My timezone is defined in php.ini as America/New_York. When I call this:
php echo ini_get('date.timezone');
I get America/New_York, which is what I expect. However, when I call this:
php echo date_default_timezone_get();
I get UTC. It seems this is responsible for the date() method returning
the time in the UTC timezone. Why is this happening? How do I make PHP
respect the timezone found in php.ini?

How should I load all the data from a column to a datagridview combobox?

How should I load all the data from a column to a datagridview combobox?

How can I make the codes work so that the datagridview combobox load with
the items listed in the "userid" column in my database? I want all the
items to be listed on the datagridview combobox from the "userid" column.
Here are the lines I've written so far..
Private Sub check()
cmd = New SqlCommand("Select UserID from info", con)
da = New SqlDataAdapter(cmd)
dt = New DataTable()
da.Fill(dt)
If dt.Rows.Count > 0 Then
ComboBox1.DataSource = dt
ComboBox1.DisplayMember = "UserID"
Dim dgvcolumn As New DataGridViewComboBoxColumn
With dgvcolumn
.Width = 150
.Items.Add(ComboBox1.Items)
.DataPropertyName = "UserID"
.HeaderText = "UserID"
End With
Else
End If
End Sub

Numerically Integrating Function Over Sphere Surface Using Irregular Differentials

Numerically Integrating Function Over Sphere Surface Using Irregular
Differentials

I'm trying to (numerically) integrate a scalar-valued function over the
surface of a unit sphere with irregularly spaced differentials. I take
mathematical standard spherical coordinates:$$x=sin(\phi)cos(\theta)\\
y=sin(\phi)sin(\theta)\\ z=cos(\phi)\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,$$
I need to integrate with $z$ and $\theta$ linear. This means that $\phi$
is nonlinear, of course.
I'm not really sure how I'd go about doing this. Using the Jacobian
determinant, I can get the spherical coordinate area element of $sin(\phi)
d\phi d\theta$, but using $sin(\phi) \Delta\phi \Delta\theta$ doesn't work
since it doesn't take into account $\phi$'s nonlinearity. Maybe I should
replace $\phi$ with $arccos(\phi)$ in the spherical coordinate definition
above and just try the Jacobian again?

Thursday, 22 August 2013

alternative for input type date

alternative for input type date

I was building an web site and used the html 5 input type date then I
found out that it worked only with chrome, is there a way to make it work
with other browsers or any better alternative?

Sometimes the Game Center authentication handler is never called

Sometimes the Game Center authentication handler is never called

In our iOS game, we're using Game Center to identify players and sync
their data across devices using our own servers. Because Game Center
identifies players, we need to know if they're authenticated, or if
they've changed authentication, etc. We have a title screen that displays
"Initializing Game Center..." until the authentication call returns, and
only once we know who they're authenticated as (if anyone) do we go into
the game.
However, a very small amount of the time (in fact, I can't reproduce it
myself), the authentication handler is never called, ever. Not even after
minutes of waiting. The Game Center welcome banner never displays either,
so it's not that just our handler is never called, but there really is no
authentication status, it seems.
So far we've implemented a 30-second timeout where if we don't hear
anything from Game Center, we assume the authentication status hasn't
changed, and we use your saved data. That 30 second timeout is not ideal,
so I'm wondering if there is any rhyme or reason to when GC does not
respond.
Here is the code that is called from our App Delegate's application:
didFinishLaunchingWithOptions: method:
PlayerModel *playerModel = [PlayerModel sharedPlayerModel];
GKLocalPlayer *localPlayer = [GKLocalPlayer localPlayer];
if ([localPlayer respondsToSelector:@selector(setAuthenticateHandler:)])
{
localPlayer.authenticateHandler = ^(UIViewController
*gkViewController, NSError *error)
{
if (localPlayer.authenticated)
{
[playerModel loadFromGameCenter];
playerModel.hasGCStatus = TRUE;
[playerModel sync];
}
else if (gkViewController)
{
[viewController presentViewController:gkViewController
animated:TRUE completion:nil];
}
else
{
NSLog(@"Could not authenticate with Game Center");
[playerModel unloadFromGameCenter];
playerModel.hasGCStatus = TRUE;
[playerModel sync];
}
};
}
else
{
[localPlayer authenticateWithCompletionHandler:^(NSError *error) {
if (localPlayer.authenticated)
{
[playerModel loadFromGameCenter];
playerModel.hasGCStatus = TRUE;
[playerModel sync];
}
else
{
NSLog(@"Could not authenticate with Game Center");
[playerModel unloadFromGameCenter];
playerModel.hasGCStatus = TRUE;
[playerModel sync];
}
}];
}

Variance of the first return time in a symmetric simple d-dimensional random walk

Variance of the first return time in a symmetric simple d-dimensional
random walk

I am trying to solve this problem....
I have a simple random walk on a $d$-regular finite graph. At each vertex
of the graph, the particle chooses one of $d$ edges equally likely. I need
to calculate the variance of first return time, i.e. the variance (or
second moment) of the time that takes until the particle is at the vertex
it started. I know that for the $i^{th}$ vertex second moment return time
is:
$ w_{ii}=-\frac{1}{\pi_i}+\frac{2z_{ii}}{\pi_i^2} $
where $\pi_i$ is the steady state probability and $z_{ii}$ is $(i,i)$
element of the fundamental matrix (fundamental matrix: $Z=(I-(A-P))^{-1}$,
$A$ is transition probability matrix and $P$ is steady state probability
matrix). I just do not know how to find $z_{ii}$ in terms of $d$. Can
anybody help to find the exact answer or an upper bound?

Update collection erases all information inside

Update collection erases all information inside

I am new to MongoDB and trying to perform my first updates.
I have my users collection that is populated by an insert statement. Now,
I want to add or insert the field authCode with some data into a specific
user.
My problem is that when I perform the following function the whole user
data becomes replaced by the information in that update statement. My
understanding is that by using upsert I would insert or update a users
collection. given that the user already exist I expect just the authCode
field to be created or updated.
Could anyone point out what am i doing wrong?
public function addAuthCode( array $userId, $code ) {
$user = $this->db()->user;
$user->update(
$userId,
array( 'authCode' => $code ),
array( 'upsert' => true, 'safe' => true )
);
}

Application object triggers custom event twice? Marionette v1.1.0

Application object triggers custom event twice? Marionette v1.1.0

I've a collection Days actually shared by 2 collections - collection view
v1 for adding or removing days (edit) and composite view v2 that displays
clickable links to navigate to the individual day's itemViews.
AppointmentManager = new Marionette.Application //app object.
To delete say appointments for day 2, user clicks on the delete button on
dayItemView2 in collectionview v1, which also causes the day to be deleted
from collection view v1, like so:
onDeleteDayClicked() {
this.model.collection.remove(this.model);
}
This deletion also gets reflected in the view v2, as collection is shared
across these two views. Day 2's navigation link is deleted from v2
automatically by Marionette.
The collection Days listens on this remove event in initialize. To ensure
that these changes are reflected and saved serverside (along with other
bits of info stored as part of the larger model that also stores
collection of days), I trigger on the application manager a save event:
Entities.Days = Backbone.Collection.extend({
initialize: function(options) {
this.on("remove", function(model,collection,index) {
AppointmentManager.trigger("appts:save");
}
});
However in my ApptController, I receive the apps:save event twice. I've
checked that collection Days receives only one delete event and only one
model is deleted , hence appts:save trigger is called ones.
ApptManager.listenTo(ApptManager, "appts:save", function() {
console.log("Saving appts!");
appts.set("days", days);
appts.save();
});
"Saving appts" gets printed twice and appts PUT twice!
Any clues?!
Using Marionette v1.1.0. I've got other modules and apps that display
header navbar view and other pages. My application structure is based on
Backbone.Marionette.js: A Gentle Introduction by David Sulc - although I
doubt if this packaging structure is of any relevance to this problem.

Error 1334 .File cannot be found in the Data1.cab

Error 1334 .File cannot be found in the Data1.cab

I am working on a Win 7-64 bit machine. I have a software installation
package which contains the .msi file, a CAB file and some MST files. I
wanted to modify the cabinet file. So I extracted the cab file using
CABARC utility.
But before making any changes to the extracted files, just for testing the
utility I removed the original cab file from the current directory. And
created a new cab file from the files extracted from the original cab
file, again using CABARC utility.
But now if I run the .msi file, it shows the error.
ERROR:1334. The file "XYZ" cannot be installed because the file cannot be
found in the cabinet file Data1.cab. This could indicate a network error,
an error reading from the CD-ROM, or a problem with this package.
But the file is present in the cabinet file I can see that. The same
installer is working fine with the original cab file.
I have tried different compression types (MSZIP, LZX:<15...21>) as well.
But none of them works. I have not removed/added any file in the cabinet
file. Am I doing anything wrong or if there is any other information that
a cabinet file stores ?
Thanks.

Wednesday, 21 August 2013

error during grouping files based on the date field

error during grouping files based on the date field

I have a large file which has 10,000 rows and each row has a date appended
at the end. All the fields in a row are tab separated. There are 10 dates
available and those 10 dates have randomly been assigned to all the 10,000
rows. I am now writing a java code to write all those rows with the same
date into a separate file where each file has the corresponding rows with
that date.
I am trying to do it using string manipulations, but when I am trying to
sort the rows based on date, I am getting an error while mentioning the
date and the error says the literal is out of range. Here is the code that
I used. Please have a look at it let me know if this is the right
approach, if not, kindly suggest a better approach. I tried changing the
datatype to Long, but still the same error. The row in the file looks
something like this: Each field is tab separated and the fields are:
business id, category, city, biz.name, longitude, state, latitude, type, date
**
qarobAbxGSHI7ygf1f7a_Q ["Sandwiches","Restaurants"] Gilbert Jersey Mike's
Subs -111.8120071 AZ 3.5 33.3788385 business 06012010
** The code is:
File f=new File(fn);
if(f.exists() && f.length()>0)
{
BufferedReader br=new BufferedReader(new FileReader(fn));
BufferedWriter bw = new BufferedWriter(new
FileWriter("FilteredDate.txt"));
String s=null;
while((s=br.readLine())!=null){
String[] st=s.split("\t");
if(Integer.parseInt(st[13])==06012010){
Thanks a lot for your time..

Almost surely statement in Willams book.

Almost surely statement in Willams book.

In Probability wih Martingales (Willams) I came across the following
proposition
and then they give the following contradictory example
Could someone please explain who it can be so? Also why is that in the
truth set they use $\rightarrow \frac{1}{2}$ and not $= \frac{1}{2}$ when
comparing each out come ?
Thank you.

Adding two images and make one

Adding two images and make one

I am new programming IOS app , and I got into this problem : I have two
images in the app that I want to post in twitter , but Twitter just accept
one picture to be uploaded , so I came out with the idea to make Image A +
Image B just One Image. I already have the posting and resizing the images
process done. However, I need help to make Image A + Image B just one
Image. Anyone can HELP? Thank you.

How to query all child objects of a list for matching entities?

How to query all child objects of a list for matching entities?

I'm a bit of a neophyte when it comes to LINQ and lambda expressions, I'm
hoping someone can help me out.
What I'm doing is creating an aggregate object from an ADO.NET
SqlDataReader with multiple data 'tables' in the response.
The recordsets look like this:
Foo
FooId
...other descriptive fields

Bar
BarId
FooId
...other descriptive fields

Baz
BazId
BarId
...other descriptive fields

I'm iterating through each data table, one at a time. After I've processed
the first table, I have all my "Foos", then the second one is the "Bars",
which I can associate to the "Foo" without any trouble. (a "Bar" can be
assigned to more than one Foo).
The object I'm hydrating is a List (for purposes of returning it via a web
service) and the objects look like this (pseudocode):
class Foo
{
int FooId
string Name
string etc
string YouGetTheIdea
List<Bar> Bars
}
class Bar
{
int BarId
string etc
List<Baz> Bazes
}
class Baz
{
int BazId
string etc
}
Up to this point, I'm fine. Where I get into trouble is that the "Bar"
objects have a list of "Baz" objects which can be attached to more than
one "Bar" (which in turn can be attached to more than one "Foo")
My code, thus far, looks something like this. If there's a better way to
approach this, please let me know. My trouble is that when I get to the
section dealing with "Baz," I'm not sure how to select all "Bar" objects
(under any Foo who has a Bar with that Id) so I can add the current BazId
to its list of Baz objects. What I have in here currently is blowing up at
runtime, so it's obviously not right.
using (SafeDataReader reader = this.ExecSPReader(SP_NAME, parms.ToArray()))
{
if (reader != null)
{
// deal with Foos
while (reader.Read())
{
Foo o = new Foo();
o.FooID = reader.GetInt64("FooID");
o.Etc = reader.GetString("etc");
//...more properties
fooList.Add(o);
}
// deal with Bars
reader.NextResult();
while (reader.Read())
{
Bar p = new Bar();
long BarFooID = reader.GetInt64("FooID");
p.BarID = reader.GetInt64("BarID");
//...more properties
// find Foo that has this Bar and add to it
Foo o = fooList.Find(x => x.FooID == barFooID);
if (o != null)
{
if (o.Bars == null)
{
o.Bars = new List<Bar>();
}
o.Bars.Add(p);
}
}
/*
***
*** Up to here, everything is fine
*** ...but now we need to assign the baz elements to bars, which can belong
*** to any/all Foos
***
*/
// deal with Bazs
reader.NextResult();
while (reader.Read())
{
long bazID = reader.GetInt64("BazID");
long barID = reader.GetInt64("BarID");
// here is the problem, ideally I'd like to get a list of all
Bar elements with
// the BarID from the datarow, but not sure how to do that --
the below foreach
// line errors at runtime
foreach(Bar p in fooList.Select(a => a.Bars.Where(b => b.BarID
== barID)))
{
if (p.Bazes == null)
{
p.Bazes = new List<Baz>();
}
p.Bazes.Add(bazID);
}
}
}
}
Greatly appreciate any help.

Finishing the Navigation Drawer Activity

Finishing the Navigation Drawer Activity

I have a NavigationDrawerActivity which has a button in the navigation
drawer that navigates to the previous activity. I achieve this through
calling finish(), which works well. Inside my NavigationDrawerActivity, I
have a ViewPager. My issue is that when I call finish from the activity,
the ViewPager will go back to the first page before going back to the
previous activity. I'm assuming this happens because the ViewPager kills
off the pages one by one, so my question is, how can I make this
transition invisible to the user? I want the user to be able to go
directly from the 2nd page or 3rd page to the previous activity. All the 3
pages in the ViewPager must remain active and I have tried making a new
intent for the previous activity and starting it (which did not work).
Thanks

Database_Exception [ 1146 ]: Table 'kohana.userdetailses' doesn't exist

Database_Exception [ 1146 ]: Table 'kohana.userdetailses' doesn't exist

This is my Controller
userdetails.php
<?php defined('SYSPATH') or die('No direct script access.');
class Controller_Userdetails extends Controller {
public function action_index() {
$view = new View('userdetails/index');
$this->response->body($view);
}
public function action_add() {
$userdetails = new Model_Userdetails();
$view = new View('userdetails/adddetails');
$view->set("userdetails", $userdetails);
$this->response->body($view);
}
model is
userdetails.php
<?php defined('SYSPATH') or die('No direct script access.');
class Model_Userdetails extends ORM {
}
userinfo.sql
CREATE TABLE `kohana`.`userinfo` (
`id` int unsigned NOT NULL AUTO_INCREMENT,
`first_name` varchar(100) DEFAULT NULL,
`last_name` varchar(100) DEFAULT NULL,
`email` varchar(100) DEFAULT NULL,
`description` text,
PRIMARY KEY (`id`)
);
I am newly learning php and kohana.I am using kohana 3.2 version.I am
following this tutorial to create,edit,update and delete data in
database.I tried with above code,i am getting this error
"Database_Exception [ 1146 ]: Table 'kohana.userdetailses' doesn't exist [
SHOW FULL COLUMNS FROM `userdetailses` ]"
need some help to solve this.

Tuesday, 20 August 2013

How to install Hershey's Old English font in MacTeX 2013?

How to install Hershey's Old English font in MacTeX 2013?

I have hard times installing Hershey's Old English font. LaTeX code would
be much appreciated!

What Hard drive would be a good upgrade choice for my Toshiba Satellite laptop c875, i3, 4Gb? [on hold]

What Hard drive would be a good upgrade choice for my Toshiba Satellite
laptop c875, i3, 4Gb? [on hold]

What Hard drive would be a good upgrade choice for my Toshiba Satellite
laptop c875, i3, 4Gb? Should I increase the ram, if so what's the most ram
that this laptop will be able to upgrade to?

python NameError: global name is not defined

python NameError: global name is not defined

I am getting this error NameError: global name 'control_queue' is not
defined I have checked control_queue through out and I think I created it
right.
Here is my code:
import multiprocessing
import time
from threading import Thread
class test_imports:#Test classes remove
alive = {'import_1': True, 'import_2': True};
def halt_listener(self, control_Queue, thread_Name, kill_command):
while True:
print ("Checking queue for kill")
isAlive = control_queue.get()
print ("isAlive", isAlive)
if isAlive == kill_command:
print ("kill listener triggered")
self.alive[thread_Name] = False;
return
def import_1(self, control_Queue, thread_Number):
print ("Import_1 number %d started") % thread_Number
halt = test_imports()
t = Thread(target=halt.halt_listener, args=(control_Queue,
'import_1', 't1kill'))
count = 0
t.run()
global alive
run = test_imports.alive['import_1'];
while run:
print ("Thread type 1 number %d run count %d") %
(thread_Number, count)
count = count + 1
print ("Test Import_1 ", run)
run = self.alive['import_1'];
print ("Killing thread type 1 number %d") % thread_Number
def import_2(self, control_queue, thread_number):
print ("Import_2 number %d started") % thread_number
count = 1
while True:
alive = control_queue.get()
count = count + 1
if alive == 't2kill':
print ("Killing thread type 2 number %d") % thread_number
return
else:
print ("Thread type 2 number %d run count %d") %
(thread_number, count)
class worker_manager:
def __init__(self):
self.children = {}
def generate(self, control_queue, threadName, runNum):
i = test_imports()
if threadName == 'one':
print ("Starting import_1 number %d") % runNum
p = multiprocessing.Process(target=i.import_1,
args=(control_queue, runNum))
self.children[threadName] = p
p.start()
elif threadName == 'two':
print ("Starting import_2 number %d") % runNum
p = multiprocessing.Process(target=i.import_2,
args=(control_queue, runNum))
self.children[threadName] = p
p.start()
elif threadName == 'three':
p = multiprocessing.Process(target=i.import_1,
args=(control_queue, runNum))
print ("Starting import_1 number %d") % runNum
p2 = multiprocessing.Process(target=i.import_2,
args=(control_queue, runNum))
print ("Starting import_2 number %d") % runNum
self.children[threadName] = p
self.children[threadName] = p2
p.start()
p2.start()
else:
print ("Not a valid choice choose one two or three")
def terminate(self, threadName):
self.children[threadName].join
if __name__ == '__main__':
# Establish communication queues
control = multiprocessing.Queue()
manager = worker_manager()
runNum = int(raw_input("Enter a number: "))
threadNum = int(raw_input("Enter number of threads: "))
threadName = raw_input("Enter number: ")
thread_Count = 0
print ("Starting threads")
for i in range(threadNum):
manager.generate(control, threadName, i)
thread_Count = thread_Count + 1
time.sleep(runNum)#let threads do their thing
print ("Terminating threads")
for i in range(thread_Count):
control.put("t1kill")
control.put("t2kill")
manager.terminate(threadName)
I think it is saying I am not creating it properly, but I went over a few
queue tutorials and as far as I can tell it is correct. Can anyone point
out where I am messing up? Thanks guys and gals!

Android security - encrypting data

Android security - encrypting data

I would like to encrypt some of my application data, in case the phone is
lost or stolen. The Android recommendations appear to be to download the
encryption key from the internet rather than including it the code.
If someone was able to get a hold of the .apk and reverse engineer back to
readable code, could they not then work out the mechanism used to get the
encryption key? Even if the code was obfuscated, would there be enough
string values to piece together how it's done?
Thank you and any replies great fully received.

Removing Gems errors

Removing Gems errors

I have 2 versions of rubies using RVM and i am trying to remove all my
gems which in this ruby version 1.8.7-p302, I tried this but got an error
&#10140; ~ gem list --no-version | xargs gem uninstall -aIx
zsh: correct 'gem' to '.gem' [nyae]? n
ERROR: While executing gem ... (Gem::InstallError)
cannot uninstall, check `gem list -d bundler`
My Gemlist:
&#10140; ~ gem list
*** LOCAL GEMS ***
bundler (1.3.5)
bundler-unload (1.0.1)
declarative_authorization (0.5.1)
fattr (2.2.1)
i18n (0.4.2)
mysql (2.9.1, 2.8.1)
rack (1.1.6, 1.0.1)
rails (2.3.18, 2.3.5)
rake (10.1.0, 0.8.7)
rubygems-bundler (1.2.2)
rush (0.6.8)
rvm (1.11.3.8)
session (3.1.0)
sqlite3 (1.3.8)

Linux script that scans a folder for XML files

Linux script that scans a folder for XML files

I need a script that scans a folder on a webserver for XML files, and then
start a cron job for every XML file it finds.
The XML files look something like this:
invoice_ddmmyy_ttmmss.xml
When the script find files, it starts a cron job:
php
"/home/xxxxxxx/public_html/administrator/components/com_csvi/helpers/cron.php"
template_id="73" filname="invoice_ddmmyy_ttmmss.xml"
I'm fairly new to scrpting, but hope anyone could help me.
Thanks :-)

Qt 5.1 application doesnt work on Windows 8 outside QtCreator, Runtime Error

Qt 5.1 application doesnt work on Windows 8 outside QtCreator, Runtime Error

I wrote a very simple application in Qt 5.1/C++. I wrote it on Windows 7
64 bit. I took *.exe file builded by QtCreator, pasted it in a newly
created folder, and added some *.dlls there.
So the content of my folder looks like this:
myapp.exe
icudt51.dll
icuin51.dll
icuuc51.dll
libgcc_s_dw2-1.dll
libstdc++-6.dll
libwinpthread-1.dll
Qt5Core.dll
Qt5Gui.dll
Qt5Widgets.dll
and it all works on my computer. However, I send it to my friend to test
it on his Windws 8 64 bit, and he got such error:

What else should I do to make it possible that my friend on Windows 8 can
run my application?
On my computer dependecy walker says, that I need those dlls:

Monday, 19 August 2013

C# Removing a timer after adding it with Timer.Elapsed

C# Removing a timer after adding it with Timer.Elapsed

I have a little problem here. For now I'm starting one timer at the start
of application using this:
if (Initialized == 0)
{
errorCheckTimer.Elapsed += (sender, e) =>
OnErrorCheckTimerElapsed(sender, e);
Initialized = 1;
}
It makes sure it's started only one time. If I were to execute this line
more than once, the timer would fire multiple times and once.
Now after initializing the timer, I occassionally run it using:
errorCheckTimer.Interval = ErrorTimerInterval;
errorCheckTimer.Enabled = true;
errorCheckTimer.Start();
And after certain actions happen, I stop it with:
tradeErrorTimer.Enabled = false;
tradeErrorTimer.Stop();
But there is some obscure glitch happening. The timer always works when
its firstly initialized, but sometimes will not turn on at all, and the
OnErrorCheckTimerElapsed will not get executed.
Therefore to make it more reilable, can I remove the timer that has been
added into OnErrorCheckTimerElapsed.Elapsed to initialize a new one every
time I need to start it?
If I try to initialize them multiple times, I get the
OnErrorCheckTimerElapsed firing multiple times at once.
Thank you.

rQuantLib returning results that seem inconsistent (European Vanilla Options)

rQuantLib returning results that seem inconsistent (European Vanilla Options)

I am pricing options on two different products, and generating their
respective greeks while using rQuantLib.
I am doing something quite typical in that I am seeing over each day until
maturity, what can I expect my greeks to be (all else equal). I do this by
iterating towards maturity and recalculating the greeks each day.
My function calls for the two separate products are the following:
VXX
EO<-EuropeanOption("put",17.740000000000002,21.0,0,0.03,0.0273972602739726,0.6003106092255815)
EO<-EuropeanOption("put",17.740000000000002,21.0,0,0.03,0.024657534246575342,0.6003106092255815)
EO<-EuropeanOption("put",17.740000000000002,21.0,0,0.03,0.021917808219178082,0.6003106092255815)
EO<-EuropeanOption("put",17.740000000000002,21.0,0,0.03,0.019178082191780823,0.6003106092255815)
EO<-EuropeanOption("put",17.740000000000002,21.0,0,0.03,0.01643835616438356,0.6003106092255815)
EO<-EuropeanOption("put",17.740000000000002,21.0,0,0.03,0.0136986301369863,0.6003106092255815)
EO<-EuropeanOption("put",17.740000000000002,21.0,0,0.03,0.010958904109589041,0.6003106092255815)
EO<-EuropeanOption("put",17.740000000000002,21.0,0,0.03,0.00821917808219178,0.6003106092255815)
EO<-EuropeanOption("put",17.740000000000002,21.0,0,0.03,0.005479452054794521,0.6003106092255815)
EO<-EuropeanOption("put",17.740000000000002,21.0,0,0.03,0.0027397260273972603,0.6003106092255815)
EO<-EuropeanOption("put",17.740000000000002,21.0,0,0.03,0.0,0.6003106092255815)
and
GLD
EO<-EuropeanOption("put",123.82499999999999,120.5,0,0.03,0.021917808219178082,0.2849419297762168)
EO<-EuropeanOption("put",123.82499999999999,120.5,0,0.03,0.019178082191780823,0.2849419297762168)
EO<-EuropeanOption("put",123.82499999999999,120.5,0,0.03,0.01643835616438356,0.2849419297762168)
EO<-EuropeanOption("put",123.82499999999999,120.5,0,0.03,0.0136986301369863,0.2849419297762168)
EO<-EuropeanOption("put",123.82499999999999,120.5,0,0.03,0.010958904109589041,0.2849419297762168)
EO<-EuropeanOption("put",123.82499999999999,120.5,0,0.03,0.00821917808219178,0.2849419297762168)
EO<-EuropeanOption("put",123.82499999999999,120.5,0,0.03,0.005479452054794521,0.2849419297762168)
EO<-EuropeanOption("put",123.82499999999999,120.5,0,0.03,0.0027397260273972603,0.2849419297762168)
EO<-EuropeanOption("put",123.82499999999999,120.5,0,0.03,0.0,0.2849419297762168)
Now strangely the shape of my results look VERY different:
(i cannot figure out how to format this table please help)
¨X¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨j¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨j¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨[
¨U Dt ¨U GLD ¨U VXX ¨U
¨d¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨p¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨p¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨g
¨U 20130710 ¨U ¨U -2.78537254 ¨U ¨U 20130711 ¨U ¨U -2.442634118 ¨U ¨U
20130712 ¨U -36.57505341 ¨U -2.043777456 ¨U ¨U 20130713 ¨U -38.06138187 ¨U
-1.586430561 ¨U ¨U 20130714 ¨U -39.63435112 ¨U -1.075717396 ¨U ¨U 20130715
¨U -41.21455042 ¨U -0.532731589 ¨U ¨U 20130716 ¨U -42.56862995 ¨U
-0.00831835 ¨U ¨U 20130717 ¨U -43.00069417 ¨U 0.404615221 ¨U ¨U 20130718
¨U -40.19249227 ¨U 0.604105594 ¨U ¨U 20130719 ¨U -25.10362413 ¨U
0.629917659 ¨U
¨^¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨m¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨m¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨a
And the results look like this:
GLD more or less makes sense compared to similar bloomberg result shapes,
while VXX makes zero sense to me. Additionally the differences in the
values are concerning.