Sunday, September 30, 2018

html - Bootstrap select dropdown list placeholder

I think, the Dropdown box with a class and JQuery code to disable the first option for user to select, will work perfectly as Select Box placeholder.




Make the first option disabled by JQuery.




This will make the first option of Dropdown as Placeholder and user will no longer able to select the first option.


Hope It helps!!

looping through javascript nested objects in html displays [object object]?

I am trying to loop through a Javascript object to display the contents on the html page. The contents is from an API that has ben parsed into javascript Object. The loop works fine but every solution i come up with either gives me nothing in the html or display [object object][object object]



I have no idea why it keeps displaying this or how to get it displaying correctly.



The data held being got from the api call



[{"id":"68343","order_id":"77348","customer_id":"2","number":"1"}, 
{"id":"68344","order_id":"77348","customer_id":"2","number":"1"},

{"id":"68342","order_id":"77348","customer_id":"3","number":"1"}]


I get the data and parse



function(data){
var result = JSON.parse(data);
if(result.status == "success")
{
//need to loop through all data so that it displays in a html div



}


}


So i have tried the for loop:-




for (var objProp in result){
for (var obj in result[objProp]){

document.getElementById("orderItem").innerHTML = result[objProp]
[obj];
}
}


displays [object object]




another for loop



for (var key in result){
document.getElementById("orderItem").innerHTML =result[key];}


getting a single item back is ok



document.getElementById("orderItem").innerHTML = result.data[0].id;

java - Reading textfile with Scanner results in 'InputMismatchException'

Using parseInt() and parseDouble() methods in combination with nextLine() method will solve your problem. I have written some code:


public class Person{
private String name;
private String gender;
private int age;
private double weight;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
}

and


import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class PersonTest {
public static void main(String[] args) throws FileNotFoundException {
File inputFile = new File("data.txt");
Scanner sc = new Scanner(inputFile);
ArrayList peopleList = new ArrayList();
Person p;
while (sc.hasNext()){
p = new Person();
p.setName(sc.nextLine());
System.out.println(p.getName());
p.setGender(sc.nextLine());
System.out.println(p.getGender());
p.setAge(Integer.parseInt(sc.nextLine()));
System.out.println(p.getAge());
p.setWeight(Double.parseDouble(sc.nextLine()));
System.out.println(p.getWeight());
peopleList.add(p);
}
sc.close();
}
}

I think the problem why your code didn't work is that after nextDouble() found 85.83, the scanner skipped that number and was still at 4th line. When you called nextLine() in the second loop, it returned the rest of 4th line, which was blank.
Using my solution, you can take a full line and then easily convert it to integer number or double number.

python - relative path not working even with __init__.py



I know that there are plenty of similar questions on . But the common answer doesn't seem to be working for me.



I have a file structure like this



  proj/
lib/
__init__.py
aa.py

bb.py
test/
__init__.py
aa_test.py


I figured that if I include the code in my test.py



import lib.aa



or



from lib import aa


I would be able to reference the modules in the lib/ directory. But that did not work.



So I tried to add to path, and it adds it correctly:




os.environ["PATH"] += ":%s" % os.path.abspath(os.path.join("..",""))
print os.environ["PATH"]


but even now when I try the import statements above... I keep getting the error



ImportError: No module named aa


or




ImportError: Importing from non-package 


Is there something obvious I am missing?



Is there a way to check if I have configured my __init__.py files correctly, or to see my package hierarchy?


Answer



You need to update your sys.path, which is where python looks for modules, as opposed to your system's path in the current environment, which is what os.environ["PATH"] is referring to.




Example:



import os, sys
sys.path.insert(0, os.path.abspath(".."))
import aa


After doing this, you can use your functions in aa like this: aa.myfunc()



There's some more information in the accepted answer for python: import a module from a directory



python - Python3 - Generate string matching multiple regexes, without modifying them

Answer


Answer




I would like to generate string matching my regexes using Python 3. For this I am using handy library called rstr.






  • ^[abc]+.

  • [a-z]+






I must find a generic way, how to create string that would match both my regexes.





Modify both regexes or join them in any way. This I consider as ineffective solution, especially in the case if incompatible regexes:




import re
import rstr

regex1 = re.compile(r'^[abc]+.')
regex2 = re.compile(r'[a-z]+')

for index in range(0, 1000):
generated_string = rstr.xeger(regex1)
if re.fullmatch(regex2, generated_string):
break;

else:
raise Exception('Regexes are probably incompatibile.')

print('String matching both regexes is: {}'.format(generated_string))


Is there any workaround or any magical library that can handle this? Any insights appreciated.








Asker already has the string, which he just want to check against multiple regexes in the most elegant way. In my case we need to generate string in a smart way that would match regexes.


Answer



I solved this using a little alternative approach. Notice second regex is basically insurance so only lowercase letters are generated in our new string.



I used Google's python package sre_yield which allows charset limitation. Package is also available on PyPi. My code:



import sre_yield
import string


sre_yield.AllStrings(r'^[abc]+.', charset=string.ascii_lowercase)[0]
# returns `aa`

html - Send mail by php mail() function

I have problem with sending mail message by php mail() function. I'm not sure if it's problem with code coz I have read that some hosting servers are not allowing to sends mail but I'm trying to send this mail also when website is on localhost and it still doesn't work - after click "Send" I see the information: "Your mail is sent", but when I'm checking on my postbox there is no mails (also in spam).



For me code looks good but maybe I'm missing something. The second option which I'm considering is that also my localhost is not allowing to send mails.

























srand((double)microtime()*1000000);

$marker = md5(uniqid(rand()));

$receiver = "address@gmail.com";
$title = "Mail";
$sender = $_POST['name'];
$sender .= $_POST['surname'];
$sender_mail = $_POST['mail'];

$message = $_POST['message'];


$headers = "From: $sender <$sender_mail>\n";
$headers .= "MIME-Version: 1.0\n";
$headers .= "Content-Type: multipart/mixed;\n";
$headers .= "\tboundary=\"___$marker==\"";

$content ="--___$marker==\n";
$content .="Content-Type: text/plain; charset=\"iso-8859-2\"\n";
$content .="Content-Transfer-Encoding: 8bit\n";
$content .="\n$message\n";


if (mail($receiver,$title,$content,$headers))
{
print "Your message is sent.";
} else {
print "Your message is not sent.

Please go back and send again.";
}
?>



Pictures with my php conf:



PHP config
PHP config
PHP config

javascript - if sentence contains string




If a sentence contains "Hello World" (no quotes) then I need to return true and do something. Possible sentences could be like this:



var sentence = "This is my Hello World and I like widgets."
var sentence = "Hello World - the beginning of all"
var sentence = "Welcome to Hello World"

if ( sentence.contains('Hello World') ){
alert('Yes');
} else {

alert('No');
}


I know the .contains does not work, so I'm looking for something does work. Regex is the enemy here.


Answer



The method you're looking for is indexOf (Documentation). Try the following



if (sentence.indexOf('Hello World') >= 0) { 
alert('Yes');

} else {
alert('No');
}

java - Regex for splitting a string using space when not surrounded by single or double quotes

Answer


Answer




