Tuesday 31 May 2016

multithreading - How to start other script inside a running python script(A new thread or process?)

If I have a program like this:



for i in range (25000):
do something
if i == 5000:
run new_script.py in a new thread/process
continue as before


How can I do this?

javascript - (Deep) copying an array using jQuery











I need to copy an (ordered, not associative) array of objects. I'm using jQuery. I initially tried



jquery.extend({}, myArray)



but, naturally, this gives me back an object, where I need an array (really love jquery.extend, by the way).



So, what's the best way to copy an array?


Answer



Since Array.slice() does not do deep copying, it is not suitable for multidimensional arrays:



var a =[[1], [2], [3]];
var b = a.slice();

b.shift().shift();

// a is now [[], [2], [3]]


Note that although I've used shift().shift() above, the point is just that b[0][0] contains a pointer to a[0][0] rather than a value.



Likewise delete(b[0][0]) also causes a[0][0] to be deleted and b[0][0]=99 also changes the value of a[0][0] to 99.



jQuery's extend method does perform a deep copy when a true value is passed as the initial argument:



var a =[[1], [2], [3]];

var b = $.extend(true, [], a);

b.shift().shift();
// a is still [[1], [2], [3]]

c++ - there is a problem in placing the ships and hitting also ,,please any one can solve this

#include
#include
#include
#include using namespace std; char userarr[10][10]; char comparr[10][10]; const int WIDTH = 10, HEIGHT = 10; void checkhit(char comparr[][10]) { // char comparr[WIDTH][HEIGHT]; char ch = 'A'; cout << " "; for (char ch = 'A'; ch < 'K'; ch++) cout << " " << char(ch); cout << endl; for (int i = 0; i < 10; i++) {

