Thursday, April 12, 2012

callback url creating new activity instead of resuming in android

I am facing problem in twitter integration with android.
Everything is working fine it goes to browser asks for credentials, and comes back to app again thru callbackURL.



And here problem arises instead of resuming the activity from where i called, it is creating
a new one which costs me loosing all the variables data that i want after authentication.



My layout is like this:- on checking facebook check-box or twitter check-box it calls the respective authentication window and then (resumes the activity) itz working fine with facebook but not with twitter which results in creation a new activity



after authentication the user can post the data he had in edit text to selected server



 @Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);

facebook.authorizeCallback(requestCode, resultCode, data);
}


//////////////////////////////Twitter/////////////////////////////

public void LoginTwitter(){
if (TwitterUtils.isAuthenticated(prefs)) {
//sendTweet();
} else {
Intent i = new Intent(getApplicationContext(), PrepareRequestTokenActivity.class);
//i.putExtra("tweet_msg",getTweetMsg());
startActivityForResult(i, 1);
}
}


Problem :- how to make the activity resume on callback so that edit-text retains itz data



Thanks in advance





Accessing individual triangles of a model

I'm attempting to do something like this:



http://www.youtube.com/watch?v=iQlbL72W9MU



The comment under the video pointed me in the right direction, but I'm not sure how to access individual triangles in the model like the creator suggested. What method would I use to access and rotate individual triangles?





How do I change seed/database settings in PlayMorphia between dev and prod?

I have a Play Framework (1.2.4) project with PlayMorphia that has two different database connection profiles. One is for development and the other is for production, but I am only seeing one static looking config file hosting the values.



I am reading on how this all works, but struggling on how to support two configuration settings. Is there some configuration trick in Play that people use?





Making a scheduled method Thread safe

I have a method that is invoked by a scheduler every minute to get a file from ftp, process and persists its records to a DB. I need to make this thread safe so that if the method has to perform multiple files at once, it acts a in a thread safe way..



public synchronized void processData(String data){
//do processing
}


is this really going to be a thread safe method that will handle high volumes of load gracefully?





Float vs Double

Would I ever get an incorrect result if I promote 2 floats to double and do a 64bit comparison rather than a 32bit comparison?



Thanks.





Copying entire directory to other location using batch file



I want to automate my build process,so I want to write a bat file that does all the copy pasting of libraries for me and do a ANT build of my java project.
Now the problem I am facing is,I have too many nested directories to copy and I tried using copy and Xcopy commands,but these copies only the files and not the Directories/Folders inside other folders.



I read about variations in xcopy but did not get anything similar.



How can I copy entire folder as it is from one location to other using BAT commands??(Similar to what we do using right click or ctrl+c) :P



Thanks

Sachin

S/W Engg

www.optionsconsultancy.com





How to zoom two Images placed side by side, together?

I have two scrollviews placed side by side and they can be zoomed individually. So far, it works fine. Now, there's a requirement to zoom the two images together. I was given the roambi app as reference in which two scrollviews can be scrolled together by scrolling either one of them for convenience during comparison. I've gone through scrollview delegate methods but was unable to achieve the required results. How do I do this?



Answer:





