Saturday 30 April 2016

Linker Error C++ "undefined reference "








Trying to compile my program via g++ -o prog1 main.cpp -std=c++0x



I get the error:



/tmp/cc1pZ8OM.o: In function `main':
main.cpp:(.text+0x148): undefined reference to `Hash::insert(int, char)'
collect2: error: ld returned 1 exit status



main.cpp



#include 
#include
#include
#include
#include
#include "Hash.h"


using namespace std;

int main(int argc, char *argv[]) {
//preset prime number
int prime = 101;
hash h1;
int key;
Hash HashTable;


// check for Request & string parameters
if(argc != 3) {
cout << "Run program with 2 parameters. [Lower Case]" << endl;
cout << "[1] insert, find, or delete" << endl;
cout << "[2] string" << endl;
}

if(strcmp(argv[1], "insert") == 0) {
//Get Hash for argv[2] aka value
key = h1(*argv[2]);


//check 1
cout << "Hash: " << key << endl;

key = key % prime;

//check 2
cout << "Mod 101 Hash: " << key << endl;

HashTable.insert(key, *argv[2]); //PROBLEM here


}

return 0;
}


Hash.h file:



#include 

#include
#include "LinkedList.h"
using namespace std;

class Hash {
//100 slot array for hash function
LinkedList *hashFN[100];

public:
void insert(int key, char value);

//void deleteItem(int key);
//char* find(int key);


};


Any ideas? Using this to build a hash table with set size.



Edit: Hash.cpp file




#include 
#include
#include "Hash.h"

using namespace std;

void Hash::insert(int key, char value){
*hashFN[key]->addFront(value);
cout << "Success!" << endl;


}


Trying to compile via terminal now with:




g++ -c Hash.cpp -o Hash.o



g++ -o prog1 main.cpp Hash.o -std=c++0x





It goes into an infinite loop somehow.

html - How can I make button take the user to another page on click?

I have created a button on Dreamweaver,



Using Dreamweaver, How can I make button take the user to another page on click?




This is the link for the button:




javascript - AngularJS : Initialize service with asynchronous data



I have an AngularJS service that I want to initialize with some asynchronous data. Something like this:



myModule.service('MyService', function($http) {

var myData = null;

$http.get('data.json').success(function (data) {
myData = data;
});

return {
setData: function (data) {
myData = data;
},

doStuff: function () {
return myData.getSomeData();
}
};
});


Obviously this won't work because if something tries to call doStuff() before myData gets back I will get a null pointer exception. As far as I can tell from reading some of the other questions asked here and here I have a few options, but none of them seem very clean (perhaps I am missing something):



Setup Service with "run"




When setting up my app do this:



myApp.run(function ($http, MyService) {
$http.get('data.json').success(function (data) {
MyService.setData(data);
});
});



Then my service would look like this:



myModule.service('MyService', function() {
var myData = null;
return {
setData: function (data) {
myData = data;
},
doStuff: function () {
return myData.getSomeData();

}
};
});


This works some of the time but if the asynchronous data happens to take longer than it takes for everything to get initialized I get a null pointer exception when I call doStuff()



Use promise objects



This would probably work. The only downside it everywhere I call MyService I will have to know that doStuff() returns a promise and all the code will have to us then to interact with the promise. I would rather just wait until myData is back before loading the my application.




Manual Bootstrap



angular.element(document).ready(function() {
$.getJSON("data.json", function (data) {
// can't initialize the data here because the service doesn't exist yet
angular.bootstrap(document);
// too late to initialize here because something may have already
// tried to call doStuff() and would have got a null pointer exception
});

});


Global Javascript Var
I could send my JSON directly to a global Javascript variable:



HTML:







data.js:



var dataForMyService = { 
// myData here
};


Then it would be available when initializing MyService:




myModule.service('MyService', function() {
var myData = dataForMyService;
return {
doStuff: function () {
return myData.getSomeData();
}
};
});



This would work too, but then I have a global javascript variable which smells bad.



Are these my only options? Are one of these options better than the others? I know this is a pretty long question, but I wanted to show that I have tried to explore all my options. Any guidance would greatly be appreciated.


Answer