cout << i << " "; for (int j = 0; j < 10; j++) { //comparr[i][j] = 'o'; cout << comparr[i][j] << " "; } cout << endl; } }


void sirfcheck() { system("cls"); int temp = 0; char ch = 'A'; cout << " "; for (char ch = 'A'; ch < 'K'; ch++) cout << " " << char(ch); cout << endl; for (int i = 0; i < 10; i++, temp++) {

cout << temp << " "; for (int j = 0; j < 10; j++) { cout << comparr[i][j] << " "; } cout << endl; }

} void check() { cout << "-----------------user--------------------"<> hit1>> hit2; int hit3 = rand() % 10; int hit4 = rand() % 10; if (comparr[hit1][hit2] == 'A' || comparr[hit1][hit2] == 'B' || comparr[hit1][hit2] == 'C' || comparr[hit1][hit2] == 'D' || comparr[hit1][hit2] == 'E') { comparr[hit1][hit2] == 'H'; score += 1; cout << endl; cout << score<
} if (userarr[hit3][hit4] == 'A' || userarr[hit3][hit4] == 'B' || userarr[hit3][hit4] == 'C' || userarr[hit3][hit4] == 'D' || userarr[hit3][hit4] == 'E') { userarr[hit3][hit4] == 'H'; score += 1; cout << endl; cout << score << endl;

} else { userarr[hit3][hit4] == 'M'; score -=0.25; cout << endl; cout << score << endl; } } void show2array(char array1[][WIDTH]) { cout << "----------------------------------------" << endl; int temp = 0; char ch = 'A'; cout << " "; for (char ch = 'A'; ch < 'K'; ch++) cout << " " << char(ch); cout << endl; for (int i = 0; i < 10; i++, temp++) {


cout << temp << " "; for (int j = 0; j < 10; j++) { cout << array1[i][j] << " "; } cout << endl; } }



void computer(char array1[][WIDTH]) { srand(time(0)); //char array1[HEIGHT][WIDTH]; char place1[5] = { 'A','B','C','D','E' }; //string arr[5] = { "Aircraft Carrier (size 5)","Battleship (size 4)","Cruiser (size 3)","Submarine (size 3)","Destroyer (size 2)" }; char ch; int size, starting, x1 = 0; //x1 for counting cout << endl; for (int i = 0; i < WIDTH; i++) {// clear grid for (int j = 0; j < HEIGHT; j++) { array1[i][j] = 'o'; } } //cout << "You have to place 5 ships." << endl; for (int j = 1, air = 0, num = 6; j <= 5; j++, air++) { int l = 5; //cout << "Where u want to place the ship no:" << ++x1 << endl; //cout << "Enter starting and ending points of " << arr[air] << " is:"; label1: starting = rand() % 10; int first = starting; size = rand() % 10; int second = size; //if (j == 1) /*if (array1[first][second] == 'A' && array1[first][second] == 'B' &&array1[first][second] == 'C' &&array1[first][second] == 'D' &&array1[first][second] == 'E') { cout << " invalid input!"; goto label1; }*/ if (starting < size) { for (int i = starting; i < size; i++) { if (array1[starting][i] != 'o') { cout << " invalid input!"; goto label1; } } } else if (starting > size) { for (int i = size; i < starting; i++) { if (array1[size][i] != 'o') { cout << " invalid input!"; goto label1; } } } if (j == 1 && starting>5) { //cout << "Invalid placement."; goto label1; } //else if (j == 2) if (j == 2 && starting > 6) { //cout << "Invalid placement."; goto label1; } //else if (j == 3) if (j == 3 && starting > 7) { //cout << "Invalid placement."; goto label1; } //else if (j == 3) if (j == 4 && starting
> 8) { //cout << "Invalid placement."; goto label1; } //else if (j == 2) if (j == 5 && starting > 9) { //cout << "Invalid placement."; goto label1; } //cout << "Enter either y-axis or x-axis" << endl << "Press x for x-axis" << endl << "Press y for y-axis" << endl; int comp = rand() % 2 + 1;

if (comp == 1) { /*srand(time(0)); int x = rand() % (size - starting); int y = rand() % (size - starting);*/ int x = starting; int y = starting; //for(int num=5,air=0,air++) if (air == 3) num = num + 1; int lx = starting + --num;

for (int j = starting, temp1 = 0; j

/*array[x][y + 1] = 1; array[x][y + 2] = 1; array[x][y + 3] = 1; array[x][y + 4] = 1; array[x][y + 5] = 1; array[x][y + 6] = 1; array[x][y + 7] = 1; array[x][y + 8] = 1; array[x][y + 9] = 1;*/ for (int i = 0; i < 10; i++) for (int j = 0; j < 10; j++) { comparr[i][j]
= array1[i][j]; } show2array(array1); } } /*void show1comp() { char array1[WIDTH][HEIGHT]; char ch = 'A'; cout << " "; for (char ch = 'A'; ch < 'K'; ch++) cout << " " << char(ch); cout << endl; for (int i
= 0; i < 10; i++) {

cout << i << " "; for (int j = 0; j < 10; j++) { array1[i][j] = 'o'; cout << array1[i][j] << " "; } cout << endl; } cout << "-------------------------------------"; computer(array1); }*/ //
=------------------------------------------------------user-------------------------------------*/ void show1(char array[][HEIGHT]) { system("cls"); int temp = 0; char ch = 'A'; cout << " "; for (char ch = 'A'; ch < 'K'; ch++) cout << " " << char(ch); cout << endl; for (int i = 0; i < 10; i++, temp++) {

cout << temp << " "; for (int j = 0; j < 10; j++) { cout << array[i][j] << " "; } cout << endl; }


} void place(char array[][HEIGHT]) { char place1[5] = { 'A','B','C','D','E' }; string arr[5] = { "Aircraft Carrier (size 5)","Battleship (size 4)","Cruiser (size 3)","Submarine (size 3)","Destroyer (size 2)" }; char ch; int size, starting, x1 = 0; //x1 for counting cout << endl; for (int i = 0; i < WIDTH; i++) // clear grid for (int j = 0; j < HEIGHT; j++) array[i][j] = 'o'; cout << "You have to place 5 ships." << endl; for (int j = 1, air = 0, num = 6; j <= 5; j++, air++) { int l = 5; cout << "Where u want to place the ship no:" << ++x1 << endl; label: cout << "Enter starting and ending points of " << arr[air] << " is:"; cin >> starting; cin >> size; //if(j==1) /*if (array[starting][size] == 'A' || array[i][j] == 'B' || array[i][j] == 'C' || array[i][j] == 'D' || array[i][j] == 'E') { cout << "invalid" << endl; goto label; }*/ if (starting < size) { for (int i = starting; i < size; i++) { if (array[starting][i] != 'o') { cout << " invalid input!"; goto label; } } } else if (starting > size) { for (int i = size; i < starting; i++) { if (array[size][i] != 'o') { cout << " invalid input!"; goto label; } } } if (j == 1 && starting>5) { cout << "Invalid placement."; goto label; } //else if(j==2) else if (j == 2 && starting > 6) { cout << "Invalid placement."; goto label; } //else if (j == 3) else if (j == 3 && starting > 7) { cout << "Invalid placement."; goto label; } //else if (j == 3) else if (j == 4 && starting > 8) { cout << "Invalid placement."; goto label; } //else if (j == 2) else if (j == 5 && starting > 9) { cout << "Invalid placement."; goto label; } cout << "Enter either y-axis or x-axis" << endl << "Press x for x-axis" << endl << "Press y for y-axis" << endl; cin >> ch;

if (ch == 'x' || ch == 'X') { /*srand(time(0)); int x = rand() % (size
- starting); int y = rand() % (size - starting);*/ int x = starting; int y = starting; //for(int num=5,air=0;;num--,air++) if (air == 3) num = num + 1; int lx = starting + --num;

for (int j = starting, temp1 = 0; j
} } else if (ch == 'y' || ch == 'Y') { /*srand(time(0)); int x = rand() % (size - starting); int y = rand() % (size - starting);*/ int x = starting; int y = starting; if (air == 3) num = num + 1; int ly = starting + --num; for (int i = starting, temp = 0; i
/*array[x][y + 1] = 1; array[x][y + 2] = 1; array[x][y + 3] = 1; array[x][y + 4] = 1; array[x][y + 5] = 1; array[x][y + 6] = 1; array[x][y + 7] = 1; array[x][y + 8] = 1; array[x][y + 9] = 1;*/ for (int i = 0; i < 10; i++) for (int j = 0; j < 10; j++) { userarr[i][j]

= array[i][j]; } show1(array); } } void show() { char array[WIDTH][HEIGHT]; char ch = 'A'; cout << " "; for (char ch = 'A'; ch < 'K'; ch++) cout << " " << char(ch); cout << endl; for (int i = 0; i < 10; i++) {

cout << i << " "; for (int j = 0; j < 10; j++) { array[i][j] = 'o'; cout << array[i][j] << " "; } cout << endl; } cout << "-------------------------------------"; place(array); computer(array); } int main() { int ships = 0; show();



//show1comp(); cout << "-------------------"; check(); cout << "-----------------------------"; hitting(); system("pause"); return 0; }

python - Reversing a list using slice notation



in the following example:



foo = ['red', 'white', 'blue', 1, 2, 3]


where: foo[0:6:1] will print all elements in foo. However, foo[6:0:-1] will omit the 1st or 0th element.



>>> foo[6:0:-1]

[3, 2, 1, 'blue', 'white']


I understand that I can use foo.reverse() or foo[::-1] to print the list in reverse, but I'm trying to understand why foo[6:0:-1] doesn't print the entire list?


Answer



Slice notation in short:



[  :  :  ]



If you want to include the first element when reversing a list, leave the middle element empty, like this:



foo[::-1]


You can also find some good information about Python slices in general here:
Explain Python's slice notation


syntax - How do I break a string over multiple lines?



In YAML, I have a string that's very long. I want to keep this within the 80-column (or so) view of my editor, so I'd like to break the string. What's the syntax for this?



In other words, I have this:



Key: 'this is my very very very very very very long string'


and I'd like to have this (or something to this effect):



Key: 'this is my very very very ' +
'long string'


I'd like to use quotes as above, so I don't need to escape anything within the string.


Answer



Using yaml folded style, each line break is replaced by a space. The indention in each line will be ignored. A line break will be inserted at the end.



Key: >
This is a very long sentence
that spans several lines in the YAML
but which will be rendered as a string
with only a single carriage return appended to the end.


http://symfony.com/doc/current/components/yaml/yaml_format.html



You can use the "block chomping indicator" to eliminate the trailing line break, as follows:



Key: >-
This is a very long sentence
that spans several lines in the YAML
but which will be rendered as a string
with NO carriage returns.


There are other control tools available as well (for controlling indentation for example).



See https://yaml-multiline.info/


python - Importing modules from parent folder




I am running Python 2.5.



This is my folder tree:



ptdraft/
nib.py
simulations/
life/
life.py



(I also have __init__.py in each folder, omitted here for readability)



How do I import the nib module from inside the life module? I am hoping it is possible to do without tinkering with sys.path.



Note: The main module being run is in the ptdraft folder.


Answer



It seems that the problem is not related to the module being in a parent directory or anything like that.



You need to add the directory that contains ptdraft to PYTHONPATH




You said that import nib worked with you, that probably means that you added ptdraft itself (not its parent) to PYTHONPATH.


Finding non-Ascii character








I'm struggling trying to find an answer to how I can find a non-ascii character in a very large file of xml data. I do not want to convert the non-ascii characters, I just want to identify where in the data file the character is located so I can inform the source to remove the value. The non-ascii data (seems to be a single character) is causing my processing program to fail. Unfortunately the error data does not help me determine where in the file the offending character is located. This XML data file contains data records, and it is most likely in a description field or name field.



I have tried using text tools, but it is such a large file (>32MB) of text that it is overwhelming. Is there a way to run a REGEX to find any character outside the 7-BIT ASCII character set in a tool like PSPad or TextPad?

Monday 30 May 2016

parsing - PHP Version 5.2.14 / Parse error: syntax error, unexpected T_FUNCTION, expecting ')'

I have a certain piece of code that I'm trying to use with PHP Version 5.2.14 . Is it incompatible?? I run the following,



jailshell-3.2$ php -l /XYZ/functions.php



And it gives:




Parse error: syntax error, unexpected T_FUNCTION, expecting ')' in /XYZ/functions.php on line 2115
Errors parsing /XYZ/functions.php




The code is:




2114    $range = array_map(
2115 function (DatePeriod $p) use ($vt2) {
2116 $res = array();

javascript - Sort array of objects by string property value



I have an array of JavaScript objects:



var objs = [ 
{ first_nom: 'Lazslo', last_nom: 'Jamf' },
{ first_nom: 'Pig', last_nom: 'Bodine' },
{ first_nom: 'Pirate', last_nom: 'Prentice' }
];



How can I sort them by the value of last_nom in JavaScript?



I know about sort(a,b), but that only seems to work on strings and numbers. Do I need to add a toString() method to my objects?


Answer



It's easy enough to write your own comparison function:



function compare( a, b ) {
if ( a.last_nom < b.last_nom ){
return -1;

}
if ( a.last_nom > b.last_nom ){
return 1;
}
return 0;
}

objs.sort( compare );



Or inline (c/o Marco Demaio):



objs.sort((a,b) => (a.last_nom > b.last_nom) ? 1 : ((b.last_nom > a.last_nom) ? -1 : 0)); 

How to acess Private function of another class in PHP

I have a dbHandeller.php file . as follow



class dbHandeler {

var $conn;

public function __construct(){

$this->initiatedb();

}

private function initiatedb(){

//Details of the Databse
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "xxxxxx";

// Create connection
$this->conn = mysqli_connect($servername, $username, $password, $dbname);

// Check connection
if (!$this->conn) {
die("Connection failed: " . mysqli_connect_error());
}else
return $this->conn;

}

private function sql_query($query){

}

}


Then I have donation.php and it extends the DB class



function __autoload($class_name) {
include $class_name . '.php';
}

class donation extends dbHandeler{


public function __construct(){

$dbObj = new dbHandeler();
$dbObj->initiatedb();
}

public function putDonation(){
var_dump($_POST);

}

public function getDonation(){


}
}


When I try to access the donation class I am getting following error




Fatal error: Call to private method dbHandeler::initiatedb() from context 'donation' in C:\xampp\htdocs\templeform\api\donation.php on line 13

error

c++ - cppcms lots of unresolved external symbols



I am having errors as follows trying to build cppcms.




Error 184 error LNK2019: unresolved external symbol __imp_pcre_compile referenced in function "public: void __cdecl booster::regex::assign(class std::basic_string,class std::allocator > const &,int)" (?assign@regex@booster@@QEAAXAEBV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@H@Z) C:\Stuff\Development\CPP\cppcms-1.0.2\build\booster\pcre_regex.obj
Error 185 error LNK2019: unresolved external symbol __imp_pcre_exec referenced in function "public: bool __cdecl booster::regex::match(char const *,char const *,class std::vector,class std::allocator > > &,int)const " (?match@regex@booster@@QEBA_NPEBD0AEAV?$vector@U?$pair@HH@std@@V?$allocator@U?$pair@HH@std@@@2@@std@@H@Z) C:\Stuff\Development\CPP\cppcms-1.0.2\build\booster\pcre_regex.obj
Error 186 error LNK2019: unresolved external symbol __imp_pcre_fullinfo referenced in function "public: void __cdecl booster::regex::assign(class std::basic_string,class std::allocator > const &,int)" (?assign@regex@booster@@QEAAXAEBV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@H@Z) C:\Stuff\Development\CPP\cppcms-1.0.2\build\booster\pcre_regex.obj
Error 187 error LNK2019: unresolved external symbol __imp_pcre_malloc referenced in function "public: __cdecl booster::regex::data::data(struct booster::regex::data const &)" (??0data@regex@booster@@QEAA@AEBU012@@Z) C:\Stuff\Development\CPP\cppcms-1.0.2\build\booster\pcre_regex.obj

Error 188 error LNK2019: unresolved external symbol __imp_pcre_free referenced in function __catch$??0data@regex@booster@@QEAA@AEBU012@@Z$0 C:\Stuff\Development\CPP\cppcms-1.0.2\build\booster\pcre_regex.obj
Error 189 error LNK2019: unresolved external symbol __imp_htons referenced in function "public: __cdecl booster::aio::endpoint::endpoint(class std::basic_string,class std::allocator > const &,int)" (??0endpoint@aio@booster@@QEAA@AEBV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@H@Z) C:\Stuff\Development\CPP\cppcms-1.0.2\build\booster\endpoint.obj



My environment is Windows 7 64 bit, using Visual Studio 2012 Professional, and CMake 2.8.9.



For everything I compile, I configure CMake to generate solutions for VS2012 to use the 64 bit compiler. When I do compile the libraries, I compile the release versions.



First I compile Zlib 1.2.7 without a problem.

Second I compile pcre-8.31 without a problem.



Then when it gets time to compile cppcms-1.0.2 I get a bunch or errors as I pointed out before. When configuring cppcms in CMake, I have my PYTHON 2.7 set, I use

 C:/Stuff/Development/CPP/Zlib/zlib-1.2.7/build 
for my ZLIB_INCLUDE_DIR, and just append a /Release/zlibstatic.lib at the end of that and you have the ZLIB library I am using, but I am not sure if I have my PCRE set up correctly.

Being that PCRE has an include and include2 in CMake, I wasn't sure what to put in them so I just did the pcre-8.31 root directory, and the pcre-8.31 build directory. For PCRE_LIB I use pcre-8.31/build/Release/pcre.lib.



I have deleted all of the build directories for the libraries and started over again even, but I still have these issues and I am not sure what could be causing them. Later I realized the booster inside of the cppcms build directory also has a solution, so I built that first, which had 3 failed projects, but most succeeded, however it didn't make a difference for cppcms building.



If you have any more questions about what I was doing, please ask and I will edit them in.


Answer




The best place to ask questions about cppcms is in the cppcms mailing list. Sign up here:
https://lists.sourceforge.net/lists/listinfo/cppcms-users



Artyom is providing an excellent support service there. Although he is also a S.O. member, not all cppcms developers are, and many of them also provide help on the mailing list. Overall, you'll get better answers there, especially since the people who are able to answer will more quickly notice your question.


What are all the uses of an underscore in Scala?

I've taken a look at the list of surveys taken on scala-lang.org and noticed a curious question: "Can you name all the uses of “_”?". Can you? If yes, please do so here. Explanatory examples are appreciated.

plot explanation - How did Thor and Banner know where to go?


In the middle of The Avengers, the team is split up after coming together on the S.H.I.E.L.D. Helicarrier. Bruce Banner/Hulk end up in an abandoned warehouse. Thor ends up in a field. Shortly afterwards, Tony Stark determines Loki's next destination, Stark Tower. This information is never transmitted to Banner or Thor. However, both of them show up in New York City and join in the climactic battle. How did they know where to go?


Answer


How Bruce Banner found the Avengers:


When Banner was aboard the Hellicarrier, his gamma ray search algorithm had worked out where the Tesseract was (Stark Tower), but before he could tell anyone Loki's machinations kicked in and he turned into the Hulk. After he went back to being Bruce Banner, he just found his way to Stark Tower, where the rest of the Avengers had assembled.


How Thor found the Avengers:


This one's a bit more problematic. Thor seems to have the ability to track down Loki. Witness how Thor knew Loki was held inside the jet after he was captured by S.H.I.E.L.D.. How he does that isn't known. So I'm assuming that, however he does it, Thor simply tracked down Loki to Stark Tower.


Does Java have a "IN" operator or function like SQL?




I want to know if there's a way of doing something like this in Java :



if(word in stringArray) {
...
}


I know I can make a function for this but I just want to know if Java has already something for this.



Thank you!


Answer



There are many collections that will let you do something similar to that. For example:



With Strings:



String s = "I can has cheezeburger?";
boolean hasCheese = s.contains("cheeze");


or with Collections:



List listOfStrings = new ArrayList();
boolean hasString = listOfStrings.contains(something);


However, there is no similar construct for a simple String[].


Can CMake Create Solution for Visual Studio Express 2010

Is CMake able to create solutions for Visual Studio Express 2010?




I'm trying to create a Visual Studio solution that will work with Visual Studio Express 2010 (for C++) but I keep running into issues. Whenever I try building the solution in Visual Studio I get the error Invalid license data. Reinstall is required.



In the output window I also see messages that state:



-- The C compiler identification is unknown.
-- The C++ compiler identification is unknown.

java - Object is same but the output is different ? please help









public class AboutStrings{
public static void main(String args[]){
String s1="hello";
String s2="hel";
String s3="lo";
String s4=s2+s3;


//to know the hash codes of s1,s4.

System.out.println(s1.hashCode());
System.out.println(s4.hashCode());

// these two s1 and s4 are having same hashcodes.

if(s1==s4){
System.out.println("s1 and s4 are same.");

}else
System.out.println("s1 and s4 are not same.");
}
}


In the above example even though s1 and s4 are refering to
same object(having same hash codes),



it is printing s1 and s4 are not same.




Can anybody explain in detail why it is behaving like this?


Answer



Just because two objects have the same hash code does not mean they are the same object (you are checking with == the object identity!).



You may want to call



s1.equals(s4)



instead - but even then, both could have the same hash code without being equal either: two objects that are equal must have the same hash code (to work properly in Collections etc), but not vice versa.


c++ - Correct format of #include directive



What's the correct/recommended way to include a file? I'm getting trouble with inclusion (VS2005 compiler...).




I know the correct way is this:



#include "source.cpp"


or this:



#include 



Could # include "source.cpp" cause problems (added space after #)? Some of my team mates use that way and we are getting an unsolved problem.



The point I'm including a source file is that I'm developing under and IDE which doesn't allows to define functions in it's editor due to they'll become local functions.


Answer



To answer your question: no, the space cannot cause an issue. It is perfectly legal to have whitespace (spaces and tabs) between the # introducing a preprocessing directive and the directive's name. VS2005 is sufficiently modern to honour that.



However, what is very strange is that you're apparently including a source file (.cpp) and not just a header file. While technically there's nothing wrong with that, it's quite likely that is not what you really want to do. You didn't specify what errors you're getting, but double definition errors would be a typical class of error caused by including a source file (and compiling it separately as well).


Using PHP in javascript's IF Statement




I am trying to make a confirm box which will desire which php code will be executed.
Heres my code:







The problem is , even if i click YES, $confirmation and boolean from defined() function returns 1.
Whatever I click, (cancel or ok) one of them should be 0 (I've already declared $confirmation before)
But both of codes at if and else blocks are used!

Normally it works like this


Answer



You fundamentally misunderstand what PHP is doing.



PHP is evaluated on the server before the page is sent to your browser. By the time the browser sees it and executes the javascript, all the PHP is gone.



Use your browser's "view source" on the browser window with this code in it. You'll see it looks like this:







You either need to implement what you want to do in javascript to run on the browser, or you need to send a new request to the server and get a new page back (either directly or indirectly) with your response.


php - Get text and link from anchor tag by regex

I have some HTML and I need to get link and text from the anchor tag.



$pattern = '/href="(.*)".*>(.*)<\/a>/'



I didn't get exact link from above pattern but If I used the following pattern



$pattern = '/href="(.*?)".*>(.*)<\/a>/'


I get the desired result, But I didn't understand what question mark (?) does here and why I don't get result If I am not using the question mark (?).

Sunday 29 May 2016

Copying values, applying a formula and pasting the results as values. All operations in different Sheets - VBA Macro Excel



I am trying to create a Macro in Excel with VBA, that builds a bunch of different email addresses with a person's first, middle and last name and the company's email domain. I then want to verify these different email addresses with an email bulk tester which is another application.



In Sheet1 I have the input data for the email addresses in the following columns:



First names: F



Middle names: G




Last names: H



Email domains: I



Since there are 52 different persons whose email addresses I want to find, all the data is thus in cells F2:I53.



On Sheet2 I would need to fill in the first, middle and last name as well as the email domain of each person separately in cells B2:B5. On the same Sheet, 46 different possible email addresses will be generated for each person in cells G2:G47.



On Sheet3, I want to copy paste all 46 different email addresses as values. For the first person, I want to copy paste these 46 email addresses into cell A3. For the second person I want to copy paste them into cell A49, for the third person into cell A95, etc. Since I wanna do this for 52 persons, the last populated cell should be A2394.




Here you can take a look at this table which I would normally have in excel:



https://docs.google.com/spreadsheets/d/1kWPfscdnz_TCS7K1H3to1rBgRzJ9XSBH8L7rjKhlTnc/edit?usp=sharing



Thus the macro is supposed to do the following in the first iteration:




  1. Select and copy cells F2:I2 on Sheet1


  2. Go to Sheet2 and special paste them (transpose) in cells B2:B5



  3. Select and copy cells G2:G47


  4. Go to Sheet3 and past them as values into cell A3




In the second iteration, the macro is supposed to do the following:




  1. Select and copy cells F3:I3 on Sheet1


  2. Go to Sheet2 and special paste them (transpose) in cells B2:B5


  3. Select and copy cells G2:G47



  4. Go to Sheet3 and past them as values into cell A49




As you can see in 1) and 2), the row number increments after every iteration. This whole process is thus to be repeated 52 times. Below, you can see the macro I have created



Sub Macro1()
Dim i As Integer
Dim m As Integer
For i = 1 To 52
'selecting the first, middle and last name (columns I to F)

m = i + 1
Range("F" & m & ":I" & m).Select ' maybe I need to use the Indirect function here?
Selection.Copy
Sheets("Sheet2").Select
Range("B2").Select
Selection.PasteSpecial Paste:=xlPasteAll, Operation:=xlNone, SkipBlanks:= _
False, Transpose:=True
' Maybe give excel some time to calculate the email addresses first?
Application.Calculate
Range("G2:G47").Select

Selection.Copy
Sheets("Sheet3").Select
'Find the first empty cell in column A
Range("A1").End(xlDown).Offset(1, 0).Select
'pasting the email addresses as values
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
'end of iteration
Next i
End Sub



However, when I run the macro, the cells A3:A2394 on Sheet3 only contain the @ sign (see google sheet). Unfortunately, I have no idea where exactly the error occurs. My suspicion was that I need to give excel some time to calculate the 46 different email addresses in G2:G47 in Sheet2, so I added the "Application.Calcuate" command, but it also didn't work.



Would be awesome if someone of you could help.



Thanks in advance,
Kevin


Answer



Below code is now working:




Sub Macro1()

Dim i As Integer
Dim m As Integer

Dim wSheet1 As Worksheet
Dim wSheet2 As Worksheet
Dim wSheet3 As Worksheet


Set wSheet1 = Sheets("Sheet1")
Set wSheet2 = Sheets("Sheet2")
Set wSheet3 = Sheets("Sheet3")

For i = 1 To 52
'selecting the first, middle and last name (columns I to F)
m = i + 1
wSheet1.Range("F" & m & ":I" & m).Copy
wSheet2.Range("B2").PasteSpecial Paste:=xlPasteAll, Operation:=xlNone, SkipBlanks:= _
False, Transpose:=True

' Maybe give excel some time to calculate the email addresses first?
Application.Calculate
wSheet2.Range("G2:G47").Copy
'Find the first empty cell in column A and paste as values
wSheet3.Range("A1").End(xlDown).Offset(1, 0).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
'end of iteration
Next i

' code from the macro runner

'Range("F2:I2").Select ' question is how to select the same range next time, only one row lower?
'Selection.Copy
'Sheets("Sheet2").Select
' pasting the name (as transpose)
'Range("B2").Select
'Selection.PasteSpecial Paste:=xlPasteAll, Operation:=xlNone, SkipBlanks:= _
False, Transpose:=True
' selecting all the possible email addresses
'Range("G2").Select ' shouldn't it be Range("G2:G47).Select ?
'Range(Selection, Selection.End(xlDown)).Select

'Application.CutCopyMode = False
'Selection.Copy
' paste all possible email addresses as values into Sheet3
'Sheets("Sheet3").Select
'Range("A1").Select ' Question is how to select the first empty row in column A of that Sheet
'Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False

End Sub


Python : When is a variable passed by reference and when by value?












My code :



locs = [ [1], [2] ]
for loc in locs:
loc = []

print locs
# prints => [ [1], [2] ]



Why is loc not reference of elements of locs ?



Python : Everything is passed as reference unless explicitly copied [ Is this not True ? ]



Please explain.. how does python decides referencing and copying ?



Update :



How to do ?




def compute(ob):
if isinstance(ob,list): return process_list(ob)
if isinstance(ob,dict): return process_dict(ob)

for loc in locs:
loc = compute(loc) # What to change here to make loc a reference of actual locs iteration ?



  • locs must contain the final processed response !


  • I don't want to use enumerate, is it possible without it ?


Answer



Everything in Python is passed and assigned by value, in the same way that everything is passed and assigned by value in Java. Every value in Python is a reference (pointer) to an object. Objects cannot be values. Assignment always copies the value (which is a pointer); two such pointers can thus point to the same object. Objects are never copied unless you're doing something explicit to copy them.



For your case, every iteration of the loop assigns an element of the list into the variable loc. You then assign something else to the variable loc. All these values are pointers; you're assigning pointers; but you do not affect any objects in any way.


How to remove value and reassign remaining values to keys in array in PHP




The below code,



$test_array = array("a","b","c","d","e");
echo "
";
htmlspecialchars(print_r($test_array));
echo "
";



which gives output like,



Array
(
[0] => a
[1] => b
[2] => c
[3] => d
[4] => e
)



I want to remove a specific entry say from index 2 and re-index the array as below,



Array
(
[0] => a
[1] => b
[2] => d
[3] => e

)


How to do that?


Answer



Use array_splice



array_splice($test_array, 2, 1);



The second argument is your index that you want to nix and the third is how many elements you want gone.


syntax - Do I need quotes for strings in YAML?



I am trying to write a YAML dictionary for internationalization of a Rails project. I am a little confused though, as in some files I see strings in double quotes and in some without. A few points to consider:





  • example 1 - all strings use double quotes;

  • example 2 - no strings (except the last two) use quotes;

  • the YAML cookbook says: Enclosing strings in double quotes allows you to use escapings to represent ASCII and Unicode characters. Does this mean I need to use double quotes only when I want to escape some characters? If yes - why do they use double quotes everywhere in the first example - only for the sake of unity / stylistic reasons?

  • the last two lines of example 2 use ! - the non-specific tag, while the last two lines of the first example don't - and they both work.



My question is: what are the rules for using the different types of quotes in YAML?




Could it be said that:




  • in general, you don't need quotes;

  • if you want to escape characters use double quotes;

  • use ! with single quotes, when... ?!?


Answer



After a brief review of the YAML cookbook cited in the question and some testing, here's my interpretation:





  • In general, you don't need quotes.

  • Use quotes to force a string, e.g. if your key or value is 10 but you want it to return a String and not a Fixnum, write '10' or "10".

  • Use quotes if your value includes special characters, (e.g. :, {, }, [, ], ,, &, *, #, ?, |, -, <, >, =, !, %, @, \).

  • Single quotes let you put almost any character in your string, and won't try to parse escape codes. '\n' would be returned as the string \n.

  • Double quotes parse escape codes. "\n" would be returned as a line feed character.

  • The exclamation mark introduces a method, e.g. !ruby/sym to return a Ruby symbol.



Seems to me that the best approach would be to not use quotes unless you have to, and then to use single quotes unless you specifically want to process escape codes.




Update



"Yes" and "No" should be enclosed in quotes (single or double) or else they will be interpreted as TrueClass and FalseClass values:



en:
yesno:
'yes': 'Yes'
'no': 'No'


apache - Tips for debugging .htaccess rewrite rules

Many posters have problems debugging their RewriteRule and RewriteCond statements within their .htaccess files. Most of these are using a shared hosting service and therefore don't have access to the root server configuration. They cannot avoid using .htaccess files for rewriting and cannot enable a RewriteLogLevel" as many respondents suggest. Also there are many .htaccess-specific pitfalls and constraints are aren't covered well. Setting up a local test LAMP stack involves too much of a learning curve for most.



So my Q here is how would we recommend that they debug their rules themselves. I provide a few suggestions below. Other suggestions would be appreciated.





  1. Understand that the mod_rewrite engine cycles through .htaccess files. The engine runs this loop:



    do
    execute server and vhost rewrites (in the Apache Virtual Host Config)
    find the lowest "Per Dir" .htaccess file on the file path with rewrites enabled
    if found(.htaccess)
    execute .htaccess rewrites (in the user's directory)
    while rewrite occurred



    So your rules will get executed repeatedly and if you change the URI path then it may end up executing other .htaccessfiles if they exist. So make sure that you terminate this loop, if necessary by adding extra RewriteCond to stop rules firing. Also delete any lower level .htaccess rewrite rulesets unless explicitly intent to use multi-level rulesets.


  2. Make sure that the syntax of each Regexp is correct by testing against a set of test patterns to make sure that is a valid syntax and does what you intend with a fully range of test URIs. See answer below for more details.


  3. Build up your rules incrementally in a test directory. You can make use of the "execute the deepest .htaccess file on the path feature" to set up a separate test directory (tree) and debug rulesets here without screwing up your main rules and stopping your site working. You have to add them one at a time because this is the only way to localise failures to individual rules.


  4. Use a dummy script stub to dump out server and environment variables. (See Listing 2)If your app uses, say, blog/index.php then you can copy this into test/blog/index.php and use it to test out your blog rules in the test subdirectory. You can also use environment variables to make sure that the rewrite engine in interpreting substitution strings correctly, e.g.



    RewriteRule ^(.*) - [E=TEST0:%{DOCUMENT_ROOT}/blog/html_cache/$1.html]


    and look for these REDIRECT_* variables in the phpinfo dump. BTW, I used this one and discovered on my site that I had to use %{ENV:DOCUMENT_ROOT_REAL} instead. In the case of redirector looping REDIRECT_REDIRECT_* variables list the previous pass. Etc..



  5. Make sure that you don't get bitten by your browser caching incorrect 301 redirects. See answer below. My thanks to Ulrich Palha for this.


  6. The rewrite engine seems sensitive to cascaded rules within an .htaccess context, (that is where a RewriteRule results in a substitution and this falls though to further rules), as I found bugs with internal sub-requests (1), and incorrect PATH_INFO processing which can often be prevents by use of the [NS], [L] and [PT] flags.




Any more comment or suggestions?



Listing 1 -- phpinfo



Saturday 28 May 2016

mysql - php - how to convert non utf-8 string to utf-8

I've a php page that return a string in persian , this is the content I have now :



    ÙروشگاÙ‡ تعطÛŒل Ù…ÛŒ باشد .

ساعت کارÛŒ ÙروشگاÙ‡ 8 اÙ„ÛŒ 22
روزهاÛŒ شنبÙ‡ تا پنج شنبÙ‡


as you can see, the encoding is wrong and it's not readable ,I need to convert it to utf-8 encoding .
I'm returning the data from database, encoding of table and cell in database is utf8_persian_ci and it's shows currency in phpmyadmin .



How can I convert this non readable string to utf-8 encoding and make it readable ?
I've tried utf8-encoding and below code but non of them works :




    echo iconv(mb_detect_encoding($string, mb_detect_order(), true), "UTF-8", $string);


How can I fix this ?

swift - What is the difference between Xcode project and Xcode playground?



I'm new to Xcode and swift and I'm trying to understand what's the difference between "starting with playground" and "creating a new xcode project"enter image description here


Answer



An Xcode project allows you to create real apps that you could eventually upload to the App Store (providing you became an Apple Developer). An Xcode Playground allows you to play with code and test it out. It isn't for mainstream developing. Does that help?


multithreading - C++11 introduced a standardized memory model. What does it mean? And how is it going to affect C++ programming?



C++11 introduced a standardized memory model, but what exactly does that mean? And how is it going to affect C++ programming?




This article (by Gavin Clarke who quotes Herb Sutter) says that,




The memory model means that C++ code
now has a standardized library to call
regardless of who made the compiler
and on what platform it's running.
There's a standard way to control how
different threads talk to the
processor's memory.




"When you are talking about splitting
[code] across different cores that's
in the standard, we are talking about
the memory model. We are going to
optimize it without breaking the
following assumptions people are going
to make in the code," Sutter said.





Well, I can memorize this and similar paragraphs available online (as I've had my own memory model since birth :P) and can even post as an answer to questions asked by others, but to be honest, I don't exactly understand this.



C++ programmers used to develop multi-threaded applications even before, so how does it matter if it's POSIX threads, or Windows threads, or C++11 threads? What are the benefits? I want to understand the low-level details.



I also get this feeling that the C++11 memory model is somehow related to C++11 multi-threading support, as I often see these two together. If it is, how exactly? Why should they be related?



As I don't know how the internals of multi-threading work, and what memory model means in general, please help me understand these concepts. :-)


Answer



First, you have to learn to think like a Language Lawyer.




The C++ specification does not make reference to any particular compiler, operating system, or CPU. It makes reference to an abstract machine that is a generalization of actual systems. In the Language Lawyer world, the job of the programmer is to write code for the abstract machine; the job of the compiler is to actualize that code on a concrete machine. By coding rigidly to the spec, you can be certain that your code will compile and run without modification on any system with a compliant C++ compiler, whether today or 50 years from now.



The abstract machine in the C++98/C++03 specification is fundamentally single-threaded. So it is not possible to write multi-threaded C++ code that is "fully portable" with respect to the spec. The spec does not even say anything about the atomicity of memory loads and stores or the order in which loads and stores might happen, never mind things like mutexes.



Of course, you can write multi-threaded code in practice for particular concrete systems – like pthreads or Windows. But there is no standard way to write multi-threaded code for C++98/C++03.



The abstract machine in C++11 is multi-threaded by design. It also has a well-defined memory model; that is, it says what the compiler may and may not do when it comes to accessing memory.



Consider the following example, where a pair of global variables are accessed concurrently by two threads:




           Global
int x, y;

Thread 1 Thread 2
x = 17; cout << y << " ";
y = 37; cout << x << endl;


What might Thread 2 output?




Under C++98/C++03, this is not even Undefined Behavior; the question itself is meaningless because the standard does not contemplate anything called a "thread".



Under C++11, the result is Undefined Behavior, because loads and stores need not be atomic in general. Which may not seem like much of an improvement... And by itself, it's not.



But with C++11, you can write this:



           Global
atomic x, y;

Thread 1 Thread 2

x.store(17); cout << y.load() << " ";
y.store(37); cout << x.load() << endl;


Now things get much more interesting. First of all, the behavior here is defined. Thread 2 could now print 0 0 (if it runs before Thread 1), 37 17 (if it runs after Thread 1), or 0 17 (if it runs after Thread 1 assigns to x but before it assigns to y).



What it cannot print is 37 0, because the default mode for atomic loads/stores in C++11 is to enforce sequential consistency. This just means all loads and stores must be "as if" they happened in the order you wrote them within each thread, while operations among threads can be interleaved however the system likes. So the default behavior of atomics provides both atomicity and ordering for loads and stores.



Now, on a modern CPU, ensuring sequential consistency can be expensive. In particular, the compiler is likely to emit full-blown memory barriers between every access here. But if your algorithm can tolerate out-of-order loads and stores; i.e., if it requires atomicity but not ordering; i.e., if it can tolerate 37 0 as output from this program, then you can write this:




           Global
atomic x, y;

Thread 1 Thread 2
x.store(17,memory_order_relaxed); cout << y.load(memory_order_relaxed) << " ";
y.store(37,memory_order_relaxed); cout << x.load(memory_order_relaxed) << endl;


The more modern the CPU, the more likely this is to be faster than the previous example.




Finally, if you just need to keep particular loads and stores in order, you can write:



           Global
atomic x, y;

Thread 1 Thread 2
x.store(17,memory_order_release); cout << y.load(memory_order_acquire) << " ";
y.store(37,memory_order_release); cout << x.load(memory_order_acquire) << endl;



This takes us back to the ordered loads and stores – so 37 0 is no longer a possible output – but it does so with minimal overhead. (In this trivial example, the result is the same as full-blown sequential consistency; in a larger program, it would not be.)



Of course, if the only outputs you want to see are 0 0 or 37 17, you can just wrap a mutex around the original code. But if you have read this far, I bet you already know how that works, and this answer is already longer than I intended :-).



So, bottom line. Mutexes are great, and C++11 standardizes them. But sometimes for performance reasons you want lower-level primitives (e.g., the classic double-checked locking pattern). The new standard provides high-level gadgets like mutexes and condition variables, and it also provides low-level gadgets like atomic types and the various flavors of memory barrier. So now you can write sophisticated, high-performance concurrent routines entirely within the language specified by the standard, and you can be certain your code will compile and run unchanged on both today's systems and tomorrow's.



Although to be frank, unless you are an expert and working on some serious low-level code, you should probably stick to mutexes and condition variables. That's what I intend to do.



For more on this stuff, see this blog post.


r - ggplot renders in shiny app but not on shinyapps.io, no errors or warnings

The shiny app in question is 250 lines of code, so I will try to copy the relevant snippets below, but it may be impractical to produce a working example that reproduces the issue I am having.



When I run the shiny app, it runs flawlessly locally. When I deploy it to shinyapps.io, I receive success messages and no errors or warnings. However, when I view the shinyapps.io in the browser none of the valueboxes or ggplots are visible.




I suspect that the issue COULD be memory (the dataset is 500K rows). Maybe the shiny apps server is running out of memory before it loads? Again, no warnings, errors, or relevant messages on the logs (or on the deploy tab when deploying the app to shinyapps.io).



In the ui, I have these rows showing various plots and value boxes:



                  #Value boxes to show numeric stats
fluidRow(
valueBoxOutput("comp_fare"),
valueBoxOutput("num_comp_fares"),
valueBoxOutput("num_aa_fares")

),

br(),
h2("Impact of continuous features on fares"),

#Select continuous variables
fluidRow(
column(selectInput(inputId = "continuous_variable",
label = "Choose a Variable to Compare: ",
choices = df %>%

select_if(is.numeric) %>% select(-fare) %>%
names,
selected = "distance"
), width = 6),
column(selectInput(inputId = "fit_method",
label = "Choose a Fit Method: ",
choices = c("Linear", "Quadratic"),
selected = "Linear"
), width = 6)
),


br(),

#Plot continuous variables
fluidRow(
plotOutput("cont_plot")
),

br(),
h2("Impact of discrete features on fares"),


#Select factor variables
fluidRow(
column(selectInput(inputId = "factor_variable",
label = "Choose a Variable to Compare: ",
choices = df %>%
select_if(is.factor) %>%
names,
selected = "hub_airport"
), width = 6),

column(selectInput(inputId = "display_layout",
label = "Choose a Display Layout: ",
choices = c("Fill", "Dodge"),
selected = "Dodge"
), width = 6)
),

br(),

#Plot factor variables

fluidRow(
plotOutput("cat_plot")
),

#server code

#ValueBoxes
output$comp_fare <- renderValueBox({
valueBox(competitor_fare_difference(),
"Difference in Competitor Fare",

icon = icon("dollar"),
color = "yellow")
})

output$cont_plot <- renderPlot({
ggplot() +
geom_smooth(data = df2(),
aes_string(input$continuous_variable, "fare", color = "carrier"),
method = "lm",
formula = y ~ poly(x, fit_method())) +

geom_point(data = sample_n(df2(), 1000),
aes_string(input$continuous_variable, "fare", color = "carrier"),
alpha = .3) +
theme_bw() +
scale_y_continuous(labels = dollar) +
labs(title = paste0("Comparison of American Airlines and ", input$competitor),
x = input$continuous_variable,
y = "Round-trip Fare ($US)"
) %>% print
})

python - Read username and password from a file




How can i read text, e.g., username and password from a file line-by-line in Python? For example, i can achieve this in shell/bash:



#!/bin/bash

AUTH='/authentication/account.txt'
U=$(sed -n 1p ${AUTH})
P=$(sed -n 2p ${AUTH})



and inside the file /authentication/account.txt are my username and password line-by-line like this:



username
userpass

Answer



You should not be storing unencrypted login details in text files.



However, here is a very simple solution anyway:




f=open("/authentication/account.txt","r")
lines=f.readlines()
username=lines[0]
password=lines[1]
f.close()

android - App force closes when returned back from the second activity to the first, the first activity no more works, has to be restarted again



I'm designing an application that allows the user to retrieve his data from the server, I'm furnishing this using two different activities, the first one receives the username as a text input and the second one displays the user's data based on the username. I'm using JSON schema for storing and retrieving the data. The app works fine for the first time but when I logout from the second screen using finish() and try to re-enter a new username in the first screen "the app force closes". This has been giving me sleepless nights, want to be overwhelmed with your support.




12-04 16:28:35.289: D/dalvikvm(553): GC_FOR_ALLOC freed 64K, 4% free 6893K/7171K, paused 64ms
12-04 16:28:35.299: I/dalvikvm-heap(553): Grow heap (frag case) to 7.757MB for 1000016-byte allocation

12-04 16:28:35.399: D/dalvikvm(553): GC_CONCURRENT freed 1K, 5% free 7868K/8199K, paused 16ms+3ms
12-04 16:28:35.529: D/dalvikvm(553): GC_FOR_ALLOC freed <1K, 5% free 7869K/8199K, paused 31ms
12-04 16:28:35.539: I/dalvikvm-heap(553): Grow heap (frag case) to 8.180MB for 443572-byte allocation
12-04 16:28:35.589: D/dalvikvm(553): GC_CONCURRENT freed 0K, 4% free 8302K/8647K, paused 3ms+5ms
12-04 16:28:35.889: D/gralloc_goldfish(553): Emulator without GPU emulation detected.
12-04 16:29:16.819: D/dalvikvm(553): GC_FOR_ALLOC freed 1079K, 14% free 7509K/8711K, paused 221ms
12-04 16:29:16.829: I/dalvikvm-heap(553): Grow heap (frag case) to 8.360MB for 1000016-byte allocation
12-04 16:29:16.889: D/dalvikvm(553): GC_CONCURRENT freed 2K, 3% free 8483K/8711K, paused 4ms+4ms
12-04 16:29:17.229: D/dalvikvm(553): GC_CONCURRENT freed 1016K, 13% free 7979K/9159K, paused 3ms+11ms
12-04 16:29:18.149: E/log_tag(553): Error parsing data org.json.JSONException: No value for Alert

12-04 16:29:20.949: D/dalvikvm(553): GC_CONCURRENT freed 274K, 12% free 8090K/9159K, paused 6ms+5ms
12-04 16:29:26.259: E/log_tag(553): Error parsing data org.json.JSONException: No value for Alert
12-04 16:29:26.859: D/AndroidRuntime(553): Shutting down VM
12-04 16:29:26.859: W/dalvikvm(553): threadid=1: thread exiting with uncaught exception (group=0x409951f8)
12-04 16:29:26.929: E/AndroidRuntime(553): FATAL EXCEPTION: main
12-04 16:29:26.929: E/AndroidRuntime(553): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.bombil.kustomizer/com.bombil.kustomizer.Menus}: java.lang.IndexOutOfBoundsException: Invalid index 2, size is 2
12-04 16:29:26.929: E/AndroidRuntime(553): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1955)
12-04 16:29:26.929: E/AndroidRuntime(553): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1980)
12-04 16:29:26.929: E/AndroidRuntime(553): at android.app.ActivityThread.access$600(ActivityThread.java:122)
12-04 16:29:26.929: E/AndroidRuntime(553): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1146)

12-04 16:29:26.929: E/AndroidRuntime(553): at android.os.Handler.dispatchMessage(Handler.java:99)
12-04 16:29:26.929: E/AndroidRuntime(553): at android.os.Looper.loop(Looper.java:137)
12-04 16:29:26.929: E/AndroidRuntime(553): at android.app.ActivityThread.main(ActivityThread.java:4340)
12-04 16:29:26.929: E/AndroidRuntime(553): at java.lang.reflect.Method.invokeNative(Native Method)
12-04 16:29:26.929: E/AndroidRuntime(553): at java.lang.reflect.Method.invoke(Method.java:511)
12-04 16:29:26.929: E/AndroidRuntime(553): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
12-04 16:29:26.929: E/AndroidRuntime(553): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
12-04 16:29:26.929: E/AndroidRuntime(553): at dalvik.system.NativeStart.main(Native Method)
12-04 16:29:26.929: E/AndroidRuntime(553): Caused by: java.lang.IndexOutOfBoundsException: Invalid index 2, size is 2
12-04 16:29:26.929: E/AndroidRuntime(553): at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:251)

12-04 16:29:26.929: E/AndroidRuntime(553): at java.util.ArrayList.get(ArrayList.java:304)
12-04 16:29:26.929: E/AndroidRuntime(553): at com.bombil.kustomizer.Menus.AddEditText(Menus.java:309)
12-04 16:29:26.929: E/AndroidRuntime(553): at com.bombil.kustomizer.Menus.AddInsertView(Menus.java:121)
12-04 16:29:26.929: E/AndroidRuntime(553): at com.bombil.kustomizer.Menus.onCreate(Menus.java:88)
12-04 16:29:26.929: E/AndroidRuntime(553): at android.app.Activity.performCreate(Activity.java:4465)
12-04 16:29:26.929: E/AndroidRuntime(553): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
12-04 16:29:26.929: E/AndroidRuntime(553): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1919)
12-04 16:29:26.929: E/AndroidRuntime(553): ... 11 more
12-04 16:29:27.009: D/dalvikvm(553): GC_CONCURRENT freed 273K, 10% free 8248K/9159K, paused 4ms+6ms
12-04 16:32:56.799: I/Process(553): Sending signal. PID: 553 SIG: 9




Answer



Apparently, you're trying to access an object in an ArrayList at in your Menus.java file at line 309. You're trying to access the object with the index of 2, but the total ArrayList size is only 2, meaning the highest index would be 1. This causes an IndexOutOfBounds exception as shown here:



    ComponentInfo{com.bombil.kustomizer/com.bombil.kustomizer.Menus}:
java.lang.IndexOutOfBoundsException: Invalid index 2, size is 2

E/AndroidRuntime(553): at com.bombil.kustomizer.Menus.AddEditText(Menus.java:309)

Friday 27 May 2016

c++ - `y=++y`, is this standard compliant? [which appears in a test by Microsoft]




I know this looks familiar but it is brought to me as a problem in a test by Microsoft to recruit interns. It seems to me that y=++y is not standard compliant, but I think maybe it would be better to be sure (not sure that I'm better than those who write up these tests at MS). So I'm asking your advice. Do you think expressions like this is standard-compliant and does not result in undefined behaviour?



#include 
int main(){
int a = 10;
int b = 10;

a = ++a; //What ???
b = b++; //What ???
printf("%d %d\n",a,b);
return 0;
}


gcc complains about it when used to compile with -Wsequence-point. (It is not explicitly stated whether it is a C or C++ specific problem.)



But only four answers provided:




a) 10 10
b) 11 10
c) 10 11
d) 11 11