I had implemented something similar a while ago (I did it for buttons). This is how I did it:
Take two UIScrollViews and reference them (I've used firstScrollView and secondScrollView)
Take two UIButtons and reference them (I've used firstImgBtn and secondImgBtn). Set the delegates to both the scrollviews and use the following delegate methods:
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView{
    //return the respective button in the scrollview to be zoomed
    if(scrollView==firstScrollView){
        return firstImgBtn;
    }
    else{
        return secondImgBtn;
    }
}
- (void)scrollViewDidZoom:(UIScrollView *)scrollView{
    // zoom in the other scrollview when one has zoomed
    if(zoomTogether){//a bool to decide whether to zoom the two together or not
        if(scrollView==firstScrollView){
            secondScrollView.zoomScale = firstScrollView.zoomScale;
        }
        else{
            firstScrollView.zoomScale = secondScrollView.zoomScale;
        }
    }
}
This can be applied to any subclass of UIView-in your case it will be UIImageViews

Changing prices in OpenCart according to script

I'm setting up a retail business to sell gold over the internet, using opencart. The difference is that I will only accept bitcoins (BTC), a new cryptographic currency.



The problem is that precious metal prices and the BTC/GBP exchange are very volatile. Thus I need my opencart prices to automatically update at a fairly frequent rate to avoid being caught out via moving exchange rates and selling at a loss.



I've written a script that is attached that pulls the gold, silver, and platinum price, then denominates the prices in bitcoins.



So, for each metallic item on the website, I'd like the prices of all products within the catalogue to change automatically (every 15 minutes would be ideal).



My question is: How do I update prices in the opencart database, according to a script?



The price has to change based on four things:
the type of precious metal the item contains.
the percentage markup for that item
the weight of precious metal the item contains.
the type of coin the item is.



I'd like these things to be attributes editable within opencart. For every item, there would be four (extra) attributes



Metal type
=> Gold
=> Silver
=> Platinum
=> Not a metal (for other items, it would then ignore all weight, price changes)
Percentage Markup
Percentage (integer?)
Weight
Integer
Coin Markup
Integer
"
So, let's say I'm selling a quarter ounce gold coin, of the Krugerrand type:



a quarter ounce gold coin weighs 7.77 grams, so on the product page the weight would be listed with that figure. The base price would be set at 7.77 grams * Gold price in grams (this figure is fetched using the attached php script).



My default markup from the wholesale gold price would be 10%, the 'base' price would be increased by 10%, this would also be listed on the product page.



Krugerrands, for historical reasons tend to include a value over and above the gold wholesale price. so the coin mark up would be around 5 bitcoins, the price would be increased to reflect this.
"
None of these price fiddles should be seen by the buyer, they should just see the price changes to reflect all of these



Every hour the price of all the products would change, to reflect the changes in the gold price, and the BTC GBP exchange rates.



Below is a PHP script to pull a gold price, a silver price, and a platinum price, then denominate the price of a gram of metal in bitcoins. It's the first thing I've ever programmed, so might be a little verbose, or not follow given conventions. The answer is likely to be very complicated, so I don't expect a full one. It'd be nice to receive some pointers though!



 <?php
/* This is a script that ultimately displays the price of gold in grams, denominated in Bitcoins (BTC), a non fiat cryptographic currency. This is also the first thing I have ever programmed, so be nice */

// line break variable
$br = "<br> <br>";


// CURL begin
//curl session 1: grab metal prices
$ch1 = curl_init();
curl_setopt( $ch1, CURLOPT_URL, 'http://drayah.no.de/metals/latest' );
curl_setopt( $ch1, CURLOPT_RETURNTRANSFER, 1 );
$metalsdata = curl_exec( $ch1 );


// curl session 2: Grab exchange rate for BTC/GBP
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, 'https://mtgox.com/api/1/BTCGBP/public/ticker' );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt( $ch, CURLOPT_FRESH_CONNECT, 1);
curl_setopt( $ch, CURLOPT_TIMEOUT_MS, 1000);
curl_setopt( $ch, CURLOPT_USERAGENT, 'useragent');
$btcgbpdata = curl_exec( $ch );
curl_close( $ch );

// curl session 3: Grab British pounds to USD exchange rates
$ch1 = curl_init();
curl_setopt( $ch1, CURLOPT_URL, 'https://raw.github.com/currencybot/open-exchange-rates/master/latest.json' );
curl_setopt( $ch1, CURLOPT_Rcheck if my code isETURNTRANSFER, 1 );
$currencydata = curl_exec( $ch1 );


//gold digest: turn JSON data into readable php, and extract the gold price
$metals = json_decode( $metalsdata, true, 512 );
$goldprice = $metals['gold']['quote'];
$silverprice = $metals['silver']['quote'];
$platprice = $metals['platinum']['quote'];

//BTC digest of JSON

$btcgbp = json_decode( $btcgbpdata, true, 512 );
$btcgbpvwap = ($btcgbp['return']['vwap']['value']);
echo "$btcgbpvwap pounds per BTC";
echo $br;


//currency digest of JSON
$currency = json_decode( $currencydata, true, 512 );
$usdgbp = ($currency['rates']['GBP']);
echo "$usdgbp pence per USD dollar";
echo $br;
echo $br;
// convert metals into price per ounce in pounds

$goldpounds = $goldprice * $usdgbp;
$silverpounds = $silverprice * $usdgbp;
$platpounds = $platprice * $usdgbp;
echo "GBP $goldpounds per ounce of gold";
echo $br;
echo "GBP $silverpounds per ounce of silver";
echo $br;
echo "GBP $platpounds per ounce of platinum";
echo $br;
echo $br;

//metals prices in grams
$goldpoundsgram = $goldpounds / 31.1034768;
$silverpoundsgram = $silverpounds / 31.1034768;
$platpoundsgram = $platpounds / 31.1034768;
echo "$goldpoundsgram pounds per gram of gold";
echo $br;
echo "$silverpoundsgram pounds per gram of silver";
echo $br;
echo "$platpoundsgram pounds per gram of platinum";
echo $br;
echo $br;
// metal prices denominated in BTC
$btcgoldgram = ($goldpoundsgram / $btcgbpvwap);
$btcsilvergram = ($silverpoundsgram / $btcgbpvwap);
$btcplatgram = ($platpoundsgram / $btcgbpvwap);
echo "<b>";
echo $btcgoldgram;
echo " bitcoins per gram of gold";
echo $br;
echo $btcsilvergram;
echo " bitcoins per gram of silver";
echo $br;
echo $btcplatgram;
echo " bitcoins per gram of platinum";

?>




Objective-C, C, or C++ Calculus Frameworks/Libraries?

I am an Electrical Engineering Student and have found a few ideas for some apps to make in my spare time, and they would need to be able to use integration and differentiation in order to do the calculations. Numerical estimation using Riemann sums would work too; my question is, are there any C, Objective-C, or C++ frameworks or libraries that I could make use of in order to make my life a little easier? If I have to, I could write my own frameworks (esp. for Riemann) but it would definitely be time consuming and I would prefer to avoid it! I have taken a look around the web and haven't dug too much up thus far, and figured other people have got to be looking for the same information too! Thanks for the help!





Cannot download a file using HttpServletResponse

I want to download a MS Word 2003 document that I am creating with the content myString in it.
I have used the following code:


BufferedReader reader = new BufferedReader(new FileReader(templatePathFilename));
 HttpServletResponse response = new MyHttpServletResponse();
 response.setContentType ("application/msword"); 
 response.setHeader ("Content-Disposition", "attachment; filename=\""+outgoingFileName); 
 ServletOutputStream myOut = response.getOutputStream();
 myOut.write(myString.getBytes());
 myOut.flush();
 myOut.close();
 


But the line myOut.write(myString.getBytes()) gives a NullPointerException.
MyHttpServletResponse is a class that eclipse has produced by default when I quick fix the error generated. Do I need to modify that class?
Can anyone please help!




If you are using a Java EE platform to perform the download operation to occur then the safest way is to do it through a servlet. A Sample Download servlet should Look like below,
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*; import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class DownloadFile extends HttpServlet{
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{ PrintWriter out = response.getWriter();
String fileName = request.getParameter("fileName");
fileName=fileName.substring(fileName.lastIndexOf("\\")+1,fileName.length());
String extension=fileName.substring(fileName.lastIndexOf(".")+1,fileName.length());
String filePath = "C:/temp/"+fileName;
FileInputStream fileToDownload = new FileInputStream(filePath);
//ServletOutputStream output = response.getOutputStream();
if(extension.equalsIgnoreCase("txt")){
    response.setContentType("text/html");
}
else if(extension.equalsIgnoreCase("doc")){
    response.setContentType("application/msword");
}
else if(extension.equalsIgnoreCase("pdf")){
    response.setContentType("application/pdf"); }
else if(extension.equalsIgnoreCase("jpg")){
    response.setContentType("image/jpeg"); }
else if(extension.equalsIgnoreCase("jpeg")){
    response.setContentType("image/jpeg");
}
response.setHeader("Content-Disposition","attachment; filename="+fileName);
response.setContentLength(fileToDownload.available());
int c;
while((c=fileToDownload.read()) != -1){
out.write(c);
}
out.flush();
out.close();
fileToDownload.close();
}
}

How to compare two Dates without the time portion?

I would like to have a compareTo method that ignores the time portion of a java.util.Date. I guess there are a number of ways to solve this. What's the simplest way?





Using ObjectContext / DbContext inside T4 Text Template

I've been searching for an example on how to use Entity Framework (ObjectContext/DbContext) inside of T4 template. How can I achieve this? Currently in my T4 I need to get values from database tables to generate files.





Slide expand animation

I have a simple list view listing results title in android. Upon click of each item, I would like it to slide down expand and show the content. Is there an easy way to do this in android?



Any help will be appreciated.
Thanks in advance.





How to make a design like this?

I am new to android development and i want to design the application like the following please any one help with sample code


enter image description here



Answer:



Basically what you have is a layout of image buttons. When a button is clicked, the handler starts another activity. The only way back to the home activity is via the Home button that appears in all of the secondary activities.
All the layout of views is done in resources files in folder res/layouts. I am assuming you are familiar with basic layouts, defining views within them, and connecting them to an activity so I will not cover those things here.
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_focused="true"
         android:state_pressed="true"
         android:drawable="@drawable/title_about_alt"/>
    <item android:state_focused="false"
         android:state_pressed="true"
         android:drawable="@drawable/title_about_alt"/>
    <item android:state_focused="true"
         android:drawable="@drawable/title_about_alt"/>
    <item android:state_focused="false"
         android:state_pressed="false"
         android:drawable="@drawable/title_about_default"/>
</selector>
For more information...

Python Script vs Cron Job

I need to run a cron job to generate a list of user rankings each week at exactly "00:00:00" UTC each Monday morning. Has anyone got an example for this, it's really doing my head in ... I looked into "crontab -e" and was instantly lost.


Basics:
  - Run the script, eg: /srv/django/get_rankings.py
  - Run the script at "00:00:00" and "00:05:00" every Monday.
  - Run the same script the next Monday ... and repeat
 


I'm on Linux Arch, any heads up would be amazing.


Thanks so much,
Hope all is well



Answer:


crontab put entry like,

00,05 0 * * 1 /srv/django/get_rankings.py

runs the script at 00.00 & 00.05 every Monday of every month

*     *     *   *    *        command to be executed-     -     -   -    -
|     |     |   |    |
|     |     |   |    +----- day of week (0 - 6) (Sunday=0)
|     |     |   +------- month (1 - 12)
|     |     +--------- day of        month (1 - 31)
|     +----------- hour (0 - 23)
+------------- min (0 - 59)
* in the value field above means all legal values as in braces for that column. The value column can have a * or a list of elements separated by commas.
An element is either a number in the ranges shown above or two numbers in the range separated by a hyphen (meaning an inclusive range)

What is a suitable replacement for android ActionBar?

I've developed an application that utilizes an actionBar, but apparently actionBar is only available for SDK 3.0 or later. I would like my application to be able to run on earlier SDKs, what would be a suitable replacement for an actionBar?



  • Pop up menu

  • Context Menu etc..



Please suggest anything that you think would be a suitable replacement or similar to an actionbar.


Thanks



Answer:


no, you can also use Actionbar Sherlock which supports below Verion 3.0 and it good too. It is a library project and you just need to add reference to your project.

http://actionbarsherlock.com/
https://github.com/JakeWharton/ActionBarSherlock

enter image description here

Graphviz + Doxygen to generate UML class diagrams

I want to use Graphviz + Doxygen to generate a class diagram based on C++ code. This works already as Doxygen comes with a native DOT support; but is it possible, to produce a UML-like output with the corresponding access modificators (public, private etc.), return and parameter types of the class methods, similar to the diagram below?


I'm aware of thread How to use doxygen to create UML class diagrams from C++ source, but it doesn't answer the question, though.


enter image description here



Answer:





Create the following source file example.cpp:
class Animal
{
  public:
    void die();
    string name;
    int age;
};

class Dog : public Animal
{
  public:
    void bark();
};

class Cat : public Animal
{
  public:
    void meow();
};
run doxygen -g and change the following options of the generated Doxyfile:
EXTRACT_ALL            = YES
HAVE_DOT               = YES
UML_LOOK               = YES
run doxygen and look at the output for the Animal class, it should be the similar as the above picture, although doxygen will not show the return types of the methods and fields.

How to increse or decrese volume in blackberry programatically

In MY application i play a video on device and when i tab on screen while video is playing. a popup window is open on center of the screen there is a volume button on that popup screen. when i click on that button volume should be increase and after maximum level of volume it should be decrease.and i don't know how to do it programmatically in blackberry.





what are the possible OCR classification algorithm for business cards?

i want to classify data extracted from a business card using tesseract OCR engine, what are the possible classification algorithms and the main steps for doing that?





regular expression for matching a word

I want to get the variable names in javascript which define a string
for that I have wrote a regular expression


var x = "sdfsfsdf";
 
 ((\w.*?)(\s*=\s*)(['"]*)(.+?)(['"]*)\1)
 


The problem with this expression is when I am using RegExp.$2 I should get the variable name as x as we consider the above code. It works fine with some expression but if there is code like


function(a) {var b = document.createElement("script");}
 


then the result is function(a){var b.


Please help me change my regular expression so it works in both cases.


NOTE: javascript variables can also be declared without var i.e. x = "sdfsfsf";



Answer:





If your strings won't be too crazy, you can try this:

/[a-z_$][a-z0-9$_]*\s*=\s*.*?(;|$)/gi

Tests:

> var r = /[a-z_$][a-z0-9$_]*\s*=\s*.*?(;|$)/gi;
  undefined
> 'var x = "sdfsfsdf";'.match(r);
  ["x = "sdfsfsdf";"]
> 'function(a) {var b = document.createElement("script");}'.match(r);
  ["b = document.createElement("script");"]

Playing video from Sd card

I have build an app that has videos in it that stream from the Internet and I'm not very impressed with the performance of them. Would anyone like to share the code for loading videos from the SD card.



Thanks





one to optional many Relationship

I want to create one to optional many relation between following two table.


'FK_transactionmember' FOREGIN KEY ('MemberID') REFERENCES 'member' ('ID')
 


I create foreign key constrain witch is one-to-many relation(Above). In this case member ID must required for transaction, but member is optional.


How to control this optional situation?


Memebr:


CREATE TABLE `member` (
 `ID` int(11) NOT NULL AUTO_INCREMENT,
 `FirstName` varchar(30) DEFAULT NULL,
 `LastName` varchar(30) DEFAULT NULL,
 `PermanentAddress` varchar(100) DEFAULT NULL,
 `TemporaryAddress` varchar(100) DEFAULT NULL,
 `Zip` varchar(30) DEFAULT NULL,
 `City` varchar(30) DEFAULT NULL,
 `LastVisit` datetime DEFAULT NULL,
 `TotalVisit` datetime DEFAULT NULL,
 `Active` tinyint(1) DEFAULT NULL,
  PRIMARY KEY (`ID`)
  ) ENGINE=InnoDB DEFAULT CHARSET=latin1
 


Transaction


CREATE TABLE `transaction` (
 `ID` int(11) NOT NULL AUTO_INCREMENT,
 `MemberID` int(11) DEFAULT '0',
 `UserID` int(11) DEFAULT NULL,
 `Total` float DEFAULT NULL,
 PRIMARY KEY (`ID`)
 ) ENGINE=InnoDB DEFAULT CHARSET=latin1
 



Answer 1 :


There are (at last) two ways create table like below:
CREATE TABLE `transaction` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`MemberID` int(11) NULL,
`UserID` int(11) DEFAULT NULL,
`Total` float DEFAULT NULL,
PRIMARY KEY (`ID`),
CONSTRAINT 'FK_transactionmember' 
    FOREGIN KEY ('MemberID') 
    REFERENCES 'member' ('ID')
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
and set MemberID to null whenever you can't connect it with member. It's fine in my opinion but it doesn't meet BNF requirements or use different table to link both tables like below:
CREATE TABLE `MemberTransactions` (
`MemberID` int(11) NULL,
`TransactionID` int(11) DEFAULT NULL,
CONSTRAINT 'FK_member' 
    FOREGIN KEY ('MemberID') 
    REFERENCES 'member' ('ID')
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
CONSTRAINT 'FK_transaction' 
    FOREGIN KEY ('TransactionID') 
    REFERENCES 'transaction' ('ID')
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
and then transaction table without MemberID column.



*************


Answer 2 :



If the MemberID is optional then its default value must be null, not zero. Therefore if no data exists the null value will be allowed.

CREATE TABLE `transaction` (
    `ID` int(11) NOT NULL AUTO_INCREMENT,
    `MemberID` int(11) DEFAULT NULL,
    `UserID` int(11) DEFAULT NULL,
    `Total` float DEFAULT NULL,
    PRIMARY KEY (`ID`),
    KEY `FK_transactionmember` (`MemberID`),
    CONSTRAINT `FK_transactionmember` FOREGIN KEY (`MemberID`) REFERENCES `member` (`ID`) ON DELETE CASCADE ON UPDATE CASCADE,
) ENGINE=InnoDB DEFAULT CHARSET=latin1

jquery mobile, pgaechange and pageload not work

I am trying to use ajax to load sometag , but my appended code is not being enhanced by JQM.
I tried $(this).trigger('create') and $(this).trigger('updatelayout') but It still not working.



Then I tried to call ajax by function jquery mobile support: $.mobile.changePage()



my code:



$.mobile.changePage({url:'/', data:'add_new_tag=true', type:'GET'}, 'slide', false, true)


in action index: I render 'index.html'
I have checked it in firebug and see response is right (expected) . But I see nothing change in my browser.



Did I miss something ? I hope to recieve your help . Thank you :D





Certain anomalies in binary search runtime

I have a modified version of binary search that takes in an array in sorted order and a value, and returns the smallest possible index of an element that is equal to or larger than the given value (or -1 if the value is larger than the max)



Upon the running the above algorithm, everything works fine and the method works as expected. However, I ran it over different input sizes to measure the runtime.



   for(int i=1;i<=20;i++){  
int size=10*(i*i*i*i);
int[] array=createRandomSortedArray(size);
long startTime=System.nanoTime();
int index=findSmallestIndex(array, needle);
long et=System.nanoTime()-startTime;
System.out.println("To find "+needle+" in "+size+" inputs "+" execution time is "+et+" nanoseconds");
}


And following were the observtions:-



To find 50 in 10 inputs  execution time is 5775 nanoseconds
To find 50 in 160 inputs execution time is 1925 nanoseconds
To find 50 in 810 inputs execution time is 4330 nanoseconds
To find 50 in 2560 inputs execution time is 5293 nanoseconds
To find 50 in 6250 inputs execution time is 3849 nanoseconds
To find 50 in 12960 inputs execution time is 3368 nanoseconds
To find 50 in 24010 inputs execution time is 3849 nanoseconds
To find 50 in 40960 inputs execution time is 11548 nanoseconds
To find 50 in 65610 inputs execution time is 9143 nanoseconds
To find 50 in 100000 inputs execution time is 4812 nanoseconds
To find 50 in 146410 inputs execution time is 4812 nanoseconds
To find 50 in 207360 inputs execution time is 11549 nanoseconds
To find 50 in 285610 inputs execution time is 8661 nanoseconds
To find 50 in 384160 inputs execution time is 8661 nanoseconds
To find 50 in 506250 inputs execution time is 11549 nanoseconds
To find 50 in 655360 inputs execution time is 11067 nanoseconds
To find 50 in 835210 inputs execution time is 11549 nanoseconds
To find 50 in 1049760 inputs execution time is 11549 nanoseconds
To find 50 in 1303210 inputs execution time is 11067 nanoseconds
To find 50 in 1600000 inputs execution time is 12030 nanoseconds


I see that execution time for 10 inputs is significantly higher than its successive 160 input size.
To verify things, I ran the execution for 10 inputs by itself outside the loop and following was the result



To find 50 in 10 inputs  execution time is 962 nanoseconds


Why is that so? Why does this anomaly exist? There are couple of other steps too where run time is slower than its preceding lower input size.





python numpy sort eigenvalues

I am using linalg.eig(A) to get the eigenvalues and eigenvectors of a matrix. Is there an easy way to sort these eigenvalues (and associated vectors) in order?



Answer:



You want to use the NumPy sort() and argsort() functions. argsort() returns the permutation of indices needed to sort an array, so if you want to sort by eigenvalue magnitude (the standard sort for NumPy arrays seems to be smallest-to-largest), you can do:
import numpy as np

A = np.asarray([[1,2,3],[4,5,6],[7,8,9]])
eig_vals, eig_vecs = np.linalg.eig(A)

eig_vals_sorted = np.sort(eig_vals)
eig_vecs_sorted = eig_vecs[eig_vals.argsort()]

# Alternatively, to avoid making new arrays
# do this:

sort_perm = eig_vals.argsort()

eig_vals.sort()     # <-- This sorts the list in place.
eig_vecs = eig_vecs[sort_perm]

ubuntu: can't unmount disk drive using disk mounter

I use disk mounter to manage my devices, whether to mount them or unmount them. It has worked fine up until I experimented with NFTS configuration tool. I played around with it, did some clicks, then it (NTFS configuration tool) says doing autoconfiguration. After that, it seems that Disk Mounter has lost the rights to mount and unmount my hard disk. Even if I go to Places > (Disk drive name), I get the error 'Unable to mount {disk name here} Error mounting:mount exited with exit code 1:helper failed with:mount:only root can mount /dev/sdb1 on /media/{disk name here}".



Is there a way to revert it back to how it was?





jquery ajax cakephp: change event for input text box displays all fields except city dropdown box

When a user enters an email, the onchange event for the input text box fires and displays all the other fields except the city dropdown box. I noticed that $("#MerryParentCityId").val(result_array[5]); is having the value 81 but the respective city name that user is not getting displayed in MerryParentCityId dropdown box. The value for the state dropdown box is displaying fine. Can someone tell me on where i'm going wrong?



I have a feeling the problem is in the html form's MerryParentCityId dropdown box. But I have no idea on what changes to make there.



thank you.



add.ctp (partial form where city and state dropdown box is located)



echo $this->Form->input('MerryParent.email');
echo $this->Form->input('MerryParent.name', array('label'=>'Parent/Guardian Name'));
echo $this->Form->input('MerryParent.landline');
echo $this->Form->input('MerryParent.mobile');
echo $this->Form->input('MerryParent.address');
echo $this->Form->input('MerryParent.state_id', array('empty'=>'Choose one','options'=>$states));
echo $this->Form->input('MerryParent.city_id');
//echo $this->Form->input('MerryParent.city_id', array('empty'=>'Choose one','options'=>$cities));
echo $this->Form->input('MerryParent.postal_code');


jquery code



<script type="text/javascript">
$(document).ready(function(){


$("#MerryParentEmail").change(function(){
//txt=$("#MerryParentEmail").val();
email_id=$("#MerryParentEmail").serialize();
//alert(txt);
$.post("../students/get_parent_info",email_id,function(result_str){
result_array=result_str.split('<br>');
$("#MerryParentName").val(result_array[0]);
$("#MerryParentLandline").val(result_array[1]);
$("#MerryParentMobile").val(result_array[2]);
$("#MerryParentAddress").val(result_array[3]);
$("#MerryParentStateId").val(result_array[4]);
$("#MerryParentCityId").val(result_array[5]);
$("#MerryParentPostalCode").val(result_array[6]);
});
});

$("#MerryParentStateId").change(function(){
state=$(this).val();
txt_str="state_id="+state;
$.get("../students/getcities",txt_str,function(result){
$("#MerryParentCityId").html(result).show();
});
});



});

</script>


students_controller.php



function get_parent_info(){
//$this->layout=false;
if (!empty($this->data)){

$merryparent_info=$this->Student->MerryParent->getMerryParents($this->data['MerryParent']['email']);

echo $merryparent_info['MerryParent']['name'].'<br>';
echo $merryparent_info['MerryParent']['landline'].'<br>';
echo $merryparent_info['MerryParent']['mobile'].'<br>';
echo $merryparent_info['MerryParent']['address'].'<br>';
echo $merryparent_info['MerryParent']['state_id'].'<br>';
echo $merryparent_info['MerryParent']['city_id'].'<br>';
echo $merryparent_info['MerryParent']['postal_code'].'<br>';
}
}

function getcities(){
$this->data['MerryParent']['state_id']=$_GET['state_id'];
if (!empty($this->data['MerryParent']['state_id'])){
$cities = $this->Student->MerryParent->City->getCities($this->data['MerryParent']['state_id']);
//print_r($cities);
foreach ($cities as $k=>$v){
echo '<option value="'.$k.'">'.$v.'</option>';
}

/* foreach($cities as $optionValue){
echo '<option>' . $optionValue . '</option>';
}*/
}else{
$this->Session->setFlash('You didn\'t select a state!');
}

}

function add(){
//saves a new students information to db
$states=$this->Student->MerryParent->State->getStates();
$this->set('states',$states);

//$cities=array();
}




Generate custom steps with behat

I try to write a custom step that's generate step



my code looks like :



/**
* @Then /^Check_raoul$/
*/
public function checkRaoul()
{
// grab the content ...

// get players ...
$to_return = array();
foreach ($players as $player) {
$player = $player->textContent;
if (preg_match('/^.*video=([^&]*)&amp;.*$/', $player, $matches))
{
array_push($to_return, new Step\Then('I check the video of id "'.$matches[1].'"'));
}
}
return $to_return;
}

/**
* @Then /^I check the video of id "([^"]*)"$/
*/
public function iCheckTheVideoOfId($id)
{
// ...
}


works fine but when integrating to jenkins or un cli, if many executions of iCheckTheVideoOfId fail, I see just one error. I wish generate a number of steps equal to the number of iCheckTheVideoOfId calls



what I a doing wrong ?





Why can't I delete the file from a php script?

Basically, I am proxying a file using a php script and then deleting it straight after... only, the file isn't deleting and I can't work out why.


this is a little out of context, so, happy to explain more should you need it.


exec("wget http://xxxx/123_" .$matches[1] . " --no-check-certificate -P /usr/share/nginx/www/" );
 
 $file = "/usr/share/nginx/www/123_" . $matches[1];
 
 if (file_exists($file)) {
     header('Content-Type: text/plain');
     header('Content-Length: ' . filesize($file));
     ob_clean();
     flush();
     readfile($file);
     exec("rm /usr/share/nginx/www/123_" . $matches[1] );
 
     exit;
 }
 



Answer:


Try this code, which will not create a local file that needs to be deleted:
// Define URL 
$url = "http://xxxx/123_{$matches[1]}"; 
 // Open pointer to remote resource if (!$remoteFP = @fopen($url, 'r')) { 
  header("{$_SERVER['SERVER_PROTOCOL']} 500 Internal Server Error"); 
  exit; } 
 // Get content length and type from remote server's headers 
$length = $type = NULL; foreach ($http_response_header as $header) { // Loop headers (see http://php.net/manual/en/reserved.variables.httpresponseheader.php) 
  list($name, $val) = explode(':', $header, 2); // Split to key/value 
  switch (strtolower(trim($name))) { // See if it's a value we want 
    case 'content-length': 
      $length = (int) trim($val); 
      break; 
    case 'content-type': 
      $type = trim($val); 
      break; 
  } 
  if ($length !== NULL && $type !== NULL) break; // if we have found both we can stop looping } 
 // Send headers if ($type === NULL) $type = 'text/plain'; 
header("Content-Type: $type"); if ($length) header("Content-Length: $length"); // Only send content-length if the server sent one. You may want to do the same for content-type. 
 // Open a file pointer for the output buffer 
$localFP = fopen('php://output', 'w'); 
 // Send the data to the remote party 
stream_copy_to_stream($remoteFP, $localFP); 
 // Close streams and exit 
fclose($remoteFP); 
fclose($localFP); exit; 
This uses the fopen() approach over cURL etc because it allows one to forward the entity straight to the output buffer, as well as giving access to the remote server's response headers before the body have been fully received. It is the most resource-efficient way to proxy using PHP.
If your server has allow_url_fopen disabled, you may be able to use cURL, which will also allow you to pass the data straight to the output buffer, but does not allow you to parse and forward the headers from the remote server.

Select highest Age where Age is closest to a number

Think I have been looking at my code too much.



But my problems is that I have a unordered list and I need to select the object with the highest number closes to or equals an input.



I have created this little sample to illustrate what I trying to do.



public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}

var persons = new List<Person>
{
new Person {Age = 10, Name = "Aaron"},
new Person {Age = 15, Name = "Alice"},
new Person {Age = 20, Name = "John"},
new Person {Age = 22, Name = "Bob"},
new Person {Age = 24, Name = "Malcom"}
};

int i = 17; //should return 'Alice 15'
int y = 22; //should return 'Bob 22