Monday, 31 October 2016

datetime - How to get the current date/time in Java



What's the best way to get the current date/time in Java?


Answer



It depends on what form of date / time you want:





  • If you want the date / time as a single numeric value, then System.currentTimeMillis() gives you that, expressed as the number of milliseconds after the UNIX epoch (as a Java long). This value is a delta from a UTC time-point, and is independent of the local time-zone ... assuming that the system clock has been set correctly.


  • If you want the date / time in a form that allows you to access the components (year, month, etc) numerically, you could use one of the following:




    • new Date() gives you a Date object initialized with the current date / time. The problem is that the Date API methods are mostly flawed ... and deprecated.


    • Calendar.getInstance() gives you a Calendar object initialized with the current date / time, using the default Locale and TimeZone. Other overloads allow you to use a specific Locale and/or TimeZone. Calendar works ... but the APIs are still cumbersome.


    • new org.joda.time.DateTime() gives you a Joda-time object initialized with the current date / time, using the default time zone and chronology. There are lots of other Joda alternatives ... too many to describe here. (But note that some people report that Joda time has performance issues.; e.g. Jodatime's LocalDateTime is slow when used the first time.)


    • in Java 8, calling LocalDateTime.now() and ZonedDateTime.now() will give you representations1 for the current date / time.






Prior to Java 8, most people who know about these things recommended Joda-time as having (by far) the best Java APIs for doing things involving time point and duration calculations. With Java 8, this is no longer true. However, if you are already using Joda time in your codebase, there is no strong2 reason to migrate.






1 - Note that LocalDateTime doesn't include a time zone. As the javadoc says: "It cannot represent an instant on the time-line without additional information such as an offset or time-zone."



2 - Your code won't break if you don't, and you won't get deprecation warnings. Sure, the Joda codebase will probably stop getting updates, but it is unlikely to need them. No updates means stability and that is a good thing. Also note that it is highly likely that if that someone will fix problems caused by regressions in the Java platform.


casting - Why didn't Katie Holmes play Rachel Dawes in The Dark Knight? - Movies & TV



Katie Holmes played Rachel Dawes in Batman Begins but Maggie Gyllenhall played the character in The Dark Knight.



Was there any particular reason why Katie Holmes didn't continue on in the role?


Answer



According to Julie Polkes, a spokeswoman for Ms. Holmes,




"Katie was offered but was unable to accept the role because of

scheduling conflicts. She was in the process of negotiating for
another project. In addition, when she returns to work, she would like
to tackle a new character."




But according to this article,




The studio is searching for a new actress who can replace Ms. Holmes
in the big-budget picture
, for which the salary range likely would

have been $1 million to $2 million, say these people, compared to the
roughly $1 million she earned for "Batman Begins."



php - Bad SQL syntax?




I'm getting the following 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 '' DStormr', 'ddo.png', 'Online:' at line 1`




The sql is the following:




"UPDATE articulo SET '".$nombre."', '".$imagen."', '".$text."', '".$precio."', '".$popup."', ".$genero_id.
" WHERE id=".$id"";


What am I missing/not seeing?


Answer



When you do an UPDATE you need to SET key = 'value'.


c - Casting allocated memory through double pointer

It is a good idea to cast the void pointer returned by malloc to the type of the destination pointer. In this case you can find an error similar to the error in your code snippet.




char **ptr;
ptr=(char *)malloc(sizeof(char)*value);


Here variable ptr has type char ** while the right side of the assignment statement has type char * due to the casting. So the compiler shall issue an error (more precisely a diagnostic message) because there is no implicit conversion from char *. to char **



By the way by this reason in C++ there is not allowed to assign a pointer of type void * to pointers of other types because such a code is unsafe.



The other reason to cast the void pointer returned by malloc is to make your code self-documented. Consider for example the following statement




p = malloc( sizeof( *p ) );


Here it is difficult to understand what is the type of memory is allocated. It would be much better to write for example



p = ( double * )malloc( sizeof( *p ) );


In this case the statement is more clear and you need not to scroll a big program listing that to determine what is the type of p.




Take into account that a good program is a program where each statement provides you as much information as you need that to understand what the statement is trying to do and what types of variables envolved in expressions..



There is one more reason to cast the pointer returned by malloc. If you will try to compile your code with a C++ compiler then it will issue numerous errors for each using of malloc without casting. When you will transfer your code from C to C++ you will estimate the value of such casting.



Here is the correct using of malloc for your example



char **ptr;

ptr = ( char ** )malloc( value * sizeof( char * ) );

for ( i = 0; i < value; i++ )
ptr[i] = ( char * )malloc( another_value * sizeof( char ) );

What's the difference between java 8 ZonedDateTime and OffsetDateTime?




I've read the documentation, but I still can't get when I should use one or the other:





According to documentation OffsetDateTime should be used when writing date to database, but I don't get why.


Answer




Q: What's the difference between java 8 ZonedDateTime and OffsetDateTime?





The javadocs say this:




"OffsetDateTime, ZonedDateTime and Instant all store an instant on the time-line to nanosecond precision. Instant is the simplest, simply representing the instant. OffsetDateTime adds to the instant the offset from UTC/Greenwich, which allows the local date-time to be obtained. ZonedDateTime adds full time-zone rules."




Source: https://docs.oracle.com/javase/8/docs/api/java/time/OffsetDateTime.html



Thus the difference between OffsetDateTime and ZonedDateTime is that the latter includes the rules that cover daylight saving time adjustments and various other anomalies.




Stated simply:




Time Zone = ( Offset-From-UTC + Rules-For-Anomalies )








Q: According to documentation OffsetDateTime should be used when writing date to database, but I don't get why.





Dates with local time offsets always represent the same instants in time, and therefore have a stable ordering. By contrast, the meaning of dates with full timezone information is unstable in the face of adjustments to the rules for the respective timezones. (And these do happen; e.g. for date-time values in the future.) So if you store and then retrieve a ZonedDateTime the implementation has a problem:




  • It can store the computed offset ... and the retrieved object may then have an offset that is inconsistent with the current rules for the zone-id.


  • It can discard the computed offset ... and the retrieved object then represents a different point in the absolute / universal timeline than the one that was stored.




If you use Java object serialization, the Java 9 implementation takes the first approach. This is arguably the "more correct" way to handle this, but this doesn't appear to be documented. (JDBC drivers and ORM bindings are presumably making similar decisions, and are hopefully getting it right.)




But if you are writing an application that manually stores date/time values, or that rely on java.sql.DateTime, then dealing with the complications of a zone-id is ... probably something to be avoided. Hence the advice.



Note that dates whose meaning / ordering is unstable over time may be problematic for an application. And since changes to zone rules are an edge case, the problems are liable to emerge at unexpected times.






A (possible) second reason for the advice is that the construction of a ZonedDateTime is ambiguous at the certain points. For example in the period in time when you are "putting the clocks back", combining a local time and a zone-id can give you two different offsets. The ZonedDateTime will consistently pick one over the other ... but this isn't always the correct choice.



Now, this could be a problem for any applications that construct ZonedDateTime values that way. But from the perspective of someone building an enterprise application is a bigger problem when the (possibly incorrect) ZonedDateTime values are persistent and used later.



calculator - Computing negative numbers in Java

Okay... I want to get around the concept of computing negative numbers. I am self-learning and I am running to a lot of difficulty. How do implement negative input?



My code:



public class MainSystem {


public static void main(String[] args) {
try (Scanner console = new Scanner(System.in)) {
String input;

System.out.print(">>> ");
input = console.nextLine();
splitEntry(input);

System.out.println("The console is now closed.");
}

}

private static void splitEntry(String input) {

String function = "[+\\-*/]+"; //placing them in an index
String[] token = input.split(function);//and this
double num1 = Double.parseDouble(token[0]);
double num2 = Double.parseDouble(token[1]);
//double answer;
String operator = input.toCharArray()[token[0].length()] + "";


if (operator.matches(function) && (token[0] + token[1] + operator).length() == input.length()) {
System.out.println("Operation is " + operator + ", your first number is " + token[0] + " your second number is " + token[1]);
} else {
System.out.println("Your entry of " + input + " is invalid");
}
if (operator.matches(function)
&& (token[0] + token[1] + operator).length() == input.length()) {
double result = 0;
if (operator.equals("+")) { // this is simplified by using formatters

result = num1 + num2;
} else if (operator.equals("-")) {
result = num1 - num2;
} else if (operator.equals("*")) {
result = num1 * num2;
} else if (operator.equals("/")) {
result = num1 / num2;
}
System.out.printf("Your first number %.2f %s by your second number %.2f = makes for %.2f%n", num1, operator, num2,
result);

}
}
}


How do I allow my calculator to place -2 + 5 and get the answer 3?



Every time I try to do that, the program crashes? What to do to make negative numbers to be computed

How to get the build/version number of your Android application?

I need to figure out how to get or make a build number for my Android application. I need the build number to display in the UI.



Do I have to do something with AndroidManifest.xml?

c# - Entity Framework claims to save changes but sometimes doesn't



I have a very strange problem - sometimes my database fails to populate with Plans and Buckets, then throws the exception shown at the end when trying to save Tasks to the db. Other times the code works perfectly. I would appreciate any insight into why this could be. Could it be a timing issue with the delete commands?




EntitiesModelContainer db = new EntitiesModelContainer();

List ignoredPlans = db.Plans.Where(p => p.Ignore).ToList();

// Delete old data completely
// foreign keys will cascade delete some tables such as buckets and tasks
db.Database.ExecuteSqlCommand("DELETE FROM Plans");
db.Database.ExecuteSqlCommand("DELETE FROM Assignees");

PlansResponse plans = GraphAPI.GetPlans();

foreach (PlanResponse plan in plans.Plans)
{
Plan planRecord = new Plan()
{
Id = plan.ID,
Title = plan.Title,
Ignore = ignoredPlans.Find(p => p.Id == plan.ID) != null
};
db.Plans.Add(planRecord);
bool changes = db.ChangeTracker.HasChanges();

int result = db.SaveChanges();

if (!planRecord.Ignore)
{
BucketsResponse buckets = GraphAPI.GetBuckets(plan);
foreach (BucketResponse bucket in buckets.Buckets)
{
Bucket bucketRecord = new Bucket()
{
Id = bucket.ID,

Name = bucket.Name,
PlanId = bucket.PlanID
};
db.Buckets.Add(bucketRecord);
db.SaveChanges();
}
TasksResponse tasks = GraphAPI.GetTasks(plan);
foreach (TaskResponse task in tasks.Tasks)
{
Task taskRecord = new Task()

{
Id = task.ID,
Title = task.Title,
Progress = task.PercentComplete,
Description = task.HasDescription ? GraphAPI.GetTaskDetails(task).Description : null,
CreatedDateTime = task.CreatedDateTime,
DueDateTime = task.DueDateTime,
CompletedDateTime = task.CompletedDateTime,
PlanId = task.PlanID,
BucketId = task.BucketID

};
db.Tasks.Add(taskRecord);
db.SaveChanges();


The last line is where the error occurs.




SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint "FK_PlanTask". The conflict occurred in database "Dashboard-dev", table "dbo.Plans", column 'Id'. The statement has been terminated.





The strange thing is, it doesn't always throw! Any help would be appreciated.



Update: You're right - it appears the code is running twice, concurrently. Why? I didn't (intentionally) mean to do this...



public class DBController : Controller
{
public ActionResult Index()
{
DBAccess.UpdateData();

return View();
}
}


The snippet posted above is the start of this method UpdateData().


Answer



Since it's complaining about the foreign key PlanId (I'm guessing), I'd say GetTasks somehow returns an incorrect PlanId.



To get to the bottom of it I'd set up a profiler session and examine the SQL statements when there's an error. Or just examine the objects in the debugger when the exception happens, I guess. The values of the properties should give a clue as to what's going on.




Edit: I just noticed your first line says 'sometimes it fails to populate with plans and tasks', missed that. I don't understand how it would continue if it couldn't save a plan, but a SQL profiler session might be able to answer that.



Edit after the fact: of course the simplest answer could be concurrency, especially if this is a web application, two requests could be coming in at the same time and overlapping.


Primitive type 'short' - casting in Java

I have a question about the primitive type short in Java. I am using JDK 1.6.



If I have the following:



short a = 2;

short b = 3;
short c = a + b;


the compiler does not want to compile - it says that it "cannot convert from int to short" and suggests that I make a cast to short, so this:



short c = (short) (a + b);


really works. But my question is why do I need to cast? The values of a and b are in the range of short - the range of short values is {-32,768, 32767}.

I also need to cast when I want to perform the operations -, *, / (I haven't checked for others).



If I do the same for primitive type int, I do not need to cast aa+bb to int. The following works fine:



int aa = 2;
int bb = 3;
int cc = aa +bb;


I discovered this while designing a class where I needed to add two variables of type short, and the compiler wanted me to make a cast. If I do this with two variables of type int, I don't need to cast.




A small remark: the same thing also happens with the primitive type byte. So, this works:



byte a = 2;
byte b = 3;
byte c = (byte) (a + b);


but this not:




byte a = 2;
byte b = 3;
byte c = a + b;


For long, float, double, and int, there is no need to cast. Only for short and byte values.

java - How to add an image to a JPanel?



I have a JPanel to which I'd like to add JPEG and PNG images that I generate on the fly.



All the examples I've seen so far in the Swing Tutorials, specially in the Swing examples use ImageIcons.



I'm generating these images as byte arrays, and they are usually larger than the common icon they use in the examples, at 640x480.





  1. Is there any (performance or other) problem in using the ImageIcon class to display an image that size in a JPanel?

  2. What's the usual way of doing it?

  3. How to add an image to a JPanel without using the ImageIcon class?



Edit: A more careful examination of the tutorials and the API shows that you cannot add an ImageIcon directly to a JPanel. Instead, they achieve the same effect by setting the image as an icon of a JLabel. This just doesn't feel right...


Answer



Here's how I do it (with a little more info on how to load an image):



import java.awt.Graphics;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JPanel;

public class ImagePanel extends JPanel{


private BufferedImage image;

public ImagePanel() {
try {
image = ImageIO.read(new File("image name and path"));
} catch (IOException ex) {
// handle exception...
}
}


@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, this); // see javadoc for more info on the parameters
}

}

javascript - Variable inside setTimeout says it is undefined, but when outside it is defined




I have a class. I need to do some http work inside of a timeout. The problem I am faceing is the http variable inside the timeout keeps saying it is undefined.



export class MyClass {

http:Http:


constructor(private http:Http) {
this.http = http;
}

sendFriendRequest(){

this.http.post( ...//http variable is defined here
setTimeout(function(){
this.http.post(... //http is not defined here
}

}
}

Answer



The reason for this is that the callback function inside setTimeout is in a different lexical environment. This is why in ES6+ functions can be defined using =>. This is so that the code within a function shares the same scope as the function.



To fix this, you can either use ES6+ syntax, where instead of function(a,b,args) {...} you would use (a,b,args) => {...}:



setTimeout( () => {
this.http.post(...)

});


or with ES5 syntax:



var root = this;

setTimeout(function(){
root.http.post(...)
}



Hope this helps!


javascript - send get request via jquery slider and keep the value on slider on after page reloads




So below this is my JQUERY script which i use , i send the value from slider to and input and than i use to in PHP to GET request .








I want some help in keeping the value on the slider after refresh here is my form and PHP









if(isset($_GET['to'])){
if($_SERVER['REQUEST_METHOD'] == 'GET'){
mysql_connect('localhost','root','GoogleFacebook') or die(mysql_error());
mysql_select_db('phones') or die(mysql_error());
$to = mysql_real_escape_string($_GET['to']);
if(!empty($to)){
$query = mysql_query("SELECT * FROM price WHERE phone_price BETWEEN 0 AND " .$to );
while($row = mysql_fetch_array($query)){
print '

';
print $row['phone_name'];

print '';
print $row['phone_price'];
print '
';
print '

';
}
}
else{

print"";
print("");

}
}
}
?>


I dont know much jquery therefore i tried the slider from JQUERY original website , i am able to retrieve results from DATABASE but i don't know the way t keep the slider value the same , is there a way to get the slider value from the url like same_page.php/to?=500 i want the "500" .



PLEASE DONT TELL ME I USE OBSOLETE MYSQL which will be removed from PHP 7


Answer




  $("#slider1").slider({

min: 0, //minimum value
max: 1100, //maximum value
animate: true,
value: 50, // <<<< THAT LINE!!
slide: function(event, ui) {
$("#value1").val(ui.value);
}
});


$("#value1").val($("#slider1").slider("value"));
});


Maybe you could echo out the value you've stored there by using PHP? Or maybe store the current value in a cookie and read it out inside the slider's initiation...






Answer:




var a = window.location.href ; var matches = a.match(/\d+$/); console.log(matches);

c++ - How do I install the OpenSSL libraries on Ubuntu?



I'm trying to build some code on Ubuntu 10.04 LTS that uses OpenSSL 1.0.0. When I run make, it invokes g++ with the "-lssl" option. The source includes:



#include 

#include
#include
#include
#include
#include


I ran:



$ sudo apt-get install openssl

Reading package lists... Done
Building dependency tree
Reading state information... Done
openssl is already the newest version.
0 upgraded, 0 newly installed, 0 to remove and 3 not upgraded.


But I guess the openssl package doesn't include the library. I get these errors on make:



foo.cpp:21:25: error: openssl/bio.h: No such file or directory

foo.cpp:22:28: error: openssl/buffer.h: No such file or directory
foo.cpp:23:25: error: openssl/des.h: No such file or directory
foo.cpp:24:25: error: openssl/evp.h: No such file or directory
foo.cpp:25:25: error: openssl/pem.h: No such file or directory
foo.cpp:26:25: error: openssl/rsa.h: No such file or directory


How do I install the OpenSSL C++ library on Ubuntu 10.04 LTS?



I did a man g++ and (under "Options for Linking") for the -l option it states: " The linker searches a standard list of directories for the library..." and "The directories searched include several standard system directories..." What are those standard system directories?



Answer



You want to install the development package, which is libssl-dev:



sudo apt-get install libssl-dev

fopen - PHP feof() returning true before the end of file



I have been working on a strange PHP problem the last few days where the feof() function is returning true before the end of a file. Below is a skeleton of my code:



$this->fh = fopen("bigfile.txt", "r");    

while(!feof($this->fh))
{
$dataString = fgets($this->fh);

if($dataString === false && !feof($this->fh))
{
echo "Error reading file besides EOF";
}
elseif($dataString === false && feof($this->fh))
{
echo "We are at the end of the file.\n";

//check status of the stream
$meta = stream_get_meta_data($this->fh);
var_dump($meta);
}
else
{
//else all is good, process line read in
}
}


Through lots of testing I have found that the program works fine on everything except one file:




  • The file is stored on the local drive.

  • This file is around 8 million lines long averaging somewhere around 200-500 characters per line.

  • It has already been cleaned and under close examination with a hex editor, no abnormal characters have been found.

  • The program consistently fails on line 7172714 when it believes it has reached the end of the file (even though it has ~800K lines left).

  • I have tested the program on files that had fewer characters per line but were between 20-30 million lines with no problems.

  • I tried running the code from a comment on http://php.net/manual/en/function.fgets.php just to see if it was something in my code that was causing the issue and the 3rd party code failed on the same line. EDIT: also worth mentioning is that the 3rd party code used fread() instead of fgets().

  • I tried specifying several buffer sizes in the fgets function and none of them made any difference.



The output from the var_dump($meta) is as follows:



 array(9) {
["wrapper_type"]=>
string(9) "plainfile"
["stream_type"]=>
string(5) "STDIO"
["mode"]=>
string(1) "r"
["unread_bytes"]=>
int(0)
["seekable"]=>
bool(true)
["uri"]=>
string(65) "full path of file being read"
["timed_out"]=>
bool(false)
["blocked"]=>
bool(true)
["eof"]=>
bool(true)
}


In attempting to find out what is causing feof to return true before the end of the file I have to guess that either:



A) Something is causing the fopen stream to fail and then nothing is able to be read in (causing feof to return true)



B) There is some buffer somewhere that is filling up and causing havoc



C) The PHP gods are angry



I have searched far and wide to see if anyone else was having this issue and cannot find any instances except in C++ where the file was being read in via text mode instead of binary mode and was causing the issue.



UPDATE:
I had my script constantly output the number of times the read function had iterated and the unique ID of the user associated with the entry it found beside it. The script is still failing after line 7172713 out of 7175502, but the unique ID of the last user in the file is showing up on line 7172713. It seems that the problem is for some reason lines are being skipped and are not read. All line breaks are present.


Answer



fgets() is seemingly randomly reading in some lines that do have content as empty. The script actually makes it to the end of the file even though my test that showed the line numbers being read was behind due to the way I did the error checking (and the way the error checking was written in the 3rd party code). Now the real question is what is causing fgets() and fread() to think that a line is empty even though it is not. I will ask that as a separate question as that is a change in topic. Thank you all for your help!



Also, just so no one is left hanging, the reason the 3rd party code did not work is because it relied on a line at least having a line break where the current problem with fgets and fread returning an empty string does not give the script what it needs to know the line ever existed, thus it continues trying to execute past the end of the file. Below is the slightly modified 3rd party script which I still consider excellent based on it's execution speed.



The original script can be found in the comments here: http://php.net/manual/en/function.fgets.php and I take absolutely no credit for it.




//File to be opened
$file = "/path/to/file.ext";
//Open file (DON'T USE a+ pointer will be wrong!)
$fp = fopen($file, 'r');
//Read 16meg chunks
$read = 16777216;
//\n Marker
$part = 0;

while(!feof($fp))
{
$rbuf = fread($fp, $read);
for($i=$read;$i > 0 || $n == chr(10);$i--)
{
$n=substr($rbuf, $i, 1);
if($n == chr(10))break;
//If we are at the end of the file, just grab the rest and stop loop
elseif(feof($fp))
{
$i = $read;
$buf = substr($rbuf, 0, $i+1);
echo "\n";
break;
}
}
//This is the buffer we want to do stuff with, maybe thow to a function?
$buf = substr($rbuf, 0, $i+1);

//output the chunk we just read and mark where it stopped with
echo $buf . "\n\n";

//Point marker back to last \n point
$part = ftell($fp)-($read-($i+1));
fseek($fp, $part);
}
fclose($fp);

?>


UPDATE: After hours more searching, analyzing, hair pulling, etc. it seems that the culprit was an uncaught bad character - in this case a 1/2 character hex value BD. While generating the file that I was reading from the script used stream_get_line() to read the line in from it's original source. It was then supposed to remove all bad characters (it appears that my regex was not up to par) and then use str_getcsv() to convert the content to an array, do some processing, then write to a new file (the one I was trying to read). Somewhere in this process, probably str_getcsv(), the 1/2 character caused the whole thing to just insert a blank line instead of the data. Several thousand of these were placed all throughout the file (wherever the 1/2 symbol appeared). This made the file appear to be the correct length, but for the EOF to be reached too quickly when counting input based on a known number of lines. I want to thank everyone who helped me with this problem and I am very sorry that the real cause had nothing to do with my question. However if it hadn't been for everyone's suggestions and questions I would not have looked in the right places.



Lesson learned from this experience - when EOF is reached too quickly the best place to look is for instances of double line breaks. When writing a script that reads from a formatted file a good practice is to check for these. Below is my original code modified to do just that:



$this->fh = fopen("bigfile.txt", "r");    

while(!feof($this->fh))
{
$dataString = fgets($this->fh);

if($dataString == "\n" || $dataString == "\r\n" || $dataString == "")
{
throw new Exception("Empty line found.");
}

if($dataString === false && !feof($this->fh))
{
echo "Error reading file besides EOF";
}
elseif($dataString === false && feof($this->fh))
{
echo "We are at the end of the file.\n";

//check status of the stream
$meta = stream_get_meta_data($this->fh);
var_dump($meta);
}
else
{
//else all is good, process line read in
}
}

sql - INNER JOIN ON vs WHERE clause



For simplicity, assume all relevant fields are NOT NULL.



You can do:



SELECT
table1.this, table2.that, table2.somethingelse
FROM
table1, table2
WHERE
table1.foreignkey = table2.primarykey
AND (some other conditions)


Or else:



SELECT
table1.this, table2.that, table2.somethingelse
FROM
table1 INNER JOIN table2
ON table1.foreignkey = table2.primarykey
WHERE
(some other conditions)


Do these two work on the same way in MySQL?


Answer



INNER JOIN is ANSI syntax which you should use.



It is generally considered more readable, especially when you join lots of tables.



It can also be easily replaced with an OUTER JOIN whenever a need arises.



The WHERE syntax is more relational model oriented.



A result of two tables JOINed is a cartesian product of the tables to which a filter is applied which selects only those rows with joining columns matching.



It's easier to see this with the WHERE syntax.



As for your example, in MySQL (and in SQL generally) these two queries are synonyms.



Also note that MySQL also has a STRAIGHT_JOIN clause.



Using this clause, you can control the JOIN order: which table is scanned in the outer loop and which one is in the inner loop.



You cannot control this in MySQL using WHERE syntax.


'saw-3' tag wiki

There is no usage guidance for this tag … yet!


Usage guidance, also known as a tag wiki excerpt, is a short blurb that describes when and why a tag should be used on this site specifically.




There is no tag wiki for this tag … yet!



Tag wikis help introduce newcomers to the tag. They contain an overview of the topic defined by the tag, along with guidelines on its usage.



All registered users may propose new tag wikis.



(Note that if you have less than 20000 reputation, your tag wiki will be peer reviewed before it is published.)


c# - How do you validate phone number in asp.net?

I need to validate phone number that allows numeric and symbols + - ()
how can i do so in asp.net?





operators - Using

This is known as heredoc. It's essentially a way of defining the value of a variable that spans multiple lines, and doesn't require escaping like traditional strings. The "CON" part is merely an identifier that represents the start and end of the value. This can be changed to a more familiar value.




$str = <<Example of string
spanning multiple lines
using heredoc syntax.
EOD;

Program error in visual studio c++ 2010 express

May i know how to solve this problem, after i have run my program in visual c++ 2010 express?



Program Code



#include "stdafx.h"
#include "stdio.h"

int main(void)

{
printf("Welcome !!!\n");
return 0;
}


Output message
1>------ Rebuild All started: Project: Exercise, Configuration: Debug Win32 ------
1> stdafx.cpp
1> Exercise.cpp

1>LINK : fatal error LNK1123: failure during conversion to COFF: file invalid or corrupt
========== Rebuild All: 0 succeeded, 1 failed, 0 skipped ==========

plot explanation - Was Frodo Baggins in the original version of The Hobbit?

I see from the trailers for the new Hobbit film that Frodo Baggins is in it.


It has been a while since I read the book but I don't remember Frodo being in it.


Was his addition only for the movie adaptation or was he in the story all along?


Answer


It looks like Frodo is being shoe-horned into The Hobbit to keep audiences happy (general audiences, mind you, not LotR fans who are not pleased with this news).


According to a report from AICN:


What’s Frodo doing in The Hobbit? I don’t want to spoil too much, but I can say that Frodo is part of the connecting tissue between The Hobbit and Fellowship of the Ring.
In fact, the next shot was an over the shoulder on Elijah Wood hammering a sign up on Bag End’s front gate: “No Admittance Except On Party Business.” You guys should have an idea where that puts this moment in the timeline


Extrapolating from this tidbit, I believe it is safe to say that 'Elderly Bilbo' (Ian Holm has already filmed his scenes in London) will be recounting his tale to Frodo before the party that we see in Fellowship of the Ring. The events of The Hobbit took place 60 years before the Lord of the Rings trilogy (and 28 years before Frodo was born) - so this explanation seems to make the most sense.


In answer to your original question - he was only added for the movie adaptation.


BTW - the same goes for Legolas...


Sunday, 30 October 2016

c# - Object Reference not set to an object (calling Razor model from View)




Using C# MVC4



My View:



@using Universe.Models
@model UserModel
@section css {
}
@using (Html.BeginForm("AddUser","Home", FormMethod.Post))

{










My Model:



public class UserModel

{
public int Id { get; set; }
public string Alias { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public bool IsExternal { get; set; }


public UserModel()
{


}

public UserModel(User user)
{
if (user == null) return;
Alias = user.Alias;
}
}



But, I keep getting the error:



enter image description here



When I try to debug it, it doesn't even go into the Html.TextBox method or into my model.


Answer



Without seeing your controller action, my guess would be that your model is null.



In your controller, make sure you are passing an instance of the model to your view. For example:




return View(new UserModel());


Instead of:



return View();

r - How to display a message/warning/error with Unicode characters under Windows?

I have a message (or warning or error) containing Unicode characters. (The string has UTF-8 encoding.)



x <- "\u20AC \ub124" # a euro symbol, and Hangul 'ne'
## [1] "€ 네"

Encoding(x)
## [1] "UTF-8"


Under Linux, this prints OK in a message if the locale is UTF-8 (l10n_info()$`UTF-8` returns TRUE).



I can force this, by doing, e.g.,



devtools::with_locale(
c(LC_CTYPE = "en_US.utf8"),

message(x)
)
## € 네


Under Windows there are no UTF-8 locales, so I can't find an equivalent way to enforce correct printing. For example, with a US locale, the Hangul character doesn't display properly.



devtools::with_locale(
c(LC_CTYPE = "English_United States"),
message(x)

)
## €


There's a related problem with Unicode characters not displaying properly when printing data frames under Windows. The advice there was to set the locale to Chinese/Japanese/Korean. This does not work here.



devtools::with_locale(
c(LC_CTYPE = "Korean_Korea"),
message(x)
)

## ¢Ã¦ ³× # equivalent to iconv(x, "UTF-8", "EUC-KR")


How can I get UTF-8 messages, warnings and errors to display correctly under Windows?

c++ - Use ndk-build to link with an existing static library

I have a library that I compile for Android using cmake and android-cmake and obtaining a static lib.



Then I tried to link my test project with this static library using such an Android.mk file:



LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE := test
LOCAL_SRC_FILES := ../test.cxx
LOCAL_C_INCLUDES += $(LOCAL_PATH)/../../src

LOCAL_CFLAGS := -std=gnu++11 -D__ANDROID__
LOCAL_CPP_FEATURES += exceptions
LOCAL_LDLIBS += -L.. -ljson++
include $(BUILD_EXECUTABLE)


And Application.mk



NDK_TOOLCHAIN_VERSION = 4.7
APP_STL := gnustl_static



json++ here is a name of a library I've previously built with cmake.



It fails during linking with




../libjson++.a(object.cpp.o):object.cpp:function json::error_json_object_invalid_type(void const*, json::object_type, json::object_type, char const*): error: undefined reference to 'std::basic_ostringstream, std::allocator >::~basic_ostringstream()'
../libjson++.a(object.cpp.o):object.cpp:function json::error_json_object_invalid_type(void const*, json::object_type, json::object_type, char const*): error: undefined reference to 'VTT for std::basic_ostringstream, std::allocator >'
../libjson++.a(object.cpp.o):object.cpp:function json::error_json_object_invalid_type(void const*, json::object_type, json::object_type, char const*): error: undefined reference to 'vtable for std::basic_ostringstream, std::allocator >'

../libjson++.a(object.cpp.o):object.cpp:function json::error_json_object_invalid_type(void const*, json::object_type, json::object_type, char const*): error: undefined reference to 'vtable for std::basic_stringbuf, std::allocator >'
../libjson++.a(object.cpp.o):object.cpp:function json::error_json_object_no_such_key(void const*, void const*, unsigned int): error: undefined reference to 'std::basic_ostringstream, std::allocator >::~basic_ostringstream()'
../libjson++.a(object.cpp.o):object.cpp:function json::error_json_object_no_such_key(void const*, void const*, unsigned int): error: undefined reference to 'VTT for std::basic_ostringstream, std::allocator >'
../libjson++.a(object.cpp.o):object.cpp:function json::error_json_object_no_such_key(void const*, void const*, unsigned int): error: undefined reference to 'vtable for std::basic_ostringstream, std::allocator >'
../libjson++.a(object.cpp.o):object.cpp:function json::error_json_object_no_such_key(void const*, void const*, unsigned int): error: undefined reference to 'vtable for std::basic_stringbuf, std::allocator >'
../libjson++.a(object.cpp.o):object.cpp:function std::basic_stringbuf, std::allocator >::~basic_stringbuf(): error: undefined reference to 'vtable for std::basic_stringbuf, std::allocator >'
collect2: error: ld returned 1 exit status
make: * [obj/local/armeabi/test] Error 1





This error is caused by libgnustl_static.a being in call of compiler before the -ljson++:



/opt/android-ndk/toolchains/arm-linux-androideabi-4.7/prebuilt/linux-x86_64/bin/arm-linux-androideabi-g++ -Wl,--gc-sections -Wl,-z,nocopyreloc --sysroot=/opt/android-ndk/platforms/android-3/arch-arm ./obj/local/armeabi/objs/test/__/test.o /opt/android-ndk/sources/cxx-stl/gnu-libstdc++/4.7/libs/armeabi/libgnustl_static.a -lgcc -no-canonical-prefixes  -Wl,--no-undefined -Wl,-z,noexecstack -Wl,-z,relro -Wl,-z,now  -L/opt/android-ndk/platforms/android-3/arch-arm/usr/lib -L.. -ljson++ -lc -lm -o ./obj/local/armeabi/test


So it can be solved by adding



 -L${ANDROID_NDK}/sources/cxx-stl/gnu-libstdc++/4.7/libs/armeabi-v7a/ -lgnustl_static



to LOCAL_LDLIBS



And the question now: what is the correct way of linking with in existing static library if it does not belong to my project and is compiled with different build system?

plot explanation - Cracks in the wall inconsistencies

In the 11th doctor's 1st series there is a story arc involving cracks appearing across the universe and removing people from history.


However I don't understand, in some examples people are removed from history (the troops from the Byzantium and Rory), however in other places beings appear to be able to enter and exit the cracks at will (Prizoner Zero and the Doctor when checking for debris inside the crack).


Is there any opinion on why the cracks have different effects on different people?


Answer


The general suggestion (at least as far as The Doctor is concerned) is that as a creature of time he is able to control his contact with the effects of the crack. He has to give himself over to it willingly before it consumes him.


In the 11th season, the nature of the crack is said to not be fully understood and will be effected by the "Great Unasked Question" of season 12. It is possible that the Silence and the race that Prisoner Zero is from are involved in this greater issue and can transcend the effects of the crack.


We do see that once inside the crack, the Doctor has some general control as he steps backwards and 'unwinds' through his own history.


c# - javascript validation for email format accepting incorrect email format @abcd.com.gmail,





Possible Duplicate:
Validate email address in Javascript?







I have to do validation for Email format, I am using the CODE below line to restrict Special Characters.



onkeypress="return AlphaNumericBox(event,this,'@._);"


But now the Problem is I don have any proper validation for the exact format for example its also accepting text like " @abcd.com.gmail,.. " Is there any javascript validation for this?
any idea?



Thanks in advance.



Answer



function CheckEmail(address){
address=address.replace(/(^\s*)|(\s*$)/g, "");
var reg=/([\w._-])+@([\w_-])+(\.([\w_-])+){1,2}/;
var matcharr=reg.exec(address);
if(matcharr!=null){
if(matcharr[0].length==address.length){
return true;
}
return false;

}
return false;
}

eg:
var sVal=" t.st@gmail.com.cn ";
var sVal2=" t.st@gmail.com.cn.abc ";
console.log(CheckEmail("name@server.com")); //outpus true
console.log(CheckEmail("@server.com")); //outpus false


java - System.currentTimeMillis()'s accuracy on windows, would it be better to use a linux VM when measuring performance?

From my research, System.currentTimeMillis() is not always accurate, especially on windows. I'm currently carrying out microbenchmarking on a Windows 10 machine. Would switching over to say, a linux VM give me more accurate results when using the method? Thanks.

How do I get extra data from intent on Android?



How can I send data from one activity (intent) to another?



I use this code to send data:



Intent i=new Intent(context,SendMessage.class);

i.putExtra("id", user.getUserAccountId()+"");
i.putExtra("name", user.getUserFullName());
context.startActivity(i);

Answer



First, get the intent which has started your activity using the getIntent() method:



Intent intent = getIntent();



If your extra data is represented as strings, then you can use intent.getStringExtra(String name) method. In your case:



String id = intent.getStringExtra("id");
String name = intent.getStringExtra("name");

python - Regex include line breaks




I have the following xml file




A




B
C




D




Picture number 3?




and I just want to get the text between

and
.
So I've tried this code :



import os, re


html = open("2.xml", "r")
text = html.read()
lon = re.compile(r'
\n(.+)\n
', re.MULTILINE)
lon = lon.search(text).group(1)
print lon


but It doesn't seem to work.


Answer



1) Don't parse XML with regex. It just doesn't work. Use an XML parser.




2) If you do use regex for this, you don't want re.MULTILINE, which controls how ^ and $ work in a multiple-line string. You want re.DOTALL, which controls whether . matches \n or not.



3) You probably also want your pattern to return the shortest possible match, using the non-greedy +? operator.



lon = re.compile(r'
\n(.+?)\n
', re.DOTALL)

c# - How to escape double quotes with string interpolation

I have this:



var s = $"my name is {model.Name}":



and I want the string to be:



"my name is "someone""



How can I do this?

javascript - Await function when used as a function parameter does not get resolved before the function is run



The following code work as expected using async/await:



try {
let feedbacks = await feedbackService.get(this.feedBackOdataModel);
this.feedBackJsonModel.setProperty('/Avaliacoes', feedbacks.results);



} catch (error) {
dialogService.showErrorDialog("Erro na obtenção das pesquisas de satisfação", error.statusText + '-' + error.statusCode);
throw new Error(error);
}


The execution is halted until feedbackService gets resolved.



But this:




... 
this.feedBackJsonModel.setProperty('/Avaliacoes', await
feedbackService.get(this.feedBackOdataModel).results);
...


I imagine the result should be the same but it seens the the promise gets resolved after the setProperty is run.


Answer



Your two code examples are not equivalent. In the first, you are awaiting




feedbackService.get(this.feedBackOdataModel)


which is presumably a promise, and in the second, you are awaiting



feedbackService.get(this.feedBackOdataModel).results


which is presumably undefined. So indeed, the await has essentially no effect, and undefined is passed into setProperty almost immediately.




To fix - use parentheses to correctly indicate what you are awaiting:



this.feedBackJsonModel.setProperty(
'/Avaliacoes',
(await feedbackService.get(this.feedBackOdataModel)).results
);

Creating new column for reactive dataframe in shiny/shiny dashboard R

within the server for my shinyApp, I created a dataframe based on the inputs. However, I want to add a new column that utilizes two of the columns of that dataframe.




server <- function(input, output, session) {
l.out <- reactive({
BatchGetSymbols(tickers = input$stock,
first.date = Sys.Date() - as.integer(input$length),
last.date = Sys.Date())
})
stock_info <- reactive({
l.out()$df.tickers
})

stock_info()$return <- reactive({
rep(0, length(stock_info()$ref.date))
})
stock_info()$return <- reactive({
for (i in 2:length(stock_info()$ref.date)){
stock_info()$return[i] <- ((stock_info()$price.close[i] -
stock_info()$price.close[i - 1]) / stock_info$price.close[i - 1])
}
})



I have tried it like this, and it works up until I try to create stock_info()$return, where I keep getting the error that NULL left assignment.
Any tips?

javascript - Pause the function execution flow till ajax request completes



I seem to be running into the typical "Asynchronous Problem", with the solution eluding me.



I have a bootstrap form wizard which is just an improvised tabs/slideshow kinda thingy. All my "Steps" are forms each inside respective tabs/slides.



It has a set of next/previous buttons to navigate around the slides.
And It provides a function callback on before moving to next slide.
Inside which(callback) I am "client-side validating" the form in current slide and if its validated then I am submitting the form using ajax. And once I get the response from server, I am deciding whether to return true (proceed to next slide) or return false (stop the navigation to next slide).




I have looked into ..




  • Using callbacks but then it wont stop the plugin from proceeding to next slide, which btw is a hard coded success message, so while we are waiting for the ajax response the wizard has already moved to the next slide.

  • Using async:false but this hangs the browser like crazy(by design), till the request is completed, so sans the hanging this is exactly what I want.



My code is as below.




JS.



  jQuery('#progressWizard').bootstrapWizard({
'nextSelector': '.next',
'previousSelector': '.previous',
onNext: function (tab, navigation, index) {
if (index == 1) { // Here I am deciding which code to execute based on the current slide/tab (index)
if (jQuery("#paymentstep1").data('bValidator').validate()) {
var data = new FormData(jQuery('#paymentstep1')[0]);
jQuery("#cgloader").fadeIn();

var success = false;
jQuery.ajax({
type: "post",
async: false,
contentType: false,
processData: false,
url: "xyz.php",
dataType: "json",
data: data,
success: function (r) {


return r;
}
});
}....

Answer



The docs for onNext say:





Fired when next button is clicked (return false to disable
moving to the next step)




So simply return false from your handler. In the AJAX success callback, call next to advance to the next slide.



var requestCompleted = false;
jQuery('#progressWizard').bootstrapWizard({
'nextSelector': '.next',
'previousSelector': '.previous',

onNext: function (tab, navigation, index) {
if (index == 1) { // Here I am deciding which code to execute based on the current slide/tab (index)
if (jQuery("#paymentstep1").data('bValidator').validate()) {
if(!requestCompleted) {
var data = new FormData(jQuery('#paymentstep1')[0]);
jQuery("#cgloader").fadeIn();
var success = false;
jQuery.ajax({
type: "post",
url: "xyz.php",

data: data,
// ...
success: function (r) {
requestCompleted = true;
jQuery('#progressWizard').bootstrapWizard('next');
return r;
}
});
return false;
}

}
}
});

Gradle cannot find the Android Support Repository - Eclipse Neon, Gradle 3.5, javafxports

This is my first post. I have searched extensively for four days through Stackoverflow and other sources for the problem and have yet to find a solution. This one really has me racking my brain.



Using Eclipse NEON, Gradle 3.5, JavaFXPorts 1.3.5, latest Android SDK



Developing on Windows 10 x64



All expected Gradle tasks are not showing for simple, one-class "Hello World" project. (eg. android, androidRelease, androidInstall, etc. tasks all missing).



From command line, I can run gradlew android and I get an error that Android Support Repository cannot be found.




AFAIK android SDK path is set properly and the Android Support Repository is installed.



Note that that "gradlew run" does build and execute the Desktop version of the project properly.



Below are key config files and outputs. I can post anything else as requested.



========



gradle.build:




buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'org.javafxports:jfxmobile-plugin:1.3.5'
}
}


apply plugin: 'org.javafxports.jfxmobile'

repositories {
jcenter()
}


dependencies {
implementation 'com.google.guava:guava:21.0'
}


jfxmobile {
android {
compileSdkVersion = 25
targetSdkVersion = 19
minSdkVersion = 17
}
}

mainClassName = 'Main'



=======



gradle.properties:



org.gradle.jvmargs=-Xms128m -Xmx1g
ANDROID_HOME=c/:androidSDK



=======



SDK Manager --list (shows repository installed):



C:\androidSDK\tools\bin>sdkmanager.bat --list
Warning: File C:\Users\Kent\.android\repositories.cfg could not be loaded.
Installed packages:
Path | Version | Description | Location
------- | ------- | ------- | -------
build-tools;25.0.3 | 25.0.3 | Android SDK Build-Tools 25.0.3 | build-tools\25.0.3\

emulator | 26.0.0 | Android Emulator | emulator\
extras;android;m2repository | 47.0.0 | Android Support Repository | extras\android\m2repository\
extras;intel;Ha...ecution_Manager | 6.0.6 | Intel x86 Emulator Accelerator... | extras\intel\Ha...cution_Manager\
patcher;v4 | 1 | SDK Patch Applier v4 | patcher\v4\
platform-tools | 25.0.5 | Android SDK Platform-Tools | platform-tools\
platforms;android-25 | 3 | Android SDK Platform 25 | platforms\android-25\
sources;android-25 | 1 | Sources for Android 25 | sources\android-25\
tools | 26.0.2 | Android SDK Tools | tools\



=======



gradlew android output:



C:\Users\Kent\workspace\TestJavaFXPorts3>gradlew android
Starting a Gradle Daemon (subsequent builds will be faster)

FAILURE: Build failed with an exception.

* What went wrong:

You must install the Android Support Repository. Open the Android SDK Manager and choose the Android Support Repository from the Extras category at the bottom of the list of packages.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

Total time: 7.627 secs



=======



Android SDK directory:



C:\androidSDK>dir
Volume in drive C is Acer
Volume Serial Number is C492-4415

Directory of C:\androidSDK


2017-05-06 08:55 PM
.
2017-05-06 08:55 PM
..
2017-05-08 06:27 PM 16 .knownPackages
2017-05-06 08:54 PM
build-tools
2017-05-06 08:42 PM
emulator
2017-05-08 06:27 PM
extras
2017-05-06 08:47 PM
licenses
2017-05-06 08:42 PM
patcher
2017-05-06 08:42 PM
platform-tools
2017-05-06 08:56 PM platforms

2017-05-06 08:49 PM sources
2017-05-06 08:43 PM tools

linux - oprofile can not use hardware performance counters

I have debian 5.0 linux server on an IBM HS22 blade with 2 Xeon E5504 processors. I found out that oprofile could not recognize hardware performance counters on this setup, only timer interrupt is available:



# opcontrol -l
Using timer interrupt.
# cat /dev/oprofile/cpu_type
timer



System information is:



# cat /etc/issue.net 
Debian GNU/Linux 5.0
# uname -a
Linux xxx 2.6.26-2-686-bigmem #1 SMP Mon Jun 21 06:45:17 UTC 2010 i686 GNU/Linux



oprofile was installed from debian repository using apt.



# opcontrol --version
opcontrol: oprofile 0.9.3 compiled on Feb 10 2008 12:08:26


What should I do to enable hardware performance counters? Thanks!

Saturday, 29 October 2016

php - mysql_fetch_array()/mysql_fetch_assoc()/mysql_fetch_row()/mysql_num_rows etc... expects parameter 1 to be resource or result



I am trying to select data from a MySQL table, but I get one of the following error messages:




mysql_fetch_array() expects parameter 1 to be resource, boolean given





or




mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given




or




Call to a member function fetch_array() on boolean / non-object





This is my code:



$username = $_POST['username'];
$password = $_POST['password'];

$result = mysql_query('SELECT * FROM Users WHERE UserName LIKE $username');

while($row = mysql_fetch_array($result)) {

echo $row['FirstName'];
}


The same applies to code like



$result = mysqli_query($mysqli, 'SELECT ...');
// mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given
while( $row=mysqli_fetch_array($result) ) {
...



and



$result = $mysqli->query($mysqli, 'SELECT ...');
// Call to a member function fetch_assoc() on a non-object
while( $row=$result->fetch_assoc($result) ) {
...



and



$result = $pdo->query('SELECT ...', PDO::FETCH_ASSOC);
// Invalid argument supplied for foreach()
foreach( $result as $row ) {
...


and




$stmt = $mysqli->prepare('SELECT ...');
// Call to a member function bind_param() on a non-object
$stmt->bind_param(...);


and



$stmt = $pdo->prepare('SELECT ...');
// Call to a member function bindParam() on a non-object
$stmt->bindParam(...);


Answer



A query may fail for various reasons in which case both the mysql_* and the mysqli extension will return false from their respective query functions/methods. You need to test for that error condition and handle it accordingly.



mysql_* extension:




NOTE The mysql_ functions are deprecated and have been removed in php version 7.





Check $result before passing it to mysql_fetch_array. You'll find that it's false because the query failed. See the mysql_query documentation for possible return values and suggestions for how to deal with them.



$username = mysql_real_escape_string($_POST['username']);
$password = $_POST['password'];
$result = mysql_query("SELECT * FROM Users WHERE UserName LIKE '$username'");

if($result === FALSE) {
die(mysql_error()); // TODO: better error handling
}


while($row = mysql_fetch_array($result))
{
echo $row['FirstName'];
}


mysqli extension
procedural style:



$username = mysqli_real_escape_string($mysqli, $_POST['username']);
$result = mysqli_query($mysqli, "SELECT * FROM Users WHERE UserName LIKE '$username'");


// mysqli_query returns false if something went wrong with the query
if($result === FALSE) {
yourErrorHandler(mysqli_error($mysqli));
}
else {
// as of php 5.4 mysqli_result implements Traversable, so you can use it with foreach
foreach( $result as $row ) {
...



oo-style:



$username = $mysqli->escape_string($_POST['username']);
$result = $mysqli->query("SELECT * FROM Users WHERE UserName LIKE '$username'");

if($result === FALSE) {
yourErrorHandler($mysqli->error); // or $mysqli->error_list
}
else {

// as of php 5.4 mysqli_result implements Traversable, so you can use it with foreach
foreach( $result as $row ) {
...


using a prepared statement:



$stmt = $mysqli->prepare('SELECT * FROM Users WHERE UserName LIKE ?');
if ( !$stmt ) {
yourErrorHandler($mysqli->error); // or $mysqli->error_list

}
else if ( !$stmt->bind_param('s', $_POST['username']) ) {
yourErrorHandler($stmt->error); // or $stmt->error_list
}
else if ( !$stmt->execute() ) {
yourErrorHandler($stmt->error); // or $stmt->error_list
}
else {
$result = $stmt->get_result();
// as of php 5.4 mysqli_result implements Traversable, so you can use it with foreach

foreach( $result as $row ) {
...





These examples only illustrate what should be done (error handling), not how to do it. Production code shouldn't use or die when outputting HTML, else it will (at the very least) generate invalid HTML. Also, database error messages shouldn't be displayed to non-admin users, as it discloses too much information.


javascript - DOM manipulation in Angular directive after sub view rendering

I need a directive that will truncate long text in element and show a popover with full text in case truncation take place.



See http://plnkr.co/edit/90WP5ISQHG7FXRpetucm?p=preview


For text truncation I've used CSS and it works well.
But when I'm trying to access element content I see {{str.data}} rather then exact text from the data.



I guess that I need even't that is fired after rendering, but I can't fing any suitable.



So my question how can I run my DOM manipulation after sub view get rendered?



The only solution I've found so far is using timeout, but I think that there is better solution for it.

c++ - Malloc vs new -- different padding



I'm reviewing someone else's C++ code for our project that uses MPI for high-performance computing (10^5 - 10^6 cores). The code is intended to allow for communications between (potentially) different machines on different architectures. He's written a comment that says something along the lines of:




We'd normally use new and delete, but here I'm using malloc and free. This is necessary because some compilers will pad the data differently when new is used, leading to errors in transferring data between different platforms. This doesn't happen with malloc.





This does not fit with anything I know from standard new vs malloc questions.



What is the difference between new/delete and malloc/free? hints at the idea that the compiler could calculate the size of an object differently (but then why does that differ from using sizeof?).



malloc & placement new vs. new is a fairly popular question but only talks about new using constructors where malloc doesn't, which isn't relevant to this.



how does malloc understand alignment? says that memory is guaranteed to be properly aligned with either new or malloc which is what I'd previously thought.




My guess is that he's misdiagnosed his own bug some time in the past and deduced that new and malloc give different amounts of padding, which I think probably isn't true. But I can't find the answer with Google or in any previous question.



Help me, StackOverflow, you're my only hope!


Answer



IIRC there's one picky point. malloc is guaranteed to return an address aligned for any standard type. ::operator new(n) is only guaranteed to return an address aligned for any standard type no larger than n, and if T isn't a character type then new T[n] is only required to return an address aligned for T.



But this is only relevant when you're playing implementation-specific tricks like using the bottom few bits of a pointer to store flags, or otherwise relying on the address to have more alignment than it strictly needs.



It doesn't affect padding within the object, which necessarily has exactly the same layout regardless of how you allocated the memory it occupies. So it's hard to see how the difference could result in errors transferring data.




Is there any sign what the author of that comment thinks about objects on the stack or in globals, whether in his opinion they're "padded like malloc" or "padded like new"? That might give clues to where the idea came from.



Maybe he's confused, but maybe the code he's talking about is more than a straight difference between malloc(sizeof(Foo) * n) vs new Foo[n]. Maybe it's more like:



malloc((sizeof(int) + sizeof(char)) * n);


vs.



struct Foo { int a; char b; }

new Foo[n];


That is, maybe he's saying "I use malloc", but means "I manually pack the data into unaligned locations instead of using a struct". Actually malloc is not needed in order to manually pack the struct, but failing to realize that is a lesser degree of confusion. It is necessary to define the data layout sent over the wire. Different implementations will pad the data differently when the struct is used.


cors - AngularJS performs an OPTIONS HTTP request for a cross-origin resource




I'm trying to setup AngularJS to communicate with a cross-origin resource where the asset host which delivers my template files is on a different domain and therefore the XHR request that angular performs must be cross-domain. I've added the appropriate CORS header to my server for the HTTP request to make this work, but it doesn't seem to work. The problem is that when I inspect the HTTP requests in my browser (chrome) the request sent to the asset file is an OPTIONS request (it should be a GET request).



I'm not sure whether this is a bug in AngularJS or if I need to configure something. From what I understand the XHR wrapper can't make an OPTIONS HTTP request so it looks like the browser is trying to figure out if is "allowed" to download the asset first before it performs the GET request. If this is the case, then do I need to set the CORS header (Access-Control-Allow-Origin: http://asset.host...) with the asset host as well?


Answer



OPTIONS request are by no means an AngularJS bug, this is how Cross-Origin Resource Sharing standard mandates browsers to behave. Please refer to this document: https://developer.mozilla.org/en-US/docs/HTTP_access_control, where in the "Overview" section it says:




The Cross-Origin Resource Sharing standard works by adding new HTTP
headers that allow servers to describe the set of origins that are
permitted to read that information using a web browser. Additionally,

for HTTP request methods that can cause side-effects on user data (in
particular; for HTTP methods other than GET, or for POST usage with
certain MIME types). The specification mandates that browsers
"preflight" the request, soliciting supported methods from the server
with an HTTP OPTIONS request header, and then, upon "approval" from
the server, sending the actual request with the actual HTTP request
method. Servers can also notify clients whether "credentials"
(including Cookies and HTTP Authentication data) should be sent with
requests.





It is very hard to provide a generic solution that would work for all the WWW servers as setup will vary depending on the server itself and HTTP verbs that you intend to support. I would encourage you to get over this excellent article (http://www.html5rocks.com/en/tutorials/cors/) that has much more details on the exact headers that needs to be sent by a server.


How to set cursor color in bash shell




I have found that I can get my cursor to blink by including the following instruction in my .bashrc file:




echo -ne "\x1b[1 q"


But I also want to change the color of the blinking cursor. I know that my terminal supports color because I can set the prompt colors and print text in color, but I just can't change the cursor color. Any suggestions?



I'm adding the following comment, that I'm aware of how to change the color of text that is displayed on the terminal, but that is not the same as changing the color of the the cursor. So my question is not addressed in that other question.



But I did find a workaround in my terminal emulator software, provided below.
Thanks for the feedback, especially the part about making the selection of the proper escape codes portable across terminal types.



Answer



I found afterwards that I can change the cursor color, not in bash, but in the terminal emulator program. In my case that program is MobaXTerm. I discovered the following sequence: Settings - Terminal - Cursor. At that point, selecting a cursor color causes the cursor in the bash shell to be displayed in the desired color. So now in the files that I edit using vim in the bash environment in my xterm window I see a blinking green block cursor, which is what I needed.



Please check the following short demonstration clip: Blinking Green Block Cursor in bash and vim



Attaining that was what my question was about, not about how to display colored text on the screen, which as was pointed out is already answered elsewhere. So my question is not a duplicate. Anyway, it turned out that my xterm emulation software Mobaxterm allowed me to set the cursor color whereas the escape sequence in my .bashrc file allowed me to get it to blink.


jquery if variable in a list of values

I have some jquery checking the choice made in a drop down.



function toggleFields() {
if ($("#chosenmove1").val() == 4)
$("#hideme").show();
else

$("#hideme").hide();
}


This works fine but I would like to change it so it checks a list of values like



if ($("#chosenmove1").val() in (3,4,5))


How can I write this to make it work (the above doesn't)




Tried a bit more



var arr = [3,4,5];
var value = $("#chosenmove1").val();
alert(value);

if ($.inArray(value, arr) > -1)
$("#hideme").show();
else

$("#hideme").hide();

}


The alert box tells me var value is getting the right value from the drop down - yet the show hide wont work under this setup.
IF I replace var value = $("#chosenmove1").val(); with
var value = 3; then it does work?

JavaScript function that returns AJAX call data





I would like to create a JavaScript function which returns the value of a jQuery AJAX call. I would like something like this.



function checkUserIdExists(userid){
return $.ajax({
url: 'theurl',
type: 'GET',

cache: false,
data: {
userid: userid
},
success: function(data){
return data;
}
});
}



I know I can do this by setting async to false but I would rather not.


Answer



With jQuery 1.5, you can use the brand-new $.Deferred feature, which is meant for exactly this.




// Assign handlers immediately after making the request,
// and remember the jqxhr object for this request
var jqxhr = $.ajax({ url: "example.php" })
.success(function() { alert("success"); })

.error(function() { alert("error"); })
.complete(function() { alert("complete"); });

// perform other work here ...

// Set another completion function for the request above
jqxhr.complete(function(){ alert("second complete"); });




Source


javascript - AngularJS load service then call controller and render




My problem is that i need a service loaded before the controller get called and the template get rendered.
http://jsfiddle.net/g75XQ/2/



Html:




Do not render this before user has loaded


{{user}}





JavaScript:



angular.module('app', []).
factory('user',function($timeout,$q){
var user = {};
$timeout(function(){//Simulate a request
user.name = "Jossi";

},1000);
return user;
}).
controller('root',function($scope,user){

alert("Do not alert before user has loaded");
$scope.user = user;

});





Answer



You can defer init of angular app using manual initialization, instead of auto init with ng-app attribute.



// define some service that has `$window` injected and read your data from it
angular.service('myService', ['$window', ($window) =>({
getData() {
return $window.myData;

}
}))

const callService = (cb) => {
$.ajax(...).success((data)=>{
window.myData = data;
cb(data)
})
}


// init angular app
angular.element(document).ready(function() {
callService(function (data) {
doSomething(data);
angular.bootstrap(document);
});
});


where callService is your function performing AJAX call and accepting success callback, which will init angular app.




Also check ngCloak directive, since it maybe everything you need.



Alternatively, when using ngRoute you can use resolve property, for that you can see @honkskillet answer


Awkward way of executing JavaScript code




In the Google tutorial for implementing Google+ sign-in in Flask application, I discovered that the developer often uses an awkward way of executing JavaScript code:



Instead of doing



var a = foo(bar);


I see this:



var a = (function() {
return foo(bar);
})();


What is the reason to do it the weird way?


Answer



This is a poor example. Consider the following:



var a = (function(){
var ret = {};
ret.test = "123";
function imPrivate() { /* ... */ }
ret.public = function() { imPrivate(); }
return ret;
})();


a will contain the varible test and the function public, however you can not access imPrivate. This is the common way to handle public vs private variables;



See Why is this function wrapped in parentheses, followed by parentheses? for more info.


PHP/MySQLi: Update / Insert with prepared queries doesnt persist into database

i have some problemes with mysql prepared queries. Especially UPDATE and INSERT.



$mysqliStmt->execute();


does NOT update or insert into a table. It just delivers stmt results. There are no errors, warnings or anything else. (see below)




I hope somebody knows what im doing wrong :)



The Insert query i use:



INSERT INTO testdatabase.`test` (`test1`, `test2`) VALUES(?, ?)


The Update query:



UPDATE testdatabase.`test` SET `test1` = ? WHERE `id` = ? LIMIT 1



Resultinformation (update):



'fieldCount' => 0,
'affectedRows' => 1,
'numRows' => 0,
'paramCount' => 2,
'insertId' => 0,
'sqlstate' => '00000',

'threadId' => 5291,
'errno' => 0,
'error' => '',
'warningCount' => 0,
'warnings' => false
'connectErrno' => 0,
'connectError' => NULL,
'hostInfo' => 'Localhost via UNIX socket',
'protocolVersion' => 10,
'serverInfo' => '5.1.49-3',

'serverVersion' => 50149,
'clientInfo' => '5.0.27',
'clientVersion' => 50027,
'info' => 'Rows matched: 1 Changed: 1 Warnings: 0'


The code:



$stmt = self::$_connection->prepare($query);
//binds params -> like/with $stmt::bind_param() but more generic

$this->_bindParameters($stmt)
$stmt->execute();


Now the update/insert data should be stored into database or im wrong?



If i use phpmyadmin or mysql console to verify the results of the queries, the database table was neither updated nor was the new data inserted.



Thank you for your help :)

Getting special characters out of a MySQL database with PHP




I have a table that includes special characters such as ™.



This character can be entered and viewed using phpMyAdmin and other software, but when I use a SELECT statement in PHP to output to a browser, I get the diamond with question mark in it.



The table type is MyISAM. The encoding is UTF-8 Unicode. The collation is utf8_unicode_ci.



The first line of the html head is







I tried using the htmlentities() function on the string before outputting it. No luck.



I also tried adding this to php before any output (no difference):



header('Content-type: text/html; charset=utf-8');



Lastly I tried adding this right below the initial mysql connection (this resulted in additional odd characters being displayed):



$db_charset = mysql_set_charset('utf8',$db);


What have I missed?


Answer



Below code works for me.




$sql = "SELECT * FROM chartest";
mysql_set_charset("UTF8");
$rs = mysql_query($sql);
header('Content-type: text/html; charset=utf-8');
while ($row = mysql_fetch_array($rs)) {
echo $row['name'];
}

In C++, when reassigning an object, why does the constructor fire before the destructor?

I'm a beginner in C++. I'm compiling my code with GCC 9.2.0. Recently I've stumbled upon some weird behaviour which is segfaulting me.



I have a certain class wrapper for Hyperscan. I've made it so it basically has the same functionality as Python's re, but many times faster and multithreaded. I have a class regex which I usually allocate like



auto some_regex = regex();



Now, the what the constructor does, for those of you unfamiliar with Hyperscan is 2 (actually 3) things -> first it allocated memory for the regular expression database. This is done by calling their API, which is in C. Then, if it succeeds, you allocate scratch space. Now, because my implementation supports multithreading, my class instance holds a member which is a vector of scratch spaces. Nevertheless, I allocated a scratch space for each thread I use, also with their API. What I then have are a pointer to the compiled regex database and a vector of scratch space pointers.



When deconstructing the object, I have to free the database and scratch spaces (I also use the provided functions from the API) if they're allocated. So far so good. The problem arises when I do something like this:



auto some_regex = regex();
some_regex = regex(R"(\s+)");



Do you see a problem here? Maybe I'm too much of a noob to see it, but it looks good to me. But nope. It segfaults in the destructor while trying to free the database memory. Debugging it, I have come across these actions:



allocate memory for some_regex
initialize some_regex
allocated new memory for some_regex
initialize new some_regex
run destructor for the old some_regex
run destructor for the new some_regex



Basically, the destructor for the first instance is run only after the constructor for the second one fires. What this does is essentially making it so that the first destructor frees up the data allocated and initialized by the second constructor instead of just cleaning itself.



Now, things get weirder. I looked into the addresses at hand, because I started setting the freed up pointers to nullptr - it turns out that this happens:



allocate memory for some_regex
initialize some_regex
allocated new memory for some_regex
initialize new some_regex
run destructor for the old some_regex
database pointer is not 0, free it

set database pointer to nullptr
run destructor for the new some_regex
database pointer is not 0, free it (BUT THIS IS ALREADY FREED MEMORY???)
SIGSEGV


I'm utterly confused. Even after setting the database pointer to null explicitly, the new one, after the constructor did its job, assigns it a new address.



This reproduces the behaviour:




#include 
#include

mock::mock()
{
std::cout << "Starting constructor..." << std::endl;
this->test = (int*)malloc(sizeof(int));
*this->test = 0;
std::cout << "Ending constructor..." << std::endl;
}


mock::mock(int x)
{
std::cout << "Starting full constructor..." << std::endl;
this->test = (int*)malloc(sizeof(int));
*this->test = x;
std::cout << "Ending full constructor..." << std::endl;
}

mock::~mock()

{
std::cout << "Starting destructor...";
free(this->test);
this->test = nullptr;
std::cout << "Address of test is " << this->test << std::endl;
std::cout << "Ending destructor..." << std::endl;
}


run it in main like this:




auto some_mock = mock();
some_mock = mock();
some_mock = mock();
some_mock = mock(3);



Expected result:




Starting constructor...
Ending constructor...
Starting destructor...Address of test is 0
Ending destructor...
Starting constructor...
Ending constructor...
Starting destructor...Address of test is 0
Ending destructor...
Starting constructor...
Ending constructor...

Starting destructor...Address of test is 0
Ending destructor...
Starting full constructor...
Ending full constructor...
Starting destructor...Address of test is 0
Ending destructor...
Process returned 0


Actual result:




Starting constructor...
Ending constructor...
Starting constructor...
Ending constructor...
Starting destructor...Address of test is 0
Ending destructor...
Starting constructor...
Ending constructor...
Starting destructor...Address of test is 0

Ending destructor...
Starting full constructor...
Ending full constructor...
Starting destructor...Address of test is 0
Ending destructor...
*** Error in `/deploy/cmake-build-local-debug/CPP': double free or corruption (fasttop): 0x0000000002027c40 ***
.
.
.
Starting destructor...

Process finished with exit code 134 (interrupted by signal 6: SIGABRT)


Is this intended behaviour? If so, why??? And how can I get around it (aside from using new and deleting before reassigning)?

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


Alias:

@Html.TextBox(Model.Alias)



Blog Archive