I'm new to regular expressions and would appreciate your help. I'm trying to put together an expression that will split the example string using all spaces that are not surrounded by single or double quotes. My last attempt looks like this: (?!") and isn't quite working. It's splitting on the space before the quote.



Example input:




This is a string that "will be" highlighted when your 'regular expression' matches something.


Desired output:



This
is
a
string

that
will be
highlighted
when
your
regular expression
matches
something.



Note that "will be" and 'regular expression' retain the space between the words.


Answer



I don't understand why all the others are proposing such complex regular expressions or such long code. Essentially, you want to grab two kinds of things from your string: sequences of characters that aren't spaces or quotes, and sequences of characters that begin and end with a quote, with no quotes in between, for two kinds of quotes. You can easily match those things with this regular expression:



[^\s"']+|"([^"]*)"|'([^']*)'


I added the capturing groups because you don't want the quotes in the list.



This Java code builds the list, adding the capturing group if it matched to exclude the quotes, and adding the overall regex match if the capturing group didn't match (an unquoted word was matched).




List matchList = new ArrayList();
Pattern regex = Pattern.compile("[^\\s\"']+|\"([^\"]*)\"|'([^']*)'");
Matcher regexMatcher = regex.matcher(subjectString);
while (regexMatcher.find()) {
if (regexMatcher.group(1) != null) {
// Add double-quoted string without the quotes
matchList.add(regexMatcher.group(1));
} else if (regexMatcher.group(2) != null) {
// Add single-quoted string without the quotes

matchList.add(regexMatcher.group(2));
} else {
// Add unquoted word
matchList.add(regexMatcher.group());
}
}


If you don't mind having the quotes in the returned list, you can use much simpler code:




List matchList = new ArrayList();
Pattern regex = Pattern.compile("[^\\s\"']+|\"[^\"]*\"|'[^']*'");
Matcher regexMatcher = regex.matcher(subjectString);
while (regexMatcher.find()) {
matchList.add(regexMatcher.group());
}

.net - Get executing assembly name from referenced DLL in C#



What is the best way to get the application name (i.e MyApplication.exe) of the executing assembly from a referenced class library in C#?



I need to open the application's app.config to retrieve some appSettings variables for the referenced DLL.



Answer



If you want to get the current appdomain's config file, then all you need to do is:



ConfigurationManager.AppSettings....



(this requires a reference to System.Configuration of course).



To answer your question, you can do it as Ray said (or use Assembly.GetExecutingAssembly().FullName) but I think the problem is easier solved using ConfigurationManager.


analysis - What happens to Alex at the end of Shallow Grave? - Movies & TV



At the end of the movie it was not obvious to me what Alex's ultimate fate was. In particular, I wasn't clear whether he lived or died from his injury. It seemed like he might live, as he was still moving a bit, but everyone around him seemed completely unconcerned with getting him medical attention. I even considered the possibility that he was dead at the time of the ending, and we were just seeing him move, but the people in movie were just seeing him as dead.



Is it made clear at some point? Is it purposely ambiguous? Or was I just missing the obvious?



Answer



It is interesting, as I never assumed that Alex was dead, or even thought that this was ambiguous. Only reading this question made me realize the discussion around this point.



Yes it is surprising that the photographer was taking pictures of him whilst he lies there injured, but (following a quick check on youtube) he is clearly moving his head and facial expressions whilst this is going on - and smiling at the thought of the bag full of fake money that Juliet has taken after hammering the knife into him with her shoe. Yes he has lost a lot of blood, but to my mind it is looking like they are awaiting paramedics to arrive.



I think that the Director is not always authoritative when it comes to interpreting a movie - but certainly the director's opinion about the intention of a scene or shot is important to consider - and Danny Boyle has been clear that he intended Alex to survive the movie (Commentary on Special Edition DVD).


plot - Plotting time graph in MATLAB

I have a function of this form in MATLAB,




C=S*e^(L*t)*inv(S)*C_0


where my



     S=[-2 -3;3 -2] 
L=[0.5 0; 0 1.5]
C_0=[1; 1]



I need to plot this function with respect to time. My output C is a 2-by-1 matrix.



What I have done is computed e^L separately using b=expm(L) and then I inserted mpower(b,t) into the function. So my resulting function in the script looks like



  b=expm(L);
C=S*mpower(b,t)*inv(S)*C_0;


Now, how should I go about plotting this w.r.t time. I tried defining the time vector and then using it, but quite obviously I get the error message which says matrix dimensions do not agree. Can someone give me a suggestion?

android - "Attempt to invoke virtual method on a null object reference" when trying to getLayoutParams of a CardView in a DialogFragment?

I'm trying to set the size of a CardView inside of a DialogFragment, but I get this error:





java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.ViewGroup$LayoutParams android.support.v7.widget.CardView.getLayoutParams()' on a null object reference




This is my code:



        CardView cardView;
onCreate(...){
cardView = (CardView) findViewById(R.id.cardViewInDialogFragment);
}


private void openDialogFragment() {

DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);

BlankFragment blankFragment = new BlankFragment();
blankFragment.show(getSupportFragmentManager(),"blankFragment");

CardView.LayoutParams layoutParams = (CardView.LayoutParams) cardView.getLayoutParams();

layoutParams.height = displayMetrics.heightPixels - 20;
layoutParams.width = displayMetrics.widthPixels - 20;
cardView.setLayoutParams(layoutParams);
}


Is it not possible or am I doing something wrong?



UPDATE:
The cardView is inside the fragment.




UPDATE 2:



When changing the code to bellow:



BlankFragment:



public static View view;
pulic void onCreateView(...) {


view = inflater.inflate(R.layout.fragment_blank, container, false);
return view;
}


MainActivity:



CardView cardView;
protected void onCreate(...){
...


cardView = (CardView) BlankFragment.view.findViewById(R.id.cardViewInDialogFragment);
openDialogFragment();
}

private void openDialogFragment() {

DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);


BlankFragment blankFragment = new BlankFragment();
blankFragment.show(getSupportFragmentManager(),"blankFragment");

CardView.LayoutParams layoutParams = (CardView.LayoutParams) cardView.getLayoutParams();
layoutParams.height = displayMetrics.heightPixels - 20;
layoutParams.width = displayMetrics.widthPixels - 20;
cardView.setLayoutParams(layoutParams);
}



, I get this error:




FATAL EXCEPTION: main
Process: com.sim.buttombarnavigationandfragment, PID: 10685
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.sim.buttombarnavigationandfragment/com.sim.buttombarnavigationandfragment.MainActivity}:
java.lang.NullPointerException: Attempt to invoke virtual method
'android.view.View android.view.View.findViewById(int)' on a null
object reference

at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2680)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2741)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1488)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6176)

at java.lang.reflect.Method.invoke(Native Method)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:888)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:778)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual
method 'android.view.View android.view.View.findViewById(int)' on a
null object reference
at
com.sim.buttombarnavigationandfragment.MainActivity.onCreate(MainActivity.java:56)
at android.app.Activity.performCreate(Activity.java:6679)

at
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2633)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2741) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1488) 
at android.os.Handler.dispatchMessage(Handler.java:102) 

at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6176) 
at java.lang.reflect.Method.invoke(Native Method) 
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:888) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:778)


javascript - How do I convert an existing callback API to promises?



I want to work with promises but I have a callback API in a format like:




1. DOM load or other one time event:



window.onload; // set to callback
...
window.onload = function() {

};


2. Plain callback:




function request(onChangeHandler) {
...
}
request(function() {
// change happened
...
});



3. Node style callback ("nodeback"):



function getStuff(dat, callback) {
...
}
getStuff("dataParam", function(err, data) {
...
})



4. A whole library with node style callbacks:



API;
API.one(function(err, data) {
API.two(function(err, data2) {
API.three(function(err, data3) {
...
});
});
});



How do I work with the API in promises, how do I "promisify" it?


Answer



Promises have state, they start as pending and can settle to:




  • fulfilled meaning that the computation completed successfully.

  • rejected meaning that the computation failed.




Promise returning functions should never throw, they should return rejections instead. Throwing from a promise returning function will force you to use both a } catch { and a .catch. People using promisified APIs do not expect promises to throw. If you're not sure how async APIs work in JS - please see this answer first.



1. DOM load or other one time event:



So, creating promises generally means specifying when they settle - that means when they move to the fulfilled or rejected phase to indicate the data is available (and can be accessed with .then).



With modern promise implementations that support the Promise constructor like native ES6 promises:



function load() {

return new Promise(function(resolve, reject) {
window.onload = resolve;
});
}


You would then use the resulting promise like so:



load().then(function() {
// Do things after onload

});


With libraries that support deferred (Let's use $q for this example here, but we'll also use jQuery later):



function load() {
var d = $q.defer();
window.onload = function() { d.resolve(); };
return d.promise;
}



Or with a jQuery like API, hooking on an event happening once:



function done() {
var d = $.Deferred();
$("#myObject").once("click",function() {
d.resolve();
});
return d.promise();

}


2. Plain callback:



These APIs are rather common since well… callbacks are common in JS. Let's look at the common case of having onSuccess and onFail:



function getUserData(userId, onLoad, onFail) { …



With modern promise implementations that support the Promise constructor like native ES6 promises:



function getUserDataAsync(userId) {
return new Promise(function(resolve, reject) {
getUserData(userId, resolve, reject);
});
}


With libraries that support deferred (Let's use jQuery for this example here, but we've also used $q above):




function getUserDataAsync(userId) {
var d = $.Deferred();
getUserData(userId, function(res){ d.resolve(res); }, function(err){ d.reject(err); });
return d.promise();
}


jQuery also offers a $.Deferred(fn) form, which has the advantage of allowing us to write an expression that emulates very closely the new Promise(fn) form, as follows:




function getUserDataAsync(userId) {
return $.Deferred(function(dfrd) {
getUserData(userId, dfrd.resolve, dfrd.reject);
}).promise();
}


Note: Here we exploit the fact that a jQuery deferred's resolve and reject methods are "detachable"; ie. they are bound to the instance of a jQuery.Deferred(). Not all libs offer this feature.



3. Node style callback ("nodeback"):




Node style callbacks (nodebacks) have a particular format where the callbacks is always the last argument and its first parameter is an error. Let's first promisify one manually:



getStuff("dataParam", function(err, data) { …


To:



function getStuffAsync(param) {
return new Promise(function(resolve, reject) {

getStuff(param, function(err, data) {
if (err !== null) reject(err);
else resolve(data);
});
});
}


With deferreds you can do the following (let's use Q for this example, although Q now supports the new syntax which you should prefer):




function getStuffAsync(param) {
var d = Q.defer();
getStuff(param, function(err, data) {
if (err !== null) d.reject(err);
else d.resolve(data);
});
return d.promise;
}



In general, you should not promisify things manually too much, most promise libraries that were designed with Node in mind as well as native promises in Node 8+ have a built in method for promisifying nodebacks. For example



var getStuffAsync = Promise.promisify(getStuff); // Bluebird
var getStuffAsync = Q.denodeify(getStuff); // Q
var getStuffAsync = util.promisify(getStuff); // Native promises, node only


4. A whole library with node style callbacks:



There is no golden rule here, you promisify them one by one. However, some promise implementations allow you to do this in bulk, for example in Bluebird, converting a nodeback API to a promise API is as simple as:




Promise.promisifyAll(API);


Or with native promises in Node:



const { promisify } = require('util');
const promiseAPI = Object.entries(API).map(([key, v]) => ({key, fn: promisify(v)}))
.reduce((o, p) => Object.assign(o, {[p.key]: p.fn}), {});



Notes:




  • Of course, when you are in a .then handler you do not need to promisify things. Returning a promise from a .then handler will resolve or reject with that promise's value. Throwing from a .then handler is also good practice and will reject the promise - this is the famous promise throw safety.

  • In an actual onload case, you should use addEventListener rather than onX.


php - Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE



I might have a syntax error or something but I don't see nothing.






On the echo line, I have the error :





[error] [client] PHP Parse error: syntax error, unexpected
T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or
T_NUM_STRING in /var/www/slimtest/views/nuevo.php on line 89




Maybe you can help, because I don't see the error D"=


Answer



This should work:






r - How to truncate the CI limits to the y range of the plot using stat_smooth

I am trying to use stat_smooth() to draw the confidence interval around a fitted line, e.g.:



Days <- c(rep(0,2),rep(10,4))
Resp <- c(1020, 955, 1599, 1220, 1264, 1273)
DummySet <- as.data.frame(cbind(Days,Resp))

a <- ggplot(data=DummySet, aes(Days, Resp))
a <- a + stat_smooth(method="lm", formula = y ~ x)

a


No y-limits



That's fine, but I face 2 problems when limiting the range of the y-axis. First, the CI shading is interrupted (instead of truncated) at the y-limit:



a <- a + ylim(c(800,1600))



Y Limits 800-1600



Second, if some points are outside of the y-range, they seem to be ignored for calculations (here 1599 seems to be ignored):



a <- a + ylim(c(800,1400))


Y Limits 800-1400



Instead, what I would like to see is the same as in the first graphic, only with truncated CI:

CI truncated



The problem may not be related to stat_smooth() but to a general misunderstanding of ggplot2, to which I am a newbie. Any hint would be appreciated.

identify this movie - Psychological thriller in which the verse "My father was a penny" keeps recurring on a wall?



I dont recall much of that movie except that it was a psychological thriller, and a verse was scribbled on a dilapidated wall. In one scene, the villain impersonates a nurse and escapes from the lunatic asylum or some place where he was confined. I dont recall much else so am sorry for the vague details.


Answer


I think the phrase that you're looking for is "My daddy is a dollar / I wrote it on a fence / My daddy is a dollar / not worth a hundred cents."


I am pretty sure this is the movie because this is what the killer keeps on writing on the asylum. The movie is In Dreams and I think its very much similiar to the type of the movie you mentioned about. It has the same scene where killer when he was a kid escapes the asylum in the disguise of a nurse who works there.


Here is the youtube trailer. Hoping this is the one you are seeking.


Check for file existence in C++ without creating file

I want to check if a file exists and tried to use the following function



#include 

bool DoesFileExist(const std::string& filename) {
std::ifstream ifile(filename.c_str());
return (bool)ifile;
}



However, it does not seem to work properly, because instead of checking the existence a file is created! What's the problem here?



Note that I'm forced to use C++98 standard and cannot use #include or #include as suggested in the accepted answer here.

horror - Cultural Basis of Asian Ghost Lady - Movies & TV



In a lot of Asian horror movies (particularly Japanese ones) a common motif is the ghost lady in white, with long black hair covering her face. The wide spread use of this image has led me to wonder if there's a cultural background to her in Asian horror folklore?


Answer



TV Tropes provides a good starting point on the subject:





An entity often seen in Japanese horror movies is a ghost, usually that of a young woman, with long, stringy black hair that covers her face, clad in a white burial kimono or shroud. Her face itself is often quite ghastly to look upon.



This is actually a type of ghost known as an onryo, the ghost of a young woman who was greatly wronged by a man in life and now seeks vengeance on the living. Strangely enough, the man who actually did the wronging is often left untouched by the onryo, which is probably perceived as the way it should be in the traditionally male-dominated Japanese society...




Wikipedia sidenote:





In some Asian and Slavic cultures, white is considered to be a color that represents death.




Which is why they're wearing white.



Now on to Wikipedia to learn about the appearance of the Onryo, which TV Tropes mentioned:




Traditionally [citation needed], onryō and other yūrei had no particular appearance. However, with the rising of popularity of Kabuki during the Edo period, a specific costume was developed.




Highly visual in nature, and with a single actor often assuming various roles within a play, Kabuki developed several visual shorthands that allowed the audience to instantly clue in as to which character is on stage, as well as emphasize the emotions and expressions of the actor.



A ghost costume consisted of three main elements:




  • White burial kimono

  • Wild, unkempt long black hair

  • White and indigo face make-up called aiguma.





Unfortunately, that part of the Wikipedia article is entirely unsourced, so I can't speak to the veracity of these claims. Wikipedia also states the origins of the Onryo trace back to 8th century, but doesn't have a source for that either.






Tonight's Saturday Night Live, provided a new clue for me. A skit refers to this trope as a "mool-gwishin 물귀신" (that's the Korean written language), which some googling got to a few separate descriptions that mention the long haired, white robed ghost. Wikipedia's article on Gwishin (귀신) states:




Gwishin are usually transparent, legless and float in mid-air. Old gwishin usually have white Hanbok (한복) which are worn for funerals. They have long, drooping black hair and sometimes they are faceless, depending on their personality. Male gwishin are somewhat rare, but they're like female ghosts, except female gwishin are more often heard.





So Korea has similar ghost legends that match the Onryo's description. The summary for the gwishin (귀신) article provides some background detail on them:




Gwishin (귀신) are Korean ghosts who are similar to a Yogwi (요괴); they are people who have died, not monsters or creatures such as Dokkaebi. They can be found in many places, but are commonly in abandoned buildings, houses, cemeteries, forests, etc. When a person who dies without completing something that they must do (e.g. revenge or staying longer with their family), their spirit remains on earth to complete the task before going on to the underworld. However, very strong gwishin do not go to the underground world if they want to remain on earth, and over time these gain strength.




So, one of the reasons gwishin (귀신) are around is to seek revenge, another similarity with the Onryo. This looks like Korea has similar legends as Japan, which helps confirm this is an Asian ghost legend.


c# - What is a NullReferenceException, and how do I fix it?





I have some code and when it executes, it throws a NullReferenceException, saying:




Object reference not set to an instance of an object.




What does this mean, and what can I do to fix this error?



Answer





Bottom Line



You are trying to use something that is null (or Nothing in VB.NET). This means you either set it to null, or you never set it to anything at all.



Like anything else, null gets passed around. If it is null in method "A", it could be that method "B" passed a null to method "A".



null can have different meanings:





  1. Object variables which are uninitialized and hence point to nothing. In this case, if you access properties or methods of such objects, it causes a NullReferenceException.

  2. The developer is using null intentionally to indicate there is no meaningful value available. Note that C# has the concept of nullable datatypes for variables (like database tables can have nullable fields) - you can assign null to them to indicate there is no value stored in it, for example int? a = null; where the question mark indicates it is allowed to store null in variable a. You can check that either with if (a.HasValue) {...} or with if (a==null) {...}. Nullable variables, like a this example, allow to access the value via a.Value explicitly, or just as normal via a.
    Note that accessing it via a.Value throws an InvalidOperationException instead of a NullReferenceException if a is null - you should do the check beforehand, i.e. if you have another on-nullable variable int b; then you should do assignments like if (a.HasValue) { b = a.Value; } or shorter if (a != null) { b = a; }.



The rest of this article goes into more detail and shows mistakes that many programmers often make which can lead to a NullReferenceException.



More Specifically




The runtime throwing a NullReferenceException always means the same thing: you are trying to use a reference, and the reference is not initialized (or it was once initialized, but is no longer initialized).



This means the reference is null, and you cannot access members (such as methods) through a null reference. The simplest case:



string foo = null;
foo.ToUpper();


This will throw a NullReferenceException at the second line because you can't call the instance method ToUpper() on a string reference pointing to null.






How do you find the source of a NullReferenceException? Apart from looking at the exception itself, which will be thrown exactly at the location where it occurs, the general rules of debugging in Visual Studio apply: place strategic breakpoints and inspect your variables, either by hovering the mouse over their names, opening a (Quick)Watch window or using the various debugging panels like Locals and Autos.



If you want to find out where the reference is or isn't set, right-click its name and select "Find All References". You can then place a breakpoint at every found location and run your program with the debugger attached. Every time the debugger breaks on such a breakpoint, you need to determine whether you expect the reference to be non-null, inspect the variable and and verify that it points to an instance when you expect it to.



By following the program flow this way, you can find the location where the instance should not be null, and why it isn't properly set.






Some common scenarios where the exception can be thrown:



Generic



ref1.ref2.ref3.member


If ref1 or ref2 or ref3 is null, then you'll get a NullReferenceException. If you want to solve the problem, then find out which one is null by rewriting the expression to its simpler equivalent:



var r1 = ref1;

var r2 = r1.ref2;
var r3 = r2.ref3;
r3.member


Specifically, in HttpContext.Current.User.Identity.Name, the HttpContext.Current could be null, or the User property could be null, or the Identity property could be null.



Indirect



public class Person {

public int Age { get; set; }
}
public class Book {
public Person Author { get; set; }
}
public class Example {
public void Foo() {
Book b1 = new Book();
int authorAge = b1.Author.Age; // You never initialized the Author property.
// there is no Person to get an Age from.

}
}


If you want to avoid the child (Person) null reference, you could initialize it in the parent (Book) object's constructor.



Nested Object Initializers



The same applies to nested object initializers:




Book b1 = new Book { Author = { Age = 45 } };


This translates to



Book b1 = new Book();
b1.Author.Age = 45;


While the new keyword is used, it only creates a new instance of Book, but not a new instance of Person, so the Author the property is still null.




Nested Collection Initializers



public class Person {
public ICollection Books { get; set; }
}
public class Book {
public string Title { get; set; }
}



The nested collection initializers behave the same:



Person p1 = new Person {
Books = {
new Book { Title = "Title1" },
new Book { Title = "Title2" },
}
};



This translates to



Person p1 = new Person();
p1.Books.Add(new Book { Title = "Title1" });
p1.Books.Add(new Book { Title = "Title2" });


The new Person only creates an instance of Person, but the Books collection is still null. The collection initializer syntax does not create a collection
for p1.Books, it only translates to the p1.Books.Add(...) statements.




Array



int[] numbers = null;
int n = numbers[0]; // numbers is null. There is no array to index.


Array Elements



Person[] people = new Person[5];

people[0].Age = 20 // people[0] is null. The array was allocated but not
// initialized. There is no Person to set the Age for.


Jagged Arrays



long[][] array = new long[1][];
array[0][0] = 3; // is null because only the first dimension is yet initialized.
// Use array[0] = new long[2]; first.



Collection/List/Dictionary



Dictionary agesForNames = null;
int age = agesForNames["Bob"]; // agesForNames is null.
// There is no Dictionary to perform the lookup.


Range Variable (Indirect/Deferred)




public class Person {
public string Name { get; set; }
}
var people = new List();
people.Add(null);
var names = from p in people select p.Name;
string firstName = names.First(); // Exception is thrown here, but actually occurs
// on the line above. "p" is null because the
// first element we added to the list is null.



Events



public class Demo
{
public event EventHandler StateChanged;

protected virtual void OnStateChanged(EventArgs e)
{
StateChanged(this, e); // Exception is thrown here

// if no event handlers have been attached
// to StateChanged event
}
}


Bad Naming Conventions:



If you named fields differently from locals, you might have realized that you never initialized the field.




public class Form1 {
private Customer customer;

private void Form1_Load(object sender, EventArgs e) {
Customer customer = new Customer();
customer.Name = "John";
}

private void Button_Click(object sender, EventArgs e) {
MessageBox.Show(customer.Name);

}
}


This can be solved by following the convention to prefix fields with an underscore:



private Customer _customer;


ASP.NET Page Life cycle:




public partial class Issues_Edit : System.Web.UI.Page
{
protected TestIssue myIssue;

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// Only called on first load, not when button clicked

myIssue = new TestIssue();
}
}

protected void SaveButton_Click(object sender, EventArgs e)
{
myIssue.Entry = "NullReferenceException here!";
}
}



ASP.NET Session Values



// if the "FirstName" session value has not yet been set,
// then this line will throw a NullReferenceException
string firstName = Session["FirstName"].ToString();


ASP.NET MVC empty view models




If the exception occurs when referencing a property of @Model in an ASP.NET MVC view, you need to understand that the Model gets set in your action method, when you return a view. When you return an empty model (or model property) from your controller, the exception occurs when the views access it:



// Controller
public class Restaurant:Controller
{
public ActionResult Search()
{
return View(); // Forgot the provide a Model here.
}
}


// Razor view
@foreach (var restaurantSearch in Model.RestaurantSearch) // Throws.
{
}

@Model.somePropertyName




WPF Control Creation Order and Events




WPF controls are created during the call to InitializeComponent in the order they appear in the visual tree. A NullReferenceException will be raised in the case of early-created controls with event handlers, etc. , that fire during InitializeComponent which reference late-created controls.



For example :





Margin="10"
SelectedIndex="0"

SelectionChanged="comboBox1_SelectionChanged">









Here comboBox1 is created before label1. If comboBox1_SelectionChanged attempts to reference `label1, it will not yet have been created.



private void comboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
label1.Content = comboBox1.SelectedIndex.ToString(); // NullReference here!!
}



Changing the order of the declarations in the XAML (i.e., listing label1 before comboBox1, ignoring issues of design philosophy, would at least resolve the NullReferenceException here.



Cast with as



var myThing = someObject as Thing;


This doesn't throw an InvalidCastException but returns a null when the cast fails (and when someObject is itself null). So be aware of that.




LINQ FirstOrDefault() and SingleOrDefault()



The plain versions First() and Single() throw exceptions when there is nothing. The "OrDefault" versions return null in that case. So be aware of that.



foreach



foreach throws when you try to iterate null collection. Usually caused by unexpected null result from methods that return collections.



 List list = null;    
foreach(var v in list) { } // exception



More realistic example - select nodes from XML document. Will throw if nodes are not found but initial debugging shows that all properties valid:



 foreach (var node in myData.MyXml.DocumentNode.SelectNodes("//Data"))








Explicitly check for null and ignore null values.



If you expect the reference sometimes to be null, you can check for it being null before accessing instance members:



void PrintName(Person p) {
if (p != null) {
Console.WriteLine(p.Name);
}
}



Explicitly check for null and provide a default value.



Methods call you expect to return an instance can return null, for example when the object being sought cannot be found. You can choose to return a default value when this is the case:



string GetCategory(Book b) {
if (b == null)
return "Unknown";
return b.Category;

}


Explicitly check for null from method calls and throw a custom exception.



You can also throw a custom exception, only to catch it in the calling code:



string GetCategory(string bookTitle) {
var book = library.FindBook(bookTitle); // This may return null
if (book == null)

throw new BookNotFoundException(bookTitle); // Your custom exception
return book.Category;
}


Use Debug.Assert if a value should never be null, to catch the problem earlier than the exception occurs.



When you know during development that a method maybe can, but never should return null, you can use Debug.Assert() to break as soon as possible when it does occur:



string GetTitle(int knownBookID) {

// You know this should never return null.
var book = library.GetBook(knownBookID);

// Exception will occur on the next line instead of at the end of this method.
Debug.Assert(book != null, "Library didn't return a book for known book ID.");

// Some other code

return book.Title; // Will never throw NullReferenceException in Debug mode.
}



Though this check will not end up in your release build, causing it to throw the NullReferenceException again when book == null at runtime in release mode.



Use GetValueOrDefault() for nullable value types to provide a default value when they are null.



DateTime? appointment = null;
Console.WriteLine(appointment.GetValueOrDefault(DateTime.Now));
// Will display the default value provided (DateTime.Now), because appointment is null.


appointment = new DateTime(2022, 10, 20);
Console.WriteLine(appointment.GetValueOrDefault(DateTime.Now));
// Will display the appointment date, not the default


Use the null coalescing operator: ?? [C#] or If() [VB].



The shorthand to providing a default value when a null is encountered:



IService CreateService(ILogger log, Int32? frobPowerLevel)

{
var serviceImpl = new MyService(log ?? NullLog.Instance);

// Note that the above "GetValueOrDefault()" can also be rewritten to use
// the coalesce operator:
serviceImpl.FrobPowerLevel = frobPowerLevel ?? 5;
}


Use the null condition operator: ?. or ?[x] for arrays (available in C# 6 and VB.NET 14):




This is also sometimes called the safe navigation or Elvis (after its shape) operator. If the expression on the left side of the operator is null, then the right side will not be evaluated, and null is returned instead. That means cases like this:



var title = person.Title.ToUpper();


If the person does not have a title, this will throw an exception because it is trying to call ToUpper on a property with a null value.



In C# 5 and below, this can be guarded with:




var title = person.Title == null ? null : person.Title.ToUpper();


Now the title variable will be null instead of throwing an exception. C# 6 introduces a shorter syntax for this:



var title = person.Title?.ToUpper();


This will result in the title variable being null, and the call to ToUpper is not made if person.Title is null.




Of course, you still have to check title for null or use the null condition operator together with the null coalescing operator (??) to supply a default value:



// regular null check
int titleLength = 0;
if (title != null)
titleLength = title.Length; // If title is null, this would throw NullReferenceException

// combining the `?` and the `??` operator
int titleLength = title?.Length ?? 0;



Likewise, for arrays you can use ?[i] as follows:



int[] myIntArray=null;
var i=5;
int? elem = myIntArray?[i];
if (!elem.HasValue) Console.WriteLine("No value");


This will do the following: If myIntArray is null, the expression returns null and you can safely check it. If it contains an array, it will do the same as:

elem = myIntArray[i]; and returns the ith element.



Use null context (available in C# 8):



Introduced in C# 8 there null context's and nullable reference types perform static analysis on variables and provides a compiler warning if a value can be potentially null or have been set to null. The nullable reference types allows types to be explicitly allowed to be null.



The nullable annotation context and nullable warning context can be set for a project using the Nullable element in your csproj file. This element configures how the compiler interprets the nullability of types and what warnings are generated. Valid settings are:




  • enable: The nullable annotation context is enabled. The nullable warning context is enabled. Variables of a reference type, string for example, are non-nullable. All nullability warnings are enabled.


  • disable: The nullable annotation context is disabled. The nullable warning context is disabled. Variables of a reference type are oblivious, just like earlier versions of C#. All nullability warnings are disabled.

  • safeonly: The nullable annotation context is enabled. The nullable warning context is safeonly. Variables of a reference type are nonnullable. All safety nullability warnings are enabled.

  • warnings: The nullable annotation context is disabled. The nullable warning context is enabled. Variables of a reference type are oblivious. All nullability warnings are enabled.

  • safeonlywarnings: The nullable annotation context is disabled. The nullable warning context is safeonly.
    Variables of a reference type are oblivious. All safety nullability warnings are enabled.



A nullable reference type is noted using the same syntax as nullable value types: a ? is appended to the type of the variable.



Special techniques for debugging and fixing null derefs in iterators




C# supports "iterator blocks" (called "generators" in some other popular languages). Null dereference exceptions can be particularly tricky to debug in iterator blocks because of deferred execution:



public IEnumerable GetFrobs(FrobFactory f, int count)
{
for (int i = 0; i < count; ++i)
yield return f.MakeFrob();
}
...
FrobFactory factory = whatever;

IEnumerable frobs = GetFrobs();
...
foreach(Frob frob in frobs) { ... }


If whatever results in null then MakeFrob will throw. Now, you might think that the right thing to do is this:



// DON'T DO THIS
public IEnumerable GetFrobs(FrobFactory f, int count)
{

if (f == null)
throw new ArgumentNullException("f", "factory must not be null");
for (int i = 0; i < count; ++i)
yield return f.MakeFrob();
}


Why is this wrong? Because the iterator block does not actually run until the foreach! The call to GetFrobs simply returns an object which when iterated will run the iterator block.



By writing a null check like this you prevent the null dereference, but you move the null argument exception to the point of the iteration, not to the point of the call, and that is very confusing to debug.




The correct fix is:



// DO THIS
public IEnumerable GetFrobs(FrobFactory f, int count)
{
// No yields in a public method that throws!
if (f == null)
throw new ArgumentNullException("f", "factory must not be null");
return GetFrobsForReal(f, count);

}
private IEnumerable GetFrobsForReal(FrobFactory f, int count)
{
// Yields in a private method
Debug.Assert(f != null);
for (int i = 0; i < count; ++i)
yield return f.MakeFrob();
}



That is, make a private helper method that has the iterator block logic, and a public surface method that does the null check and returns the iterator. Now when GetFrobs is called, the null check happens immediately, and then GetFrobsForReal executes when the sequence is iterated.



If you examine the reference source for LINQ to Objects you will see that this technique is used throughout. It is slightly more clunky to write, but it makes debugging nullity errors much easier. Optimize your code for the convenience of the caller, not the convenience of the author.



A note on null dereferences in unsafe code



C# has an "unsafe" mode which is, as the name implies, extremely dangerous because the normal safety mechanisms which provide memory safety and type safety are not enforced. You should not be writing unsafe code unless you have a thorough and deep understanding of how memory works.



In unsafe mode, you should be aware of two important facts:





  • dereferencing a null pointer produces the same exception as dereferencing a null reference

  • dereferencing an invalid non-null pointer can produce that exception
    in some circumstances



To understand why that is, it helps to understand how .NET produces null dereference exceptions in the first place. (These details apply to .NET running on Windows; other operating systems use similar mechanisms.)



Memory is virtualized in Windows; each process gets a virtual memory space of many "pages" of memory that are tracked by the operating system. Each page of memory has flags set on it which determine how it may be used: read from, written to, executed, and so on. The lowest page is marked as "produce an error if ever used in any way".




Both a null pointer and a null reference in C# are internally represented as the number zero, and so any attempt to dereference it into its corresponding memory storage causes the operating system to produce an error. The .NET runtime then detects this error and turns it into the null dereference exception.



That's why dereferencing both a null pointer and a null reference produces the same exception.



What about the second point? Dereferencing any invalid pointer that falls in the lowest page of virtual memory causes the same operating system error, and thereby the same exception.



Why does this make sense? Well, suppose we have a struct containing two ints, and an unmanaged pointer equal to null. If we attempt to dereference the second int in the struct, the CLR will not attempt to access the storage at location zero; it will access the storage at location four. But logically this is a null dereference because we are getting to that address via the null.



If you are working with unsafe code and you get a null dereference exception, just be aware that the offending pointer need not be null. It can be any location in the lowest page, and this exception will be produced.


c++ - Failed to specialize function template




This is homework, although it's already submitted with a different approach.



I'm getting the following from Visual Studio 2008




error C2893: Failed to specialize function template 'void std::sort(_RanIt,_RanIt,_Pr)'


The code is as follows





main.cpp
Database<> db;
db.loadDatabase();
db.sortDatabase(sort_by_title());

Database.cpp
void Database::sortDatabase(const sort_by &s) {
std::sort(db_.begin(), db_.end(), s);
}



And the function objects are defined as




struct sort_by : public std::binary_function {
virtual bool operator()(const Media *l, const Media *r) const = 0;
};

struct sort_by_title : public sort_by {

bool operator()(const Media *l, const Media *r) const { ... }
};
...


What's the cure here?



[Edit]
Sorry, maybe I should have made the inheritance clear





template >
class Database : public IDatabase


[/Edit]



[Edit2]
After the suggestion from Toolbox (which seemed very reasonable) I ended up with the following error message





error C2664: 'Database<>::sortMedia' : cannot convert parameter 1 from 'sort_by_title' to 'const sort_by &'


main.cpp is still the same, but with some slight modifications to the functor hierarchy and source files. Forward declarations and such did not work so I had to put the definitions in separate files.




Search.h
struct sort_by_impl {
virtual bool operator()(const Media *l, const Media *r) const = 0;
};

struct sort_by : public std::binary_function {
sort_by_impl *sbp;
bool operator()(const Media *l, const Media *r) const {
return (*sbp)(l, r);
}
};

IDatabase.h
struct sort_by_title : public sort_by_impl {
bool operator()(const Media *l, const Media *r) const {

return (l->getTitle() < r->getTitle());
}
};


I'm really not grokking this, what am I missing here? Some conversion operation, or what?
[/Edit2]



[Edit3]
Last and final edit, I hope. I actually got this working after debugging and rewriting some of the code. This is what I ended up with, and it's the best I could do





class sort_by : public std::binary_function {
public:
sort_by(sort_by_impl *sbp) : sbp_(sbp) {};
bool operator()(const Media *l, const Media *r) const {
return (*sbp_)(l, r);
}
private:
sort_by_impl *sbp_;
};


main.cpp
db.sortDatabase(&sort_by_title());

Database.cpp
void Database::sortDatabase(const sort_by &s) {
std::sort(db_.begin(), db_.end(), s);


This seems to work, both in a separate project (spending the better part of this day messing with this) and in my actual project which I submitted some days ago.
Thank you very much for your time and help!
[/Edit3]


Answer




I'm not sure this is what's causing the problem, as it has nothing to do with specializing std::sort, but in sortDatabase you shouldn't be passing in a functor that's meant to behave polymorphically. The reason is that std::sort accepts your function object by value, which means it gets copied as a sort_by object, not whatever it actually is (i.e. you have a slicing problem).



If you want the function object to have a virtual operator(), the function object should hold a pointer to the polymorphic class like so:



struct sort_by : public std::binary_function {
bool operator()(const Media *l, const Media *r) const
{
return (*p_impl)(l, r);
}


sort_by_impl* p_impl;
};


Then, sort_by_impl can be your abstract base class from which specific sorting function objects derive and override. Hope that helps.



EDIT



Based on the new error message, if I had to guess, you're trying to do something like this inside sortMedia:




Database > db; // initialized elsewhere...

sort_by_title my_sort;
db.sortDatabase(my_sort);


The problem is that my_sort is of type sort_by_title, which is a derived form of sort_by_impl - not of type sort_by. That means you actually want to pass my_sort to be the sbp pointer in a sort_by object, which is the actual function object you'll use. To illustrate:



Database > db; // initialized elsewhere...


sort_by my_sort_fn;
my_sort_fn.sbp = new sort_by_title;
db.sortDatabase(my_sort_fn);

delete my_sort_fn.sbp;


The code isn't exception safe, by the way; consider replacing sbp with a reference-counting smart pointer. Or even easier, just declare the sort_by_title on the stack and pass in its address. Just be careful not to let it be destroyed before it's used. :)



Hopefully that helps. Let me know how it turns out!



Saturday, September 29, 2018

Global functions in javascript

I'm new to js and trying to understand global and private functions. I understand global and local variables. But if I have an html named test.html and a 2 js files named test1.js and test2.js. Now I include the test1.js and test2.js in test.html and call the functions written in test2.js inside test1.js and test.html.



The functions that I have written in test2.js are in this form



function abc(){...}

function pqr(){...} etc.


are these above functions global? If they are , how can I not make them global and still access them in test1.js and test.html?



As I have read global functions or global variables are bad right?

regex - gsub() everything except specified characters?

We need to use ^ inside the [ to match all characters except the ro. Here, the [^ro]+ implies matching one or more characters that are not a 'r' or 'o' and replace it with blank ("").


gsub("[^ro]+", "", str1)
#[1] "roooro"



If we have a vector of values, we can create the pattern with paste


v1 <- c("r", "o")
gsub(paste0("[^", paste(v1, collapse=""), "]+"), "", str1)
#[1] "roooro"

Can JSON start with "["?




From what I can read on json.org, all JSON strings should start with { (curly brace), and [ characters (square brackets) represent an array element in JSON.



I use the json4j library, and I got an input that starts with [, so I didn't think this was valid JSON. I looked briefly at the JSON schema, but I couldn't really find it stated that a JSON file cannot start with [, or that it can only start with {.


Answer



JSON can be either an array or an object. Specifically off of json.org:




JSON is built on two structures:





  • A collection of name/value pairs. In various languages, this is
    realized as an object, record,
    struct, dictionary, hash table,
    keyed list, or associative array.

  • An ordered list of values. In most languages, this is realized as an
    array, vector, list, or sequence.




It then goes on to describe the two structures as:
A JSON object

A JSON array



Note that the starting and ending characters are curly brackets and square brackets respectively.



Edit
And from here: http://www.ietf.org/rfc/rfc4627.txt




A JSON text is a sequence of tokens.
The set of tokens includes six
structural characters, strings,

numbers, and three literal names.



A JSON text is a serialized object or array.




Update (2014)



As of March 2014, there is a new JSON RFC (7159) that modifies the definition slightly (see pages 4/5).



The definition per RFC 4627 was: JSON-text = object / array




This has been changed in RFC 7159 to: JSON-text = ws value ws



Where ws represents whitespace and value is defined as follows:




A JSON value MUST be an object, array, number, or string, or one of
the following three literal names:



false null true




So, the answer to the question is still yes, JSON text can start with a square bracket (i.e. an array). But in addition to objects and arrays, it can now also be a number, string or the values false, null or true.



Also, this has changed from my previous RFC 4627 quote (emphasis added):




A JSON text is a sequence of tokens. The set of tokens includes six
structural characters, strings, numbers, and three literal names.




A JSON text is a serialized value. Note that certain previous
specifications of JSON constrained a JSON text to be an object or an
array. Implementations that generate only objects or arrays where a
JSON text is called for will be interoperable in the sense that all
implementations will accept these as conforming JSON texts.



props - Hebrew newspaper in Laurel & Hardy's Blotto? - Movies & TV

In the Laurel & Hardy movie (or episode, if you will) Blotto (1930), in the first scene, Stan is reading a hebrew newspaper.



Hebrew newspaper



So I was wondering, why a hebrew newspaper? Is there any reason and purpose for this, or has it got any meaning? I couldn't spot anything in the movie that this is a reference to or anything... I can guess it's some sort of a 'random' joke that really doesn't have a special meaning or purpose, yet I'm eager to find out if this is the case.

mysql - How to insert into MySQLusing a prepared statement with PHP





I am just learning about databases and I want to be able to store user inputs. What would be a basic example on how to get form data and save it to a database using PHP?



Also making the form secure from SQL attacks.


Answer



File sample.html










File sample.php



    if (isset($_POST['submit'])) {


$mysqli = new mysqli('localhost', 'user', 'password', 'mysampledb');

/* Check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}

$stmt = $mysqli->prepare("INSERT INTO SampleTable VALUES (?)");

$stmt->bind_param('s', $sample); // Bind $sample to the parameter

$sample = isset($_POST['sample'])
? $_POST['sample']
: '';

/* Execute prepared statement */
$stmt->execute();

printf("%d Row inserted.\n", $stmt->affected_rows);


/* Close statement and connection */
$stmt->close();

/* Close connection */
$mysqli->close();
}
?>



This is a very basic example. Many PHP developers today are turning to PDO. Mysqli isn’t obsolete, but PDO is much easier, IMHO.


php - Is mysql_real_escape_string is really safe to use?




OK, I have one question before I start coding MySQL in my school project. Is mysql_real_escape_string is really safe to use? I've heard that it's still not really safe to use..So are there any tweaks which makes SQL query secure? I've used mysql_real_escape_string before many times, but not I am building a website for my school, so first thing I've to check is security.


Answer



UPDATE: The answer below was to the best of my knowledge correct at the time of writing. The fact is mysql_real_escape_string is not safe and never really was. You should always use prepared statements instead.



As mysql_* has been removed completely as of PHP 7 the situation has become moot. I've left my original answer for historical purposes below.







mysql_real_escape_string is safe to use if used properly (ie, everywhere you're inserting PHP variables into your queries), but as has been pointed out in the comments it's not the only thing you need to worry about. For example, HTML markup could be inserted into your DB and used for Cross Site Scripting attacks.



You might also want to consider prepared statements as an alternative to mysql_real_escape_string, as they will automatically escape input for you so there's no chance of accidentally forgetting to escape a parameter.


What is the most efficient way to deep clone an object in JavaScript?

What is the most efficient way to clone a JavaScript object? I've seen obj = eval(uneval(o)); being used, but that's non-standard and only supported by Firefox.

I've done things like obj = JSON.parse(JSON.stringify(o)); but question the efficiency.

I've also seen recursive copying functions with various flaws.

I'm surprised no canonical solution exists.

vb.net - HTML encoding issues - "Â" character showing up instead of " "



I've got a legacy app just starting to misbehave, for whatever reason I'm not sure. It generates a bunch of HTML that gets turned into PDF reports by ActivePDF.




The process works like this:




  1. Pull an HTML template from a DB with tokens in it to be replaced (e.g. "~CompanyName~", "~CustomerName~", etc.)

  2. Replace the tokens with real data

  3. Tidy the HTML with a simple regex function that property formats HTML tag attribute values (ensures quotation marks, etc, since ActivePDF's rendering engine hates anything but single quotes around attribute values)

  4. Send off the HTML to a web service that creates the PDF.




Somewhere in that mess, the non-breaking spaces from the HTML template (the  s) are encoding as ISO-8859-1 so that they show up incorrectly as an "Â" character when viewing the document in a browser (FireFox). ActivePDF pukes on these non-UTF8 characters.



My question: since I don't know where the problem stems from and don't have time to investigate it, is there an easy way to re-encode or find-and-replace the bad characters? I've tried sending it through this little function I threw together, but it turns it all into gobbledegook doesn't change anything.



Private Shared Function ConvertToUTF8(ByVal html As String) As String
Dim isoEncoding As Encoding = Encoding.GetEncoding("iso-8859-1")
Dim source As Byte() = isoEncoding.GetBytes(html)
Return Encoding.UTF8.GetString(Encoding.Convert(isoEncoding, Encoding.UTF8, source))
End Function



Any ideas?



EDIT:



I'm getting by with this for now, though it hardly seems like a good solution:



Private Shared Function ReplaceNonASCIIChars(ByVal html As String) As String
Return Regex.Replace(html, "[^\u0000-\u007F]", " ")
End Function


Answer




Somewhere in that mess, the non-breaking spaces from the HTML template (the  s) are encoding as ISO-8859-1 so that they show up incorrectly as an "Â" character




That'd be encoding to UTF-8 then, not ISO-8859-1. The non-breaking space character is byte 0xA0 in ISO-8859-1; when encoded to UTF-8 it'd be 0xC2,0xA0, which, if you (incorrectly) view it as ISO-8859-1 comes out as " ". That includes a trailing nbsp which you might not be noticing; if that byte isn't there, then something else has mauled your document and we need to see further up to find out what.



What's the regexp, how does the templating work? There would seem to be a proper HTML parser involved somewhere if your   strings are (correctly) being turned into U+00A0 NON-BREAKING SPACE characters. If so, you could just process your template natively in the DOM, and ask it to serialise using the ASCII encoding to keep non-ASCII characters as character references. That would also stop you having to do regex post-processing on the HTML itself, which is always a highly dodgy business.




Well anyway, for now you can add one of the following to your document's and see if that makes it look right in the browser:




  • for HTML4:

  • for HTML5:



If you've done that, then any remaining problem is ActivePDF's fault.


php - Fatal error: Can't use function return value



When i'm using following code then fatal error generate.




echo empty(is_resource(true));


Error:




Fatal error: Can't use function return value in write context.





Why?


Answer



empty requires a variable as if the parameter were passed by reference:




Note:
empty() only checks variables as anything else will result in a parse error. In other words, the following will not work: empty(trim($name)).




So you could do this:




$var = is_resource(true);
echo empty($var);


But as is_resource already returns a boolean value, you actually don’t need another testing function.


javascript - How to decide when to use Node.js?





I am new to this kind of stuff, but lately I've been hearing a lot about how good Node.js is. Considering how much I love working with jQuery and JavaScript in general, I can't help but wonder how to decide when to use Node.js. The web application I have in mind is something like Bitly - takes some content, archives it.



From all the homework I have been doing in the last few days, I obtained the following information. Node.js




  • is a command-line tool that can be run as a regular web server and lets one run JavaScript programs

  • utilizes the great V8 JavaScript engine


  • is very good when you need to do several things at the same time

  • is event-based so all the wonderful Ajax-like stuff can be done on the server side

  • lets us share code between the browser and the backend

  • lets us talk with MySQL



Some of the sources that I have come across are:






Considering that Node.js can be run almost out-of-the-box on Amazon's EC2 instances, I am trying to understand what type of problems require Node.js as opposed to any of the mighty kings out there like PHP, Python and Ruby. I understand that it really depends on the expertise one has on a language, but my question falls more into the general category of: When to use a particular framework and what type of problems is it particularly suited for?


Answer



You did a great job of summarizing what's awesome about Node.js. My feeling is that Node.js is especially suited for applications where you'd like to maintain a persistent connection from the browser back to the server. Using a technique known as "long-polling", you can write an application that sends updates to the user in real time. Doing long polling on many of the web's giants, like Ruby on Rails or Django, would create immense load on the server, because each active client eats up one server process. This situation amounts to a tarpit attack. When you use something like Node.js, the server has no need of maintaining separate threads for each open connection.



This means you can create a browser-based chat application in Node.js that takes almost no system resources to serve a great many clients. Any time you want to do this sort of long-polling, Node.js is a great option.



It's worth mentioning that Ruby and Python both have tools to do this sort of thing (eventmachine and twisted, respectively), but that Node.js does it exceptionally well, and from the ground up. JavaScript is exceptionally well situated to a callback-based concurrency model, and it excels here. Also, being able to serialize and deserialize with JSON native to both the client and the server is pretty nifty.



I look forward to reading other answers here, this is a fantastic question.




It's worth pointing out that Node.js is also great for situations in which you'll be reusing a lot of code across the client/server gap. The Meteor framework makes this really easy, and a lot of folks are suggesting this might be the future of web development. I can say from experience that it's a whole lot of fun to write code in Meteor, and a big part of this is spending less time thinking about how you're going to restructure your data, so the code that runs in the browser can easily manipulate it and pass it back.



Here's an article on Pyramid and long-polling, which turns out to be very easy to set up with a little help from gevent: TicTacToe and Long Polling with Pyramid.


linux - Troubleshooting PHP Mail




How can I check a problem with mail being sent on my server?
I run a simple test:



if(mail($to, $subject, $message)) {
echo 'Mail Sent';
}


which the test outputs the text; but, no mail ever arrives.



How can I go about tracking down the issue?


Answer



That is quite a long story. A few bullet points (Assuming that mail() returns true and there are no errors in the error log) :




  • Does the sender address ("From") belong to a domain on your server? If not, make it so.

  • Is your server on a blacklist (e.g. check IP on spamhaus.org)? This is a remote possibility with shared hosting.

  • Are mails filtered by a spam filter? Open an account with a freemailer that has a spam folder and find out. Also, try sending mail to an address without a spam filter.

  • Do you possibly need the fifth parameter "-f" of mail() to add a sender address? (See mail() command in the PHP manual)

  • If you have access to log files, check those, of course, as suggested above.

  • Do you check the "from:" address for possible bounce mails ("Returned to sender")? You can also set up a separate "errors-to" address.



For german speakers, I have written a quite exhaustive "what to do" on this issue some time ago. See here.


plot explanation - Why did Peaches&#39; mom hang on the tree? - Movies &amp; TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...