Although one is not restricted to select only one answer ( so maybe I should choose all four? )



Well, in my opinion, between self-incrementing and assignment there is no sequence point. So this violates the specification. Doesn't it?



Answer



They're both well-defined behaviour as per C++11. C++11 doesn't even have sequence points, so a sequence-point related warning is obviously outdated. The assignment operator imposes sequencing on its arguments.



Edit:



Whilst everyone can agree that i = ++i is now well-defined behaviour, it is rather non-trivial to decide the definedness of i = i++. Intuitively, I should describe it as well-defined, but the Standard clearly states that



i = i++ + 1;



is UB, and I'm not seeing the + 1 making any difference here.



The short is, if you wanted to answer this question, you would need to be an expert on the decidedly non-trivial C++11 sequencing rules, which it appears that I am not, but it appears that the answer is "None of the above because UB".


c++ - Does sizeof(pointer) depend on the object type?




I'm trying to understand what a pointer to an object means. I'm wondering if A is an incomplete type, why is a pointer to A a complete type. Consider the following program:



#include 

class B; //B is incomplete type here

int main()
{

printf("%d\n",sizeof(B*));//4
}


Please explain why does sizeof(B*) return 4? What exactly does a pointer to an object represent in memory?


Answer




Please explain why sizeof(B*) return 4?





It returns 4 because size of a pointer variable is 4 in your system.




What exactly pointer to object represents in memory?




Objects reside in memory, and pointer to an object contains the starting memory address of that object. For example, if your B object has size 100 Byte, and it is placed in 1024-1123(100 Bytes) memory location, then a pointer to that object will hold the value `024 (starting address).




Is pointer to sizeof depends on the object type?





I guess you meant does pointer size depends on object type?. No, since pointers contain an address, it's size depends on address space of your system, not type of object it points to.


How do I generate random integers within a specific range in Java?

How do I generate a random int value in a specific range?




I have tried the following, but those do not work:



Attempt 1:



randomNum = minimum + (int)(Math.random() * maximum);
// Bug: `randomNum` can be bigger than `maximum`.


Attempt 2:




Random rn = new Random();
int n = maximum - minimum + 1;
int i = rn.nextInt() % n;
randomNum = minimum + i;
// Bug: `randomNum` can be smaller than `minimum`.

assembly - How is POPCNT implemented in hardware?




According to http://www.agner.org/optimize/instruction_tables.pdf, the POPCNT instruction (which returns the number of set bits in a 32-bit or 64-bit register) has a throughput of 1 instruction per clock cycle on modern Intel and AMD processors. This is much faster than any software implementation which needs multiple instructions (How to count the number of set bits in a 32-bit integer?).



How is POPCNT implemented so efficiently in hardware?


Answer



There's a patent for combined popcnt, bit scan forward / reverse:



US8214414 B2 - Combined set bit count and detector logic




Abstract




A merged datapath for PopCount and BitScan is described. A hardware circuit includes a compressor tree utilized for a PopCount function, which is reused by a BitScan function (e.g., bit scan forward (BSF) or bit scan reverse (BSR)). Selector logic enables the compressor tree to operate on an input word for the PopCount or BitScan operation, based on a microprocessor instruction. The input word is encoded if a BitScan operation is selected. The compressor tree receives the input word, operates on the bits as though all bits have same level of significance (e.g., for an N-bit input word, the input word is treated as N one-bit inputs). The result of the compressor tree circuit is a binary value representing a number related to the operation performed (the number of set bits for PopCount, or the bit position of the first set bit encountered by scanning the input word).



Complex CSS selector for parent of active child





Is there a way to select a parent element based on the class of a child element in the class? The example that is relevant to me relating to HTML output by a nice menu plugin for http://drupal.org. The output renders like this:



  


My question is whether or not it is possible to apply a style to the list item that contains the anchor with the active class on it. Obviously, I'd prefer that the list item be marked as active, but I don't have control of the code that gets produced. I could perform this sort of thing using javascript (JQuery springs to mind), but I was wondering if there is a way to do this using CSS selectors.



Just to be clear, I want to apply a style to the list item, not the anchor.


Answer




Unfortunately, there's no way to do that with CSS.



It's not very difficult with JavaScript though:



// JavaScript code:
document.getElementsByClassName("active")[0].parentNode;

// jQuery code:
$('.active').parent().get(0); // This would be the 's parent
  • .


  • c++ - error LNK2019: unresolved external symbol in a multiple projects solution



    I have a visual studio solution with multiple projects. One of them, "MyProject" is a static library (.lib). The project, among many other classes has two classes "A" and "B".



    A.h:



    #pragma once


    class A
    {
    public:
    void foo();
    };


    A.cpp:




    #include A.h

    void A::foo(){
    //do something
    }


    B.h:



    #pragma once


    class B
    {
    public:
    void bar();
    };


    B.cpp:




    #include B.h
    #include A.h

    void B::bar(){
    A a;
    a.foo();
    }


    Without compilation errors I'm getting the linkage error:





    OtherProject.lib(B.obj) : error LNK2019: unresolved external symbol "public: void __thiscall
    A::foo(void)" (?foo@A@@QAE_NXZ) referenced in function "public: void
    __thiscall B::bar(void)" (?bar@B@@QAEXXZ)




    Everything seems to be fine. I do see the compilation process of A.cpp. Building or linking only the project "MyProject" is fine. But when trying to build the whole solution I'm getting the error.



    Thanks!



    Answer



    It turns out that, there is another project OtherProject that includes class B and uses it's function bar(). I didn't read the error good enough and didn't notice that the linkage error occurs in another project. All I had to do is include A.cpp in OtherProject.


    bash - How to make the hardware beep sound in Mac OS X 10.6



    I just want that Mac OS X 10.6 does a hardware beep sound like in open suse and other distributions. I tried following approaches



    Terminal -> beep = -bash: beep: command not found



    Terminal -> say beep = voice speaks out beep (Not a Hardware beep but awesome ;) )




    applescript -> beep = Macintosh bell (I want a Hardware beep!)



    Does anybody know how to make the Hardware beep in bin/bash or applescript?


    Answer



    There is no "hardware beep" in macOS.



    The functionality you're thinking of is an artifact of very old (pre-1990s) IBM PC-compatible hardware. Before most computers had sound cards, most machines had a small speaker or piezo buzzer connected to one of the channels of a timer chip. This could be used to generate simple tones or beeps. Even after many computers integrated sound cards, it remained common for quite some time for computers to route this output to a separate internal speaker. More recently, many computers, especially laptops, have integrated this functionality into the onboard sound card.



    (If you're curious about the technical details of how the PC speaker interface worked, there are more details here.)




    This hardware has never existed in Apple computers. The only audio output available is through the sound card, and the only system beep in macOS is the user's alert sound.


    javascript - Angular 2 - Using 'this' inside setTimeout




    I have a function like so in my class



      showMessageSuccess(){


    var that = this;
    this.messageSuccess = true;

    setTimeout(function(){
    that.messageSuccess = false;
    },3000);

    }



    How can I re-write this so I don't have to store a reference to 'this' in the 'that' var? If I use 'this' inside the setTimeout, the messageSuccess bool doesn't seem to change/get updated.


    Answer



    You need to use ArrowFunction ()=> to preserve this context within setTimeout.



    // var that = this; // no need of this line
    this.messageSuccess = true;

    setTimeout(()=>{ //<<<--- using ()=> syntax
    this.messageSuccess = false;

    }, 3000);

    html - how can I align to middle by height




    I want to create image box(with image).
    It's ugly when text is in the top of box.



    How can I align text to middle?
    I tried to use vertical-align, but it seems, that it don't works



    Demo of my code



    EDIT:
    Your solution works fine with short messages.
    But if they will be multi-lined, it is ugly again.
    Is it possible to not increase size of line If we don't need it?



    enter image description here


    Answer



    What usually works fine is line-height:



    line-height: 32px;


    http://jsfiddle.net/DhHnZ/2/


    reactjs - Cannot read property 'setState' of undefined, when running a function



    class App extends Component {
    constructor(){

    super();
    this.state = {
    sideNav: '',
    language: 'en'
    }
    }

    langEn() {
    this.setState({language: 'en'}).bind(this);
    console.log("Language changed to en");

    }

    langEs() {
    this.setState({language: 'es'}).bind(this);
    console.log("Language changed to es");
    }

    render() {

    const mouseEnter = e => {

    this.setState({sideNav: "sideNav sidenav---sidenav---_2tBP sidenav---expanded---1KdUL"});
    }

    const mouseLeave = e => {
    this.setState({sideNav: "sidenav---sidenav---_2tBP sidenav---collapsed---LQDEv"});
    }


    return (



    onMouseEnter={mouseEnter}
    onMouseLeave={mouseLeave}
    className={this.state.sideNav}
    onSelect={(selected) => {
    // Add your code here
    }}
    >







    Dashboard








    Sites








    Tours







    Media








    Add new Site








    Language








    Profile











    );
    }
    }

    export default App;



    The error happens when I press one of the two buttons to run the lanEn or lanEs functions. I have tried alternating where they are, placing them in or out of the render() method, removing this using bind. The end goal is change the language state using these buttons and transfer it to different pages using props


    Answer



    You just need to add this piece of code in the constructor:



    this.langEn = this.langEn.bind(this);


    What the above code does is, it replaces the existing langEn function with a new function with the this context changed to class App.




    If you don't want to manually bind it in the constructor, you can go with arrow functions, which has lexical binding.


    Thursday 26 May 2016

    replaceall - Java Remove Dash In String Array





    Currently I am trying to remove dash in my string array. The code that I tried below didn't work.



    splitTimeStamp[0].replaceAll("[\\s\\-()]", "");
    System.out.println(splitTimeStamp[0]);



    Got the replaceAll code from another stackoverflow page.



    Thanks in advance!


    Answer



    The method returns a new String. The original one isn't changed.
    You need to save the result like this



    splitTimeStamp[0] = splitTimeStamp[0].replaceAll("[\\s\\-()]", "");
    System.out.println(splitTimeStamp[0]);


    php - Why do I get a SQL error when preparing a statement in mysqli?




    I have the following query:



    INSERT INTO ipi_messages (Message_userID, Message_fromName, Message_fromEmail, Message_subject, Message_body) VALUES(0, 'hope', 'thisworks@gmail.com', 'i hope', 'this works')


    And I get the following MySQL error:



    You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '0' at line 1



    Here's my table schema:



    enter image description here



    Here is my main PHP code:



        require 'lib/class.Database.php';
    require 'lib/class.Messages.php';


    $messageDatabase = new Database('ipi2');
    $messageDatabase->newDatabaseUsers([
    ['Query','ipi_query','k2QvHmtxGhVN'],
    ['admin','ipi_admin','r0HHRsQ76kS2']
    ]);
    $messageDatabase->makeConnection('admin');

    var_dump($_POST);

    if(array_key_exists('sendMessage', $_POST)){

    // $query = "INSERT INTO ipi_messages (Message_userID, Message_fromName, Message_fromEmail, Message_subject, Message_body) VALUES(?,?,?,?,?)";
    // $result = $messageDatabase->query($query, $_POST['to'], $_POST['fromName'], $_POST['fromEmail'], $_POST['subject'], $_POST['message']);

    $messages = new Messages($messageDatabase);
    $messages->postMessage([
    'Message_userID' => (int)$_POST['to'],
    'Message_fromName' => $_POST['fromName'],
    'Message_fromEmail' => $_POST['fromEmail'],
    'Message_subject' => $_POST['subject'],
    'Message_body' => $_POST['message']

    ]);
    }

    if(array_key_exists('getMessages', $_POST)){
    $query_get = "SELECT * FROM ipi_messages WHERE Message_userID = ?";
    $result_get = $messageDatabase->query($query_get, $_POST['user']);
    }
    ?>





    Messages



    Send Message



    To:




    Name:


    Email:



    Subject:


    Message:







    Your Messages:






    if (isset($result_get)) {
    foreach ($result_get as $result) {

    ?>








    }
    }

    ?>





    class.Messages.php:



    require_once 'lib/classFunctions.php';


    class Messages
    {
    protected $database;
    protected $userID = -1;

    public function __construct(Database $messageDatabase) {
    $this->database = $messageDatabase;
    }


    public function getMessages($userID = null){

    }

    public function postMessage(Array $columnsValues){
    // $query = "INSERT INTO ipi_messages (Message_userID, Message_fromName, Message_fromEmail, Message_subject, Message_body) VALUES(?,?,?,?,?)";

    $columns = '';
    $values = '';
    $queryParams = array();


    foreach ($columnsValues as $column => $value) {
    $columns .= "$column, ";
    $values .= is_int($value) ? "$value, " : "'$value', ";
    $queryParams[] = $value;
    }

    $columns = substr($columns, 0, strlen($columns) - 2);
    $values = substr($values, 0, strlen($values) - 2);


    $query = "INSERT INTO ipi_messages ($columns) VALUES($values)";

    // array_unshift($queryParams, $query);

    // $result = $messageDatabase->query($query, $_POST['to'], $_POST['fromName'], $_POST['fromEmail'], $_POST['subject'], $_POST['message']);
    echo $query . '
    ';
    return $result = call_user_func_array(array($this->database,'query'), refValues($queryParams));
    }

    public function deleteMessage(){}

    }


    class.Database.php:



    require_once 'lib/classFunctions.php';

    class Database
    {

    protected $DATABASE = 'database';
    protected $SERVER = 'localhost';
    protected $DATABASEUSERS;
    protected $CONNECTION;


    public function __construct($database, $server = 'localhost'){
    $this->DATABASE = $database;
    $this->SERVER = $server;
    }


    public function makeConnection($userType){
    $user = $this->DATABASEUSERS[strtolower($userType)];
    $this->CONNECTION = new mysqli($this->SERVER, $user->getUsername(), $user->getPassword(), $this->DATABASE) or die('Cannot make connection to database...');
    }

    public function escapeSpecialChars($string){
    return $this->CONNECTION->real_escape_string($string);
    }


    public function newDatabaseUser($userType, $username, $password){
    $userType = strtolower($userType);
    $this->DATABASEUSERS[$userType] = new DatabaseUser($userType, $username, $password);
    }

    public function newDatabaseUsers($usersCollection){
    foreach ($usersCollection as $user) {
    $userType = strtolower($user[0]);
    $username = $user[1];
    $password = $user[2];


    $this->DATABASEUSERS[$userType] = new DatabaseUser($userType, $username, $password);
    }
    }

    public function closeConnection(){
    if($this->CONNECTION)
    $this->CONNECTION->close();
    else
    throw new Exception("No connection available.", 1);

    }

    public function query($query, $vars = null){
    $stmt = $this->CONNECTION->stmt_init();

    $args = func_get_args();
    if($stmt->prepare($query)){

    if($vars != null){
    $queryParams = array();

    $queryTypes = '';
    $argsCount = count($args);

    for( $i = 1 ; $i < $argsCount ; $i++ ){
    $var = $args[$i];
    $varType = gettype($var);
    switch ($varType) {
    case 'string':
    $queryTypes .= 's';
    break;

    case 'integer':
    $queryTypes .= 'i';
    break;
    case 'double':
    $queryTypes .= 'd';
    break;
    case 'blob':
    $queryTypes .= 'b';
    break;


    default:
    throw new Exception("Could not bind parameter of type: " . $varType, 1);
    break;
    }
    }
    $queryParams[] = $queryTypes;

    for( $i = 1 ; $i < $argsCount ; $i++ )
    $queryParams[] = $args[$i];


    // $stmt->bind_param($queryParams);
    call_user_func_array(array($stmt,'bind_param'), refValues($queryParams));
    }

    $isExecuted = $stmt->execute();
    if($isExecuted)
    return $result = $stmt->get_result();
    else
    die("Could not execute query($query):" . $this->CONNECTION->error);


    }else{
    die("Could not prepare statement: " . $this->CONNECTION->error);
    }

    $stmt->reset();
    }
    }

    class DatabaseUser
    {

    protected $USERTYPE = 'query';
    protected $USERNAME = 'username';
    protected $PASSWORD = 'password';

    public function __construct($userType, $username, $password) {
    $this->USERTYPE = $userType;
    $this->USERNAME = $username;
    $this->PASSWORD = $password;
    }


    public function getUserType(){ return $this->USERTYPE; }
    public function getUsername(){ return $this->USERNAME; }
    public function getPassword(){ return $this->PASSWORD; }
    }


    classFunctions.php:



    function refValues($arr){

    if (strnatcmp(phpversion(),'5.3') >= 0) //Reference is required for PHP 5.3+
    {
    $refs = array();
    foreach($arr as $key => $value)
    $refs[$key] = &$arr[$key];
    return $refs;
    }
    return $arr;
    }



    EDIT: I have added the PHP classes and scripts I am using along with updated my SQL query to make the 0 an int instead of a string.



    Why am I getting a SQL error when I prepare my mysqli statement? I tried taking just the SQL query and running it on the database, and the row inserted just fine.


    Answer



    I finally figured out what I was doing wrong. I was getting that error because I was placing the actual values into the VALUES() portion of my sql. This way, when my bind_param method was trying to bind values, it didn't have the ? markers to bind to, rather, it saw the actual values.



    My new class.Messages.php looks like:




    require_once 'lib/classFunctions.php';

    class Messages
    {
    protected $database;
    protected $userID = -1;

    public function __construct(Database $messageDatabase) {
    $this->database = $messageDatabase;
    }


    public function getMessages($userID = null){

    }

    public function postMessage(Array $columnsValues){
    $columns = '';
    $values = '';
    $queryParams = array();


    foreach ($columnsValues as $column => $value) {
    $columns .= "$column, ";
    $values .= "?, ";
    $queryParams[] = $value;
    }

    $columns = substr($columns, 0, strlen($columns) - 2);
    $values = substr($values, 0, strlen($values) - 2);

    $query = "INSERT INTO ipi_messages ($columns) VALUES($values)";


    array_unshift($queryParams, $query);

    return $result = call_user_func_array(array($this->database,'query'), refValues($queryParams));
    }

    public function deleteMessage(){}
    }



    Thanks everyone for your help!


    c++ - Does curly brackets matter for empty constructor?

    Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...