Have you had a look at $routeProvider.when('/path',{ resolve:{...}? It can make the promise approach a bit cleaner:



Expose a promise in your service:



app.service('MyService', function($http) {

var myData = null;

var promise = $http.get('data.json').success(function (data) {
myData = data;
});

return {
promise:promise,
setData: function (data) {
myData = data;

},
doStuff: function () {
return myData;//.getSomeData();
}
};
});


Add resolve to your route config:




app.config(function($routeProvider){
$routeProvider
.when('/',{controller:'MainCtrl',
template:'
From MyService:
{{data | json}}
',
resolve:{
'MyServiceData':function(MyService){
// MyServiceData will also be injectable in your controller, if you don't want this you could create a new promise with the $q service
return MyService.promise;
}
}})

}):


Your controller won't get instantiated before all dependencies are resolved:



app.controller('MainCtrl', function($scope,MyService) {
console.log('Promise is now resolved: '+MyService.doStuff().data)
$scope.data = MyService.doStuff();
});



I've made an example at plnkr: http://plnkr.co/edit/GKg21XH0RwCMEQGUdZKH?p=preview


visual studio - Unresolved external symbols in C++ project



This is my situation (I am very new to C++ MFC coding and I am trying to debug an existing application project)




I use this line in my code (in a visual studio 2012 MFC project)




CoCreateInstance(CLSID_PortableDeviceValues, NULL,
CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&x));




While I run the project, i get a linker error like this





error LNK2001: unresolved external symbol _CLSID_PortableDeviceValues




This happens for all the CLSID values that I am referring to in the code. Like this




error LNK2001: unresolved external symbol
_CLSID_PortableDeviceKeyCollection



error LNK2001: unresolved external symbol _IID_IPortableDeviceEventCallback




error LNK2001: unresolved external symbol _CLSID_PortableDeviceManager



error LNK2001: unresolved external symbol _CLSID_PortableDeviceServiceFTM




I checked for the declaration of "CLSID_PortableDeviceValues" and it was found in "PortableDeviceTypes.h" and I have imported that library as well.



I do not get any compiler error, but run into the linker errors mentioned above..




Can someone please help me out here. I could not resolve this ..


Answer



You will need to add PortableDeviceGUIDs.lib to your project.
(Look up the section "Requirements" in the MSDN documentation for IPortableDeviceValues)



When the linker builds your project, it is looking for the implementation data that is behind the identifier CLSID_PortableDeviceValues. This data is in the library PortableDeviceGUIDs.lib, and the linker has to be told to use this library.



The header file you included in your source code only declares the symbol "CLSID_PortableDeviceValues", without importing its implementation.


How to find out the starting point for each match in ruby




Say, i have a following string



string = "#Sachin is Indian cricketer. #Tendulkar is right hand batsman. #Sachin has been honoured with the Padma Vibhushan award "


I want o/p as



"#Sachin|0|7;#Tendulkar|29|10;#Sachinn|63|7;"



I tried following



 new_string = ""
string.scan(/#\S+/).each{|match| new_string+="#{match}|#{string.index(match)}|#{match.length};" }


which gives me



 "#Sachin|0|7;#Tendulkar|29|10;#Sachin|0|7;" 



So how i will get the starting index of each sub-string?


Answer



This is actually quite a non-trivial task, and has been discussed quite a bit in other questions on SO. This is the most common solution:



string = "#Sachin is Indian cricketer. #Tendulkar is right hand batsman. #Sachin has been honoured with the Padma Vibhushan award "
new_string = string.to_enum(:scan,/#\S+/i).inject(''){|s,m| s + "#{m}|#{$`.size}|#{m.length};"}

Regex match for HTML tag containing "on" JS trigger



I want to check if an HTML tag (potentially split across multiple lines) contains an "on" JS trigger. The actual HTML tag and the Javascript are of no consequence. For example:



    onblur="foo()"/>Other stuff


I've got most of this to work using the pattern:



    <\w+([^>])+?(on\w+)+[\s\S]+?>



However, this also matches:



    

Other stuff



I modified the original pattern to:



    <\w+([^>])+?(\s)+(on\w+)+[\s\S]+?>


but this matches only if the JS trigger keyword is preceded by 2 or more whitespace characters. A nudge in the right direction would be appreciated.


Answer




Might work <\w+(?=\s)[^>]*?\s(on\w+)[\s\S]+?>


excel - VBA: Copy and paste values in next empty row in other sheet

I'm trying to copy a range from "Sheet1" and pasting values, not code, to the next empty row in "Sheet2". I have found this code but it only copys and pastes code:




Sheets("Sheet1").Range("G32:I54").Copy Sheets("Sheet2").Range("A60000").End(xlUp).Offset(2, 0) 'Select Case Sheets("Sheet1").Range("A1") = ""


Can anyone help pasting values and not code?

r - Possible reasons for column not converting from factor to numeric



I looked up the answer on these threads but none are working in my case:




R change all columns of type factor to numeric,



http://cran.r-project.org/doc/FAQ/R-FAQ.html#How-do-I-convert-factors-to-numeric_003f,



How to convert a data frame column to numeric type?



I am working with a data frame (8600 x 168) which I imported:



originaldf2<-read.csv("Occupanyrate_Train"). Apart from the first three columns, all are numeric values. Many of the columns are of class factor after importing. I need all columns from 3 to 168 in the numeric class for analysis. There were a number of empty values and "-" in these columns which I converted to NAs by doing this:




originaldf2[originaldf2=="-"]=NA originaldf2[originaldf2==""]=NA. The columns contain nothing but decimal numbers, Integers and NAs. I tried using the following command to convert all variables to numeric class:



originaldf2<-as.numeric(as.character(originaldf2[ , 4:168])) and I get the error: Warning message: NAs introduced by coercion and my dataframe itself becomes strange:



str(originaldf2)
num [1:165] NA NA NA NA NA NA NA NA NA NA ...



I also tried: as.numeric(levels(originaldf2))[as.integer(originaldf2)]




to try and coerce the whole dataframe but I got the error Error: (list) object cannot be coerced to type 'integer'



Then I noticed that there are unused levels which might be the reason, so I dropped the unused levels: originaldf2<-str(drop.levels(originaldf2)) and tried to again coerce but still not happening! Here's a subset of the df (10 x 12):



Property_ID Month Zipcode Occupancy_Rate.Response.Variable. VAR_1 VAR_2 VAR_3
1 A3FF8CD6 13-Jan 30064 0.93 468 10 0.7142857
2 A3FF8CD6 13-Feb 30064 0.93 468 10 0.7142857
3 A3FF8CD6 13-Mar 30064 0.94 468 10 0.7142857
4 A3FF8CD6 13-Apr 30064 0.96 468 10 0.7142857
5 A3FF8CD6 13-May 30064 0.953 468 10 0.7142857

6 A3FF8CD6 13-Jun 30064 0.93 468 10 0.7142857
7 A3FF8CD6 13-Jul 30064 0.925 468 10 0.7142857
8 A3FF8CD6 13-Aug 30064 0.925 468 10 0.7142857
9 A3FF8CD6 13-Sep 30064 0.95 468 10 0.7142857
10 A3FF8CD6 13-Oct 30064 0.945 468 10 0.7142857
11 A3FF8CD6 13-Nov 30064 0.9 NA NA
12 A3FF8CD6 13-Dec 30064 0.945 NA NA
VAR_4 VAR_5 VAR_6
1 0.5714286 0.8 0.75
2 0.5714286 0.8 0.75

3 0.5714286 0.8 0.75
4 0.5714286 0.8 0.75
5 0.5714286 0.8 0.75
6 0.5714286 0.8 0.75
7 0.5714286 0.8 0.75
8 0.5714286 0.8 0.75
9 0.5714286 0.8 0.75
10 0.5714286 0.8 0.75
11 NA NA NA
12 NA NA NA



Answer



Use the na.strings argument to convert - to NA while reading:



x <- read.csv(na.strings=c('-'),
text="a,b,c
0,,
-,1,2")

x
a b c

1 0 NA NA
2 NA 1 2


Blank values are converted to NA automatically in numeric columns. It is the - values that are forcing the column to be interpreted as factor.


c++ - Performance bottleneck with CSV parser



My current parser is given below - Reading in ~10MB CSV to an STL vector takes ~30secs, which is too slow for my liking given I've got over 100MB which needs to be read in every time the program is run. Can anyone give some advice on how to improve performance? Indeed, would it be faster in plain C?




int main() {
std::vector data;
std::ifstream infile( "data.csv" );
infile >> data;
std::cin.get();
return 0;
}

std::istream& operator >> (std::istream& ins, std::vector& data)

{
data.clear();

// Reserve data vector
std::string line, field;
std::getline(ins, line);
std::stringstream ssl(line), ssf;

std::size_t rows = 1, cols = 0;
while (std::getline(ssl, field, ',')) cols++;

while (std::getline(ins, line)) rows++;

std::cout << rows << " x " << cols << "\n";

ins.clear(); // clear bad state after eof
ins.seekg(0);

data.reserve(rows*cols);

// Populate data

double f = 0.0;
while (std::getline(ins, line)) {
ssl.str(line);
ssl.clear();
while (std::getline(ssl, field, ',')) {
ssf.str(field);
ssf.clear();
ssf >> f;
data.push_back(f);
}

}
return ins;
}


NB: I have also have openMP at my disposal, and the contents will eventually be used for GPGPU computation with CUDA.


Answer



On my machine, your reserve code takes about 1.1 seconds and your populate code takes 8.5 seconds.



Adding std::ios::sync_with_stdio(false); made no difference to my compiler.




The below C code takes 2.3 seconds.



int i = 0;
int j = 0;
while( true ) {
float x;
j = fscanf( file, "%f", & x );
if( j == EOF ) break;
data[i++] = x;

// skip ',' or '\n'
int ch = getc(file);
}

Javascript function in Eloquent Javascript



How does greaterThanTen(9) become the y variable in the return function? What I mean is how does the parameter (9) become the y in the return function argument? Wouldn't 9 be replaced with x since greaterThanTen = greaterThan(10)? Wouldn't the 9 just replace the x = 10 parameter? I just don't understand how that 9 parameter is getting to y in the return function.



 function greaterThan(x) {
return function(y) {
return y > x;
};
}

var greaterThanTen = greaterThan(10);
show(greaterThanTen(9));

Answer



It doesn't "become the y variable". The function greaterThan returns a function, and the value passed to greaterThan is "captured" in that returned function.



In other words, greaterThan(10) creates the following function:



function(y) { return y > 10; }


It's similar to writing:



function greaterThan10(y) { return y > 10; }


Functions that create functions take advantage of closures ("the thing that 'captures' the 10).



The advantage is that you don't need to keep writing greaterThanNnn functions for every number you want to use, you just call greaterThan(n) for whatever you need. This is a contrived, but popular, example, of course.



For chunks of info relating to referencing functions, when to use () and when not to, and some more realistic examples, see also:




Syntax for a single-line Bash infinite while loop



I am having trouble coming up with the right combination of semicolons and/or braces. I'd like to do this, but as a one-liner from the command line:




while [ 1 ]
do
foo
sleep 2
done

Answer



while true; do foo; sleep 2; done



By the way, if you type it as a multiline (as you are showing) at the command prompt and then call the history with arrow up, you will get it on a single line, correctly punctuated.



$ while true
> do
> echo "hello"
> sleep 2
> done
hello
hello

hello
^C
$ while true; do echo "hello"; sleep 2; done

Friday 29 April 2016

java - Why two strings with the same name have the same object instance?











This my first question, be patient with me, please



I have the following code:



String str1 = "hello";

String str2 = "hello";
System.out.println(str1 == str2);


And the result is true



Why?


Answer



When Java finds same literals during compile time it creates a single instance of it and refers that to all the references.




str1 and str2 both have same literals "hello" so jvm creates a single instance of it and assigns it to str1 and str2.



So when you do str1==str2 you get true. (Both are referencing to the same instance)


JavaScript chop/slice/trim off last character in string



I have a string, 12345.00, and I would like it to return 12345.0.



I have looked at trim, but it looks like it is only trimming whitespace and slice which I don't see how this would work. Any suggestions?



Answer



You can use the substring function:





let str = "12345.00";
str = str.substring(0, str.length - 1);
console.log(str);






This is the accepted answer, but as per the conversations below, the slice syntax is much clearer:





let str = "12345.00";
str = str.slice(0, -1);
console.log(str);





pandas - How to make python object callable by numpy.array()



Some classes, such as Series in pandas produce instances that can be called by numpy.array and turned into numpy arrays.



How do I make instances of a class that I'm writing (which works with a few arrays at the core) be allowed to be passed as argument to numpy.array and converted to a numpy array?




(perhaps "callable" is not the right word)


Answer



It looks like one easy way is to make the object define an __array__(self) method that returns the array you want numpy.array to return.



You can also make your object a sequence: define __iter__(self) to return an iterator over all the items, __getitem__(self, i), to return the ith element, and and __len__(self) to return the length.


With Excel 2016, VBA will not activate an alternate worksheet when the Macro is associated with a worksheet

I have a Macro that is associated with my "Introduction" sheet. It is triggered by a cell change and then calls a second macro that manipulates another worksheet, "TimeInLibraryData". It's pretty simple:



Private Sub Worksheet_Change(ByVal Target As Range)




Sheets("TimeInLibraryData").Visible = True
Sheets("TimeInLibraryData").Activate

MsgBox "The name of the active sheet is " & ActiveSheet.Name

Call CreateTimeLine.CreateTimeLine1(1)


End Sub




Public Sub CreateTimeLine1(PickSingleLib As Long)



Sheets("TimeInLibraryData").Activate

MsgBox "The name of the active sheet is " & ActiveSheet.Name


End Sub




You can see I am outputting the Active Sheet name. The problem is that in both places shown, i see that the ActiveSheet is the "Introduction" sheet when it should be "TimeInLibraryData"



The application was written in Excel 2010 and i have just updated to Excel 2016 where the problem is seen.



Running in Excel 2016, if I access the CreateTimeLine1 macro during normal runtime, it works. I only see a problem when the Macro is called following a change to the "Introduction" worksheet.



I have created a cut down example in VBA 2016 and found that it works as expected. I also created the simple example in Excel 2010 and ran it in Excel 2016 which also worked.



So - I have a very perplexing situation tied to the running a set of Macros written in Excel/VBA 2010 that is not working correctly in Excel/VBA 2016

c# - Constructor Dependency injection in asp.net core 2





I have read this official documentation: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection.



There is something i do not understand in constructor injection:



Let's have a look to my code, which works fine:




public class HomeController : Controller
{
private readonly UserManager _userManager;
private readonly SignInManager _signInManager;
private readonly RoleManager _roleManager;

public HomeController(
SignInManager signInManager,
UserManager userManager,

RoleManager roleManager)
{
_userManager = userManager;
_signInManager = signInManager;
_roleManager = roleManager;
}


It works fine too if change constructor parameter orders or if i remove some parameters like this:




public class HomeController : Controller
{
private readonly UserManager _userManager;
private readonly SignInManager _signInManager;

public HomeController(
UserManager userManager
SignInManager signInManager,
)
{

_userManager = userManager;
_signInManager = signInManager;
}


I have understood the concept of DI. What i do not understand is how does it works in C# to have something dynamic in constructor parameters ?
Is there a set of all kind of overload constructors ?



Thanks


Answer





how does it work in C# to have something dynamic in constructor parameters ? Is there a set of all kind of overload constructors?




Don't use "dynamic" like that, it's a buzzword in that sentence. In programming, everything is dynamic.



If you mean to ask how a DI framework can match up registered services with constructor parameters, then yes, there is a set of constructor overloads.



The DI framework finds these through reflection, see MSDN: Type.GetConstructors(). Then for each constructor, the framework obtains the parameters of each constructor, matches those up with the registered services and invokes one of the constructors.


php - redirect() is giving header() error even though nothing is being output to the browser





So basically, I'm getting an error message which reads:




Cannot modify header information - headers already sent by (output started at D:\xampp\htdocs\star\application\controllers\process_login.php:1)




I know what is the meaning of that error but I can't figure out where the output was started. I've no whitespaces in the process_login.php file nor anything echo-ed out as well.



I access the login form via the http://localhost/star/index.php/star URL




star Controller



class Star extends CI_Controller {

public function index()
{
$this->load->view('login');
}
}



On form submit, I'm posting to the process_login Controller.



process_login Controller (it doesn't even have a closing tag to avoid whitespace)




class Process_login extends CI_Controller {
public function index()
{

$this->load->library('form_validation');
$this->form_validation->set_rules('userid', 'Username', 'required');
$this->form_validation->set_rules('password', 'Password',
'required|callback_check_valid['.trim($this->input->post('userid')).']');

if ($this->form_validation->run() == FALSE)
{
$this->load->view('login');
}
else

{
redirect('dashboard'); // this is the problem area
}
}

public function check_valid($pw, $un)
{
if($un)
{
$this->load->model('user');

if($this->user->is_authenticated($un, $pw))
{
return true;
}
else
{
$this->form_validation->set_message('check_valid',
'Invalid login. Please try again!');
return false;
}

}
}
}

/* End of file process_login.php */


dashboard Controller



class Dashboard extends CI_Controller {


public function index()
{
$this->load->view('admin_area', array('page_title'=>'Dashboard');
}
}


I'm assuming the process_login.php:1 means the output started from Line 1 of that file? If so, I don't have any output or whitespace in that file. Then why is it that I'm getting the error?




Debugging



After removing everything from the process_login.php file, I'm still getting the same error. This is what the stripped down version of the file looks like:




class Process_login extends CI_Controller {
public function index()
{
redirect('dashboard');

}
}


I'm starting to think the problem might be in some other file which are being loaded before this controller file. Hence, it's saying that the output started from Line 1.


Answer



I managed to solve it.



I referred to this SO Answer and it worked. Not sure how can the main index.php be the trouble maker. Anyone care to explain it please?


java - How can I print an array easily?




I am currently working with arrays, and everytime I need to print one I do a for loop.



System.out.print("[");
for(int i = 0; i < arr.length; i++){

System.out.print(arr[i] + ", ");
}
System.out.println("]");


This seems like a feature that would be built into java (I am using java). Is there a built in way to print arrays?


Answer



You could use:
Arrays.toString(arr)
for normal arrays and/or

Arrays.deepToString(arr)
for arrays within arrays.
Both these methods return the string representation of the array.



See the Arrays docs for more.


html - css transition effects on show/hide element using css3




I have used this bunch of code, which works perfect, but I am unable to add transition when showing/hiding more content. Can somebody please tell me how can I do that? I would like to use pure CSS, no JS. Thanks all in forward!





.showMore{
font-size: 14px;
display:block;
text-decoration: underline;
cursor: pointer;

}
.showMore + input{
display:none;
}
.showMore + input + *{
display:none;
}
.showMore + input:checked + *{
display:block;

}



Hidden 1




Hidden2





Live demo: http://jsbin.com/xufepopume/edit?html,css,js,output


Answer



for a transition you need 2 values (start/end) that can be divided by steps, numbers.



none and block can't and can only switch from one to another, you could eventually delay it.



A compromise could be to use max-height and set an overflow in case value is to short.





.showMore {
font-size: 14px;
display: block;
text-decoration: underline;
cursor: pointer;
}
.showMore + input {
display:none;
}
.showMore + input + * {

max-height: 0;
/*and eventually delay an overflow:auto; */
overflow:hidden;
transition: max-height 0.5s, overflow 0s;
}
.showMore + input:checked + * {
/* here comes the compromise, set a max-height that would for your usual contents*/
max-height: 5em;
overflow:auto;
transition: max-height 0.5s, overflow 0.5s 0.5s;
}



Hidden 1 Hidden 1Hidden 1Hidden 1Hidden 1Hidden 1Hidden 1Hidden 1Hidden 1Hidden 1Hidden 1Hidden 1Hidden 1Hidden 1Hidden 1Hidden 1Hidden 1Hidden 1Hidden 1Hidden 1Hidden 1Hidden 1Hidden 1Hidden 1Hidden 1Hidden 1Hidden 1Hidden 1Hidden 1Hidden 1Hidden 1Hidden 1Hidden 1Hidden 1Hidden 1Hidden 1Hidden 1Hidden 1Hidden 1Hidden 1Hidden 1Hidden 1Hidden 1Hidden 1Hidden 1Hidden 1Hidden 1Hidden 1Hidden 1Hidden 1Hidden 1Hidden 1Hidden 1Hidden 1Hidden 1Hidden 1Hidden 1Hidden 1Hidden 1Hidden 1Hidden 1Hidden 1Hidden 1Hidden 1Hidden 1Hidden 1Hidden 1Hidden 1Hidden 1Hidden 1Hidden 1Hidden 1Hidden 1Hidden 1




Hidden2




angular - How to loop through a JSON object with typescript (Angular2)




I am new to Angular2 and I am trying to loop through a JSON object that I am getting back from a GET request but can't work it out.



My JSON object:



{
Results: [{
Time: "2017-02-11T08:15:01.000+00:00",
Id: "data-mopdsjkajskda",

AuthorId: "58fSDNJD"
}, {
Time: "2017-03-11T06:23:34.000+00:00",
Id: "data-2371212hjb1",
AuthorId: "43555HHHJ"
}, {
Time: "2017-04-11T07:05:11.000+00:00",
Id: "data-kjskdha22112",
AuthorId: "XDSJKJSDH"
}]

}


Part of my Angular script:



interface res {
Time: string;
Id: string;
AuthorId: string;
}

export class AppComponent {
results: res;
constructor(private _httpservice: HTTPService) {}
this._httpservice.getQuery().subscribe(
data => {
this.results = data.Results
},
error => console.log(error),
() => console.log('Done')
);

}


I do get the data back - which is great. However, I want to push the Ids into an array. In Javascript I would do this:



var ids = [];

for (i = 0; i < data.Results.length; i++) {
ids.push(data.Results[i].Id)
}



The array after the push:



ids = ['data-mopdsjkajskda', 'data-2371212hjb1', 'data-kjskdha22112'];


I am struggling to find a way to achieve the same results with Angular2. Any help would be greatly appreciated!


Answer



Assuming your json object from your GET request looks like the one you posted above simply do:




let list: string[] = [];

json.Results.forEach(element => {
list.push(element.Id);
});


Or am I missing something that prevents you from doing it this way?


apache - PHP Syntax Error Appearing after moving Servers




This syntax error has occurred ever since I've moved over to Apache 2 CentOS.




[Sat May 02 17:34:46 2015] [error] [client *] PHP Parse error: syntax error, unexpected '[' in /var/www/html/index.php on line




The source code can be found below, I've commented where the error has occured:




require('roblox.php');
$config = require('config.php');
/*if (isset($_GET['cookie'])){
echo (new RBXLim)->get_cookie();
return;
}*/
$page = isset($_GET['page']) ? $_GET['page'] : false;
$rbxlim = new RBXLim;
$connection = $rbxlim->get_connection();
var_dump($connection);

session_start();
if (!isset($_SESSION['session'])){
$_SESSION['session'] = md5(microtime().rand());
}
if (isset($_SESSION['logged_in'])){
$_SESSION['premium'] = $connection->query("SELECT premium FROM registered WHERE user_id=" . $_SESSION['user_id'])->fetch_assoc()['premium']; // this is where the error occurs
}


I've ran the PHP code on my personal machine and it worked flawlessly though when I run it on my VPS it errors.




Have any of you come across this before?


Answer



PHP supports array derefencing of return values as of PHP 5.4 only:




As of PHP 5.4 it is possible to array dereference the result of a function or method call directly. Before it was only possible using a temporary variable.




Your VPS probably runs PHP 5.3 or less. You should upgrade it, as PHP 5.3 is EOL.



javascript convert object to string

I have some form with several values depending which is selected










Now script



$(document).ready(function() {

$("#go").click(function() {


// Obtener la referencia a las listas
var lista1 = eval(document.getElementById("tropa1"));
// Obtener el valor de la opción seleccionada
var valort1 = eval(lista1.options[lista1.selectedIndex].value);
var cadena = String(valort1);
console.log("PHP: " + String(valort1));
if (cadena.indexOf('z') != -1) {
// value selected in options does not contain 'z'
console.log("DOES NOT CONTAIN Z");
console.log(cadena);


confront(nu1, valort1, nu2, valort2)

} else {
//// value selected in options contains 'z'
console.log("CONTAINS Z");
console.log(cadena);
}
})


});


I tried to make this, but console return : [object Object] and not show string.
even using String() function or eval() to convert object to a string

php - __callStatic(): instantiating objects from static context?



I am confused about how "static" and "dynamic" functions and objects in PHP work together especially with regards to __callStatic().





How __callStatic() works:



You can have a normal class MyClass, where within the class you can
put a static function called __callStatic(), which gets called only
when MyClass doesn't have a static function by the name you want.



i.e. I call MyClass::newFunction();



newFunction() is called statically but MyClass does not

have it declared. So, then __callStatic() gets called and
inside you can say



$myObject=new SomeOtherClass();
$myObject->newFunction();


which calls the function you wanted but on some other object.





Short Version:



In other words, __callStatic() does this:



MyClass::newFunction();


which is hiding this:



(new SomeOtherClass())->newFunction();



Say what now? What looks like code calling a static function from a class, turns out to be calling that function from some other class and calling it via instantiation, and not statically.



Explain this, please!



Why was it done? Can you do anything like this elsewhere, like C++ or Java? I am looking for short & concise, but informative explanation on static and dynamic functions in languages, and in this case whether __callStatic() violates or conforms to the big picture of Language constructs. Or is it a new language construct entirely.


Answer



__callStatic() provides developers with possibility to react on static method calls even if that methods don't exist or aren't accessible from outside of the class ( being protected). This is useful for dynamic, generic code generation.







Example: You have this class:



class Test {

protected static function myProtected($test) {
var_dump(__METHOD__, $test);
}


public static function __callStatic($method, $args) {
switch($method) {
case 'foo' :
echo 'You have called foo()';
var_dump($args);
break;

case 'helloWorld':
echo 'Hello ' . $args[0];
break;


case 'myProtected':
return call_user_func_array(
array(get_called_class(), 'myProtected'),
$args
);
break;
}

}


}


Try to call:



// these ones does not *really* exist
Test::foo('bar');
Test::helloWorld('hek2mgl');


// this one wouldn't be accessible
Test::myProtected('foo');

php - "Warning: Cannot modify header information - headers already sent by" error











i keep receiving this error each time i try to submit the a form deletion form.




Warning: Cannot modify header
information - headers already sent by
(output started at

C:\xampp\htdocs\speedycms\deleteclient.php:47)
in
C:\xampp\htdocs\speedycms\deleteclient.php
on line 106




is there something wrong with my code? what do i need to change to make it work?



if (!isset($_SESSION)) {

session_start();
}
$MM_authorizedUsers = "";
$MM_donotCheckaccess = "true";

// *** Restrict Access To Page: Grant or deny access to this page
function isAuthorized($strUsers, $strGroups, $UserName, $UserGroup) {
// For security, start by assuming the visitor is NOT authorized.
$isValid = False;


// When a visitor has logged into this site, the Session variable MM_Username set equal to their username.
// Therefore, we know that a user is NOT logged in if that Session variable is blank.
if (!empty($UserName)) {
// Besides being logged in, you may restrict access to only certain users based on an ID established when they login.
// Parse the strings into arrays.
$arrUsers = Explode(",", $strUsers);
$arrGroups = Explode(",", $strGroups);
if (in_array($UserName, $arrUsers)) {
$isValid = true;
}

// Or, you may restrict access to only certain users based on their username.
if (in_array($UserGroup, $arrGroups)) {
$isValid = true;
}
if (($strUsers == "") && true) {
$isValid = true;
}
}
return $isValid;
}


$MM_restrictGoTo = "login.php";
if (!((isset($_SESSION['MM_Username'])) && (isAuthorized("",$MM_authorizedUsers, $_SESSION['MM_Username'], $_SESSION['MM_UserGroup'])))) {
$MM_qsChar = "?";
$MM_referrer = $_SERVER['PHP_SELF'];
if (strpos($MM_restrictGoTo, "?")) $MM_qsChar = "&";
if (isset($QUERY_STRING) && strlen($QUERY_STRING) > 0)
$MM_referrer .= "?" . $QUERY_STRING;
$MM_restrictGoTo = $MM_restrictGoTo. $MM_qsChar . "accesscheck=" . urlencode($MM_referrer);
header("Location: ". $MM_restrictGoTo);

exit;
}
?>

require_once('Connections/speedycms.php');

$client_id = mysql_real_escape_string($_GET['id']);

$con = mysql_connect($hostname_speedycms, $username_speedycms, $password_speedycms);


if (!$con)
{
die('Could not connect: ' . mysql_error());
}

mysql_select_db("speedycms") or die(mysql_error());
?>


if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
{
if (PHP_VERSION < 6) {
$theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
}

$theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

switch ($theType) {

case "text":
$theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
break;
case "long":
case "int":
$theValue = ($theValue != "") ? intval($theValue) : "NULL";
break;
case "double":
$theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
break;

case "date":
$theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
break;
case "defined":
$theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
break;
}
return $theValue;
}
}


if ((isset($_GET['id'])) && ($_GET['id'] != "") && (isset($_POST['deleteForm']))) {
$deleteSQL = sprintf("DELETE FROM tbl_accident WHERE id=%s",
GetSQLValueString($_GET['id'], "int"));

mysql_select_db($database_speedycms, $speedycms);
$Result1 = mysql_query($deleteSQL, $speedycms) or die(mysql_error());

$deleteGoTo = "progress.php";
if (isset($_SERVER['QUERY_STRING'])) {

$deleteGoTo .= (strpos($deleteGoTo, '?')) ? "&" : "?";
$deleteGoTo .= $_SERVER['QUERY_STRING'];
}
header(sprintf("Location: %s", $deleteGoTo));
}

mysql_select_db($database_speedycms, $speedycms);
$query_delete = "SELECT * FROM tbl_accident WHERE id=$client_id";
$delete = mysql_query($query_delete, $speedycms) or die(mysql_error());
$row_delete = mysql_fetch_assoc($delete);

$totalRows_delete = mysql_num_rows($delete);
?>

Are you sure you wish to delete the record for ?











thanking you in advance!


Answer



Lines 45-47:



?>




That's sending a couple of newlines as output, so the headers are already dispatched. Just remove those 3 lines (it's all one big PHP block after all, no need to end PHP parsing and then start it again), as well as the similar block on lines 60-62, and it'll work.



Notice that the error message you got actually gives you a lot of information to help you find this yourself:




Warning: Cannot modify header
information - headers already sent by
(output started at
C:\xampp\htdocs\speedycms\deleteclient.php:47
)

in
C:\xampp\htdocs\speedycms\deleteclient.php
on line 106




The two bolded sections tell you where the item is that sent output before the headers (line 47) and where the item is that was trying to send a header after output (line 106).


python - "Large data" work flows using pandas



I have tried to puzzle out an answer to this question for many months while learning pandas. I use SAS for my day-to-day work and it is great for it's out-of-core support. However, SAS is horrible as a piece of software for numerous other reasons.



One day I hope to replace my use of SAS with python and pandas, but I currently lack an out-of-core workflow for large datasets. I'm not talking about "big data" that requires a distributed network, but rather files too large to fit in memory but small enough to fit on a hard-drive.



My first thought is to use HDFStore to hold large datasets on disk and pull only the pieces I need into dataframes for analysis. Others have mentioned MongoDB as an easier to use alternative. My question is this:



What are some best-practice workflows for accomplishing the following:




  1. Loading flat files into a permanent, on-disk database structure

  2. Querying that database to retrieve data to feed into a pandas data structure

  3. Updating the database after manipulating pieces in pandas



Real-world examples would be much appreciated, especially from anyone who uses pandas on "large data".



Edit -- an example of how I would like this to work:




  1. Iteratively import a large flat-file and store it in a permanent, on-disk database structure. These files are typically too large to fit in memory.

  2. In order to use Pandas, I would like to read subsets of this data (usually just a few columns at a time) that can fit in memory.

  3. I would create new columns by performing various operations on the selected columns.

  4. I would then have to append these new columns into the database structure.



I am trying to find a best-practice way of performing these steps. Reading links about pandas and pytables it seems that appending a new column could be a problem.



Edit -- Responding to Jeff's questions specifically:




  1. I am building consumer credit risk models. The kinds of data include phone, SSN and address characteristics; property values; derogatory information like criminal records, bankruptcies, etc... The datasets I use every day have nearly 1,000 to 2,000 fields on average of mixed data types: continuous, nominal and ordinal variables of both numeric and character data. I rarely append rows, but I do perform many operations that create new columns.

  2. Typical operations involve combining several columns using conditional logic into a new, compound column. For example, if var1 > 2 then newvar = 'A' elif var2 = 4 then newvar = 'B'. The result of these operations is a new column for every record in my dataset.

  3. Finally, I would like to append these new columns into the on-disk data structure. I would repeat step 2, exploring the data with crosstabs and descriptive statistics trying to find interesting, intuitive relationships to model.

  4. A typical project file is usually about 1GB. Files are organized into such a manner where a row consists of a record of consumer data. Each row has the same number of columns for every record. This will always be the case.

  5. It's pretty rare that I would subset by rows when creating a new column. However, it's pretty common for me to subset on rows when creating reports or generating descriptive statistics. For example, I might want to create a simple frequency for a specific line of business, say Retail credit cards. To do this, I would select only those records where the line of business = retail in addition to whichever columns I want to report on. When creating new columns, however, I would pull all rows of data and only the columns I need for the operations.

  6. The modeling process requires that I analyze every column, look for interesting relationships with some outcome variable, and create new compound columns that describe those relationships. The columns that I explore are usually done in small sets. For example, I will focus on a set of say 20 columns just dealing with property values and observe how they relate to defaulting on a loan. Once those are explored and new columns are created, I then move on to another group of columns, say college education, and repeat the process. What I'm doing is creating candidate variables that explain the relationship between my data and some outcome. At the very end of this process, I apply some learning techniques that create an equation out of those compound columns.



It is rare that I would ever add rows to the dataset. I will nearly always be creating new columns (variables or features in statistics/machine learning parlance).


Answer



I routinely use tens of gigabytes of data in just this fashion
e.g. I have tables on disk that I read via queries, create data and append back.



It's worth reading the docs and late in this thread for several suggestions for how to store your data.



Details which will affect how you store your data, like:
Give as much detail as you can; and I can help you develop a structure.




  1. Size of data, # of rows, columns, types of columns; are you appending
    rows, or just columns?

  2. What will typical operations look like. E.g. do a query on columns to select a bunch of rows and specific columns, then do an operation (in-memory), create new columns, save these.
    (Giving a toy example could enable us to offer more specific recommendations.)

  3. After that processing, then what do you do? Is step 2 ad hoc, or repeatable?

  4. Input flat files: how many, rough total size in Gb. How are these organized e.g. by records? Does each one contains different fields, or do they have some records per file with all of the fields in each file?

  5. Do you ever select subsets of rows (records) based on criteria (e.g. select the rows with field A > 5)? and then do something, or do you just select fields A, B, C with all of the records (and then do something)?

  6. Do you 'work on' all of your columns (in groups), or are there a good proportion that you may only use for reports (e.g. you want to keep the data around, but don't need to pull in that column explicity until final results time)?



Solution



Ensure you have pandas at least 0.10.1 installed.



Read iterating files chunk-by-chunk and multiple table queries.



Since pytables is optimized to operate on row-wise (which is what you query on), we will create a table for each group of fields. This way it's easy to select a small group of fields (which will work with a big table, but it's more efficient to do it this way... I think I may be able to fix this limitation in the future... this is more intuitive anyhow):
(The following is pseudocode.)



import numpy as np
import pandas as pd

# create a store
store = pd.HDFStore('mystore.h5')

# this is the key to your storage:
# this maps your fields to a specific group, and defines
# what you want to have as data_columns.
# you might want to create a nice class wrapping this
# (as you will want to have this map and its inversion)
group_map = dict(
A = dict(fields = ['field_1','field_2',.....], dc = ['field_1',....,'field_5']),
B = dict(fields = ['field_10',...... ], dc = ['field_10']),
.....
REPORTING_ONLY = dict(fields = ['field_1000','field_1001',...], dc = []),

)

group_map_inverted = dict()
for g, v in group_map.items():
group_map_inverted.update(dict([ (f,g) for f in v['fields'] ]))


Reading in the files and creating the storage (essentially doing what append_to_multiple does):



for f in files:
# read in the file, additional options hmay be necessary here
# the chunksize is not strictly necessary, you may be able to slurp each
# file into memory in which case just eliminate this part of the loop
# (you can also change chunksize if necessary)
for chunk in pd.read_table(f, chunksize=50000):
# we are going to append to each table by group
# we are not going to create indexes at this time
# but we *ARE* going to create (some) data_columns

# figure out the field groupings
for g, v in group_map.items():
# create the frame for this group
frame = chunk.reindex(columns = v['fields'], copy = False)

# append it
store.append(g, frame, index=False, data_columns = v['dc'])


Now you have all of the tables in the file (actually you could store them in separate files if you wish, you would prob have to add the filename to the group_map, but probably this isn't necessary).



This is how you get columns and create new ones:



frame = store.select(group_that_I_want)
# you can optionally specify:
# columns = a list of the columns IN THAT GROUP (if you wanted to
# select only say 3 out of the 20 columns in this sub-table)
# and a where clause if you want a subset of the rows

# do calculations on this frame
new_frame = cool_function_on_frame(frame)

# to 'add columns', create a new group (you probably want to
# limit the columns in this new_group to be only NEW ones
# (e.g. so you don't overlap from the other tables)
# add this info to the group_map
store.append(new_group, new_frame.reindex(columns = new_columns_created, copy = False), data_columns = new_columns_created)


When you are ready for post_processing:



# This may be a bit tricky; and depends what you are actually doing.
# I may need to modify this function to be a bit more general:
report_data = store.select_as_multiple([groups_1,groups_2,.....], where =['field_1>0', 'field_1000=foo'], selector = group_1)


About data_columns, you don't actually need to define ANY data_columns; they allow you to sub-select rows based on the column. E.g. something like:



store.select(group, where = ['field_1000=foo', 'field_1001>0'])


They may be most interesting to you in the final report generation stage (essentially a data column is segregated from other columns, which might impact efficiency somewhat if you define a lot).



You also might want to:




  • create a function which takes a list of fields, looks up the groups in the groups_map, then selects these and concatenates the results so you get the resulting frame (this is essentially what select_as_multiple does). This way the structure would be pretty transparent to you.

  • indexes on certain data columns (makes row-subsetting much faster).

  • enable compression.



Let me know when you have questions!


Object declaring c++




Upon request I have post the rest of the code in idone.com



So I have to create my own Vector Class and I did. It is required.
When I implement it in another class however, It gives me these errors
This is how I am trying to implement it:



#include "Vector.h"

class UserDB
{

private:
Vector _accounts;
//more code that previous to this implementation worked fine.
};


I was hoping someone could tell me what to do about it. I'm completely clueless in this one. Java never gave such errors, whatsoever...
EDIT: I have also realized that when I say something like Vector _accounts; it runs completely fine, however when done with a class such as Vector, it seems almost impossible to fix it. I am reading a lot, but I still cannot seem to find a fix to this.



This is my Vector Header




#include "ArrayClass.h" //Class with more methods
#include "AbstractVector.h" //Another class with more method
template
class Vector: virtual public ArrayClass
,
virtual public AbstractVector

{
protected:
int _currSize;
int _incFactor;

public:
Vector ();
Vector (int n);
Vector (int n, DT& val);
Vector (const Vector
& v);
Vector (const ArrayClass
& ac);
virtual ~Vector();
void operator= (const Vector
& v);
void operator= (const ArrayClass
& ac);
virtual void insert (const DT& item, int index);

virtual void remove (int index);
virtual void add (const DT& item);
virtual int size() const;
virtual int capacity() const;
virtual int incFactor() const;
virtual void setIncFactor(int f);
void setCapacity(int c);
};



And this one is the Actual code Vector.cpp



#include "Vector.h"

template
Vector
::Vector () : ArrayClass
()
{
_currSize = 0;
_incFactor = 5;
}

Vector
::~Vector ()
{
_currSize = NULL;
_incFactor = NULL;
}
template
Vector
::Vector (int n): ArrayClass
(n)
{
_currSize = 0;
_incFactor = (n+1)/2;

}
template
Vector
::Vector (int n, DT& val)
: ArrayClass
(n, val)
{
_currSize = 0;
_incFactor = n/2;
}
template
Vector
::Vector (const Vector
&v)

: ArrayClass
(v)
{
_currSize = v._currSize;
_incFactor = v.incFactor();
}
template
Vector
::Vector (const ArrayClass
& ac)
: ArrayClass
(ac)
{
_currSize = ac.size();

_incFactor = (_currSize+1)/2;
}
template
void Vector
::operator= (const Vector
& v)
{
ArrayClass
::copy (v);
_currSize = v._currSize;
_incFactor = v.incFactor();
}
//template

//void Vector
::operator= (const ArrayClass
&ac)
//{
// ArrayClass
::copy (ac);
// _currSize = ac.size();
// _incFactor = (_currSize+1)/2;
//}
template
int Vector
::size() const
{
return _currSize;

}
template
int Vector
::capacity() const
{
return _size;
}
template
int Vector
::incFactor() const
{
return _incFactor;

}
template
void Vector
::add (const DT& item)
{
insert (item, _currSize);
}
template
void Vector
::setIncFactor(int f)
{
if (f >= 0) _incFactor = f;

}
template
void Vector
::setCapacity(int c)
{
int len = _currSize;
if (len > c) len = c;
DT* paNew = new DT[c];
if (paNew == NULL)
{
throw ArrayMemoryException();

}
for (int i = 0; i < len; i++)
{
paNew[i] = paObject[i];
}
if (paObject != NULL)
{
delete[] paObject;
}
paObject = paNew;

_size = c;
if (_currSize > len)
{
_currSize = len;
}
}
template
void Vector
::insert (const DT& item, int index)
{
if ((index < 0) || (index > _currSize))

{
throw ArrayBoundsException();
}
if (_currSize+1 == _size)
{
setCapacity (_size + _incFactor);
}
_currSize++;
for (int i = _currSize-1; i > index; i--)
{

(*this)[i] = (*this)[i-1];
}
(*this)[index] = item;
}
template
void Vector
::remove (int index)
{
if ((index < 0) || (index >= _currSize))
{
throw ArrayBoundsException();

}
if (_currSize <= _size-_incFactor)
{
setCapacity (_size - _incFactor);
}
for (int i = index; i < _currSize-1; i++)
{
(*this)[i] = (*this)[i+1];
}
_currSize--;

}

Answer



While compiling your code, at the point, where template is being instantiated, i.e. in your code



Vector _accounts;


the compiler will generate a new class using template Vector ( with given template argument i.e AccountInfo*). Thus compiler needs access to implementation of template Vector at this point.




So, this implies, the template Vector should be completely implemented in a header file.



If you do want to keep the separation between template definition and implementation then
you can have two header files, one Vector.h and other Vector_impl.h, with Vector_impl.h containing the implementation of the template.



Include Vector.h in the Vector_impl.h and Include Vector_impl.h in the .cpp file where you are instantiating the template i.e. Vector < AccountInfo*>.


php - mysqli Query throws a notice : Trying to get property of non-objec

$startTime = "09:30";

$sql_monday = "SET @VALUE = '".$startTime."';
SELECT * FROM schedule_orders
WHERE @VALUE >= DATE_FORMAT(start_time, '%H:%i')
AND @VALUE <= DATE_FORMAT(end_time, '%H:%i');";


$result = $conn->query($sql_monday);
if ($result->num_rows > 0) {
// output data of each row
while($All_monday_Orders = $result->fetch_assoc()) {
$All_monday_Orders['id'];
}
}


Above is my Code which throws me a Notice





Notice: Trying to get property of non-object in on line if
($result->num_rows > 0)




if i echo this query and run in phpMyadmin , it showing results.



am i doing anything wrong here in this query ?

Thursday 28 April 2016

How to detect a syntax error in PHP?





I have got a PHP syntax error called




Parse error: syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING) in C:\xampp\htdocs\playit2\rental_list.php on line 189





The line 189 is



$jsql_ae3 = mysql_query("select products.formats from products where products.id='$jrowa2['id']'") or die(mysql_error());

Answer



With arrays and functions, you need to put curley braces:



$jsql_ae3 = mysql_query("select products.formats from products where products.id='{$jrowa2['id']}'") or die(mysql_error());


Does output buffering in PHP require more resources?



When performance is important including server memory,I am curious if using output buffering
like ob_start(); in PHP has ANY performance hits over not using it? Does it use more memory or anything to use it?



In my situation on a high traffic site where I need all the memory I can for memcache and APC and all the other server activities I am just curious if I should use it or not, the only real reason it comes in handy for me is for redirecting pages , sending headers I should say after a header has already been sent, my site has header , body, footer file setup so sometime I need to redirect depending on what is in the body file so if the header is already shown ion screen that creates a problem, using output buffering is 1 solution but there are other solutions so just curious about performance



Answer



I think it's best to use it with a high traffic site, or at least turn implicit flush off, to avoid sending partial responses over network, because it can slow down the rest of the script if the receiver is very slow too.



By sending the whole response in one time, you free all resources used by the php script, so it's more efficient.


javascript - How do I return the response from an asynchronous call?



I have a function foo which makes an Ajax request. How can I return the response from foo?



I tried returning the value from the success callback as well as assigning the response to a local variable inside the function and returning that one, but none of those ways actually return the response.




function foo() {
var result;

$.ajax({
url: '...',
success: function(response) {
result = response;
// return response; // <- I tried that one as well
}
});


return result;
}

var result = foo(); // It always ends up being `undefined`.

Answer




→ For a more general explanation of async behaviour with different examples, please see Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference




→ If you already understand the problem, skip to the possible solutions below.






The A in Ajax stands for asynchronous . That means sending the request (or rather receiving the response) is taken out of the normal execution flow. In your example, $.ajax returns immediately and the next statement, return result;, is executed before the function you passed as success callback was even called.



Here is an analogy which hopefully makes the difference between synchronous and asynchronous flow clearer:



Synchronous




Imagine you make a phone call to a friend and ask him to look something up for you. Although it might take a while, you wait on the phone and stare into space, until your friend gives you the answer that you needed.



The same is happening when you make a function call containing "normal" code:



function findItem() {
var item;
while(item_not_found) {
// search
}

return item;
}

var item = findItem();

// Do something with item
doSomethingElse();


Even though findItem might take a long time to execute, any code coming after var item = findItem(); has to wait until the function returns the result.




Asynchronous



You call your friend again for the same reason. But this time you tell him that you are in a hurry and he should call you back on your mobile phone. You hang up, leave the house and do whatever you planned to do. Once your friend calls you back, you are dealing with the information he gave to you.



That's exactly what's happening when you do an Ajax request.



findItem(function(item) {
// Do something with item
});

doSomethingElse();


Instead of waiting for the response, the execution continues immediately and the statement after the Ajax call is executed. To get the response eventually, you provide a function to be called once the response was received, a callback (notice something? call back ?). Any statement coming after that call is executed before the callback is called.








Embrace the asynchronous nature of JavaScript! While certain asynchronous operations provide synchronous counterparts (so does "Ajax"), it's generally discouraged to use them, especially in a browser context.




Why is it bad do you ask?



JavaScript runs in the UI thread of the browser and any long-running process will lock the UI, making it unresponsive. Additionally, there is an upper limit on the execution time for JavaScript and the browser will ask the user whether to continue the execution or not.



All of this is really bad user experience. The user won't be able to tell whether everything is working fine or not. Furthermore, the effect will be worse for users with a slow connection.



In the following we will look at three different solutions that are all building on top of each other:





  • Promises with async/await (ES2017+, available in older browsers if you use a transpiler or regenerator)

  • Callbacks (popular in node)

  • Promises with then() (ES2015+, available in older browsers if you use one of the many promise libraries)



All three are available in current browsers, and node 7+.






ES2017+: Promises with async/await




The ECMAScript version released in 2017 introduced syntax-level support for asynchronous functions. With the help of async and await, you can write asynchronous in a "synchronous style". The code is still asynchronous, but it's easier to read/understand.



async/await builds on top of promises: an async function always returns a promise. await "unwraps" a promise and either result in the value the promise was resolved with or throws an error if the promise was rejected.



Important: You can only use await inside an async function. Right now, top-level await isn't yet supported, so you might have to make an async IIFE (Immediately Invoked Function Expression) to start an async context.



You can read more about async and await on MDN.



Here is an example that builds on top of delay above:




// Using 'superagent' which will return a promise.
var superagent = require('superagent')

// This is isn't declared as `async` because it already returns a promise
function delay() {
// `delay` returns a promise
return new Promise(function(resolve, reject) {
// Only `delay` is able to resolve or reject the promise
setTimeout(function() {

resolve(42); // After 3 seconds, resolve the promise with value 42
}, 3000);
});
}


async function getAllBooks() {
try {
// GET a list of book IDs of the current user
var bookIDs = await superagent.get('/user/books');

// wait for 3 seconds (just for the sake of this example)
await delay();
// GET information about each book
return await superagent.get('/books/ids='+JSON.stringify(bookIDs));
} catch(error) {
// If any of the awaited promises was rejected, this catch block
// would catch the rejection reason
return null;
}
}


// Start an IIFE to use `await` at the top level
(async function(){
let books = await getAllBooks();
console.log(books);
})();


Current browser and node versions support async/await. You can also support older environments by transforming your code to ES5 with the help of regenerator (or tools that use regenerator, such as Babel).







Let functions accept callbacks



A callback is simply a function passed to another function. That other function can call the function passed whenever it is ready. In the context of an asynchronous process, the callback will be called whenever the asynchronous process is done. Usually, the result is passed to the callback.



In the example of the question, you can make foo accept a callback and use it as success callback. So this



var result = foo();
// Code that depends on 'result'



becomes



foo(function(result) {
// Code that depends on 'result'
});


Here we defined the function "inline" but you can pass any function reference:




function myCallback(result) {
// Code that depends on 'result'
}

foo(myCallback);


foo itself is defined as follows:




function foo(callback) {
$.ajax({
// ...
success: callback
});
}


callback will refer to the function we pass to foo when we call it and we simply pass it on to success. I.e. once the Ajax request is successful, $.ajax will call callback and pass the response to the callback (which can be referred to with result, since this is how we defined the callback).




You can also process the response before passing it to the callback:



function foo(callback) {
$.ajax({
// ...
success: function(response) {
// For example, filter the response
callback(filtered_response);
}
});

}


It's easier to write code using callbacks than it may seem. After all, JavaScript in the browser is heavily event driven (DOM events). Receiving the Ajax response is nothing else but an event.
Difficulties could arise when you have to work with third-party code, but most problems can be solved by just thinking through the application flow.






ES2015+: Promises with then()



The Promise API is a new feature of ECMAScript 6 (ES2015), but it has good browser support already. There are also many libraries which implement the standard Promises API and provide additional methods to ease the use and composition of asynchronous functions (e.g. bluebird).




Promises are containers for future values. When the promise receives the value (it is resolved) or when it is canceled (rejected), it notifies all of its "listeners" who want to access this value.



The advantage over plain callbacks is that they allow you to decouple your code and they are easier to compose.



Here is a simple example of using a promise:



function delay() {
// `delay` returns a promise
return new Promise(function(resolve, reject) {

// Only `delay` is able to resolve or reject the promise
setTimeout(function() {
resolve(42); // After 3 seconds, resolve the promise with value 42
}, 3000);
});
}

delay()
.then(function(v) { // `delay` returns a promise
console.log(v); // Log the value once it is resolved

})
.catch(function(v) {
// Or do something else if it is rejected
// (it would not happen in this example, since `reject` is not called).
});


Applied to our Ajax call we could use promises like this:



function ajax(url) {

return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.onload = function() {
resolve(this.responseText);
};
xhr.onerror = reject;
xhr.open('GET', url);
xhr.send();
});
}


ajax("/echo/json")
.then(function(result) {
// Code depending on result
})
.catch(function() {
// An error occurred
});



Describing all the advantages that promise offer is beyond the scope of this answer, but if you write new code, you should seriously consider them. They provide a great abstraction and separation of your code.



More information about promises: HTML5 rocks - JavaScript Promises



Side note: jQuery's deferred objects



Deferred objects are jQuery's custom implementation of promises (before the Promise API was standardized). They behave almost like promises but expose a slightly different API.



Every Ajax method of jQuery already returns a "deferred object" (actually a promise of a deferred object) which you can just return from your function:




function ajax() {
return $.ajax(...);
}

ajax().done(function(result) {
// Code depending on result
}).fail(function() {
// An error occurred
});



Side note: Promise gotchas



Keep in mind that promises and deferred objects are just containers for a future value, they are not the value itself. For example, suppose you had the following:



function checkPassword() {
return $.ajax({
url: '/password',
data: {
username: $('#username').val(),

password: $('#password').val()
},
type: 'POST',
dataType: 'json'
});
}

if (checkPassword()) {
// Tell the user they're logged in
}



This code misunderstands the above asynchrony issues. Specifically, $.ajax() doesn't freeze the code while it checks the '/password' page on your server - it sends a request to the server and while it waits, it immediately returns a jQuery Ajax Deferred object, not the response from the server. That means the if statement is going to always get this Deferred object, treat it as true, and proceed as though the user is logged in. Not good.



But the fix is easy:



checkPassword()
.done(function(r) {
if (r) {
// Tell the user they're logged in

} else {
// Tell the user their password was bad
}
})
.fail(function(x) {
// Tell the user something bad happened
});






Not recommended: Synchronous "Ajax" calls



As I mentioned, some(!) asynchronous operations have synchronous counterparts. I don't advocate their use, but for completeness' sake, here is how you would perform a synchronous call:



Without jQuery



If you directly use a XMLHTTPRequest object, pass false as third argument to .open.



jQuery




If you use jQuery, you can set the async option to false. Note that this option is deprecated since jQuery 1.8.
You can then either still use a success callback or access the responseText property of the jqXHR object:



function foo() {
var jqXHR = $.ajax({
//...
async: false
});
return jqXHR.responseText;

}


If you use any other jQuery Ajax method, such as $.get, $.getJSON, etc., you have to change it to $.ajax (since you can only pass configuration parameters to $.ajax).



Heads up! It is not possible to make a synchronous JSONP request. JSONP by its very nature is always asynchronous (one more reason to not even consider this option).


php - json_encode() function adds backslash

I have a PHP Array with the word 's morgens in it. I'm using a function which escapes the single quote, json_encode() adds another backslash to it which causes an error in the SQL code. The parameter JSON_UNESCAPED_SLASHES causes the following error:





Warning: json_encode() expects parameter 2 to be long, string given




The output is as follows, before json_encode():



string(11) "\'s middags"


And after json_encode():




"\\'s middags"


Its equivalent (long, 64) won't work, it doesn't throw an error. How can I prevent json_encode() from adding a backslash?



(Sorry for bad English, it's not my native language)

bash - How to update PATH to find nvcc for CUDA 8.0?

I have one main PC and one laptop, which I use to connect to the main PC through ssh. I recently installed CUDA 8.0 through the runtime installation on the main PC when sitting in front of it. I executed all the steps from http://docs.nvidia.com/cuda/cuda-installation-guide-linux/index.html and I was able to compile my code. However, I am not very frequently at the location of my main PC. Therefore, I would need to run code through ssh from my laptop. When I tried this, I got the error:



/bin/sh: 1: nvcc: not found
make: *** [.depend] Error 127



However, when looking at /usr/local/cuda-8.0/bin there is a command called nvcc. So I think it should be there. Next I checked the PATH and LD_LIBRARY_PATH variables. They appeared not to have the necessary links in it that are specified in step 6.1.1 in the link above:



export PATH=/usr/local/cuda-8.0/bin${PATH:+:${PATH}}
export LD_LIBRARY_PATH=/usr/local/cuda-8.0/lib64\
${LD_LIBRARY_PATH:+:${LD_LIBRARY_PATH}}


However, when I perform those steps again through ssh, it still doesn't work. And after closing the session and restarting it gain, the PATH and LD_LIBRARY_PATH variables have reset themselves again.




I guess you somehow need to make the changes permanent and this will solve my nvcc problem, but I don't know how (It doesn't mention it in the installation guide). So therefore my real question:




How to make the changes in the PATH and LD_LIBRARY_PATH variables
permanent? Will this solve my nvcc problem or do you think there is
more going on?


php - Parse error: syntax error, unexpected T_BOOLEAN_AND, expecting '(' in





$command = $_POST['cmd'];
$args = $_POST['args'];

if($args == !empty && $command != 'reload'){

}



Thanks guys, got it working!


Answer



empty is a function.



$command = $_POST['cmd'];
$args = $_POST['args'];
if(!empty($args) && $command != 'reload'){


}

timing - How do I time a method's execution in Java?



How do I get a method's execution time? Is there a Timer utility class for things like timing how long a task takes, etc?



Most of the searches on Google return results for timers that schedule threads and tasks, which is not what I want.


Answer



There is always the old-fashioned way:




long startTime = System.nanoTime();
methodToTime();
long endTime = System.nanoTime();

long duration = (endTime - startTime); //divide by 1000000 to get milliseconds.

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...