Thursday, January 31, 2019

plot explanation - Why didn't Cobb talk to any of his team members at the airport in the ending of Inception? - Movies & TV



In Inception, it always makes me wonder why Cobb didn't say a hello to his team members. He does not even smile at any of his team members at the airport.



What is the reason he acts like he does now know his team members?



Can someone help me to understand the airport scene in Inception?


Answer




They do give each other some knowing glances but you are correct, as the team arrive in Los Angeles airport, they split up and almost ignore each other going through immigration and baggage collection.



IMHO there are two main reasons for this:




  • They have just completed a crime, they illegally drugged Fischer and forced him into a shared dream without his knowledge. The team appeared to board the plane giving the impression of not knowing each other. They probably do not want to make Fischer suspicious by suddenly being all friendly at the destination. Fischer has woken up with a new idea in his head (to break up his fathers business empire) and they probably don't want him to even start to connect that with the journey he just completed. As a result the team are moving through the arrival lounge just as if they are normal business people on separate journeys.

  • Cobb is wanted for murder and is just about to go through immigration checks. Everyone else in his team knows this. Cobb is probably nervous and his friends are probably nervous for him and/or curious too see whether Saito was able or willing to get Cobb into the country.


first appearance - What year did they begin announcing that TV shows were "Filmed in front of a live studio audience"? - Movies & TV




I was watching antenna TV and now I wonder: What year did they begin to make the point of announcing that specific TV shows were "Filmed in front of a live studio audience" and which show was the first one to include that announcement in its credits?



Answer



One of the earliest, if not the first such announcements was "All in the Family was recorded on tape before a live audience" from 1971.



According to Michael Tueth's Laughter In The Living Room (2005), one of the earliest American sitcoms to broadcast live was I Love Lucy (1951 – 1957). For personal reasons, Lucy Ball wanted to produce the programme from Hollywood instead of New York City, but New York was the only place where live TV was produced and broadcast live. Ball suggested they film in Hollywood, and broadcast from New York. This started a trend.



Tueth says they also insisted on filming with a live audience, but this wasn't repeated until a new wave of comedies in the 1970s, such as All in the Family (1971 – 1979) started announcing it "was filmed in front of a live studio audience".



Wikipedia says:





All in the Family was the first major American series to be videotaped in front of a live studio audience. In the 1960s, most sitcoms had been filmed in the single-camera format without audiences, with a laugh track simulating audience response. Lear employed the Multi-camera format of shooting in front of an audience, but used tape, whereas previous multi-camera shows like Mary Tyler Moore had used film. Thanks to the success of All in the Family, videotaping sitcoms in front of an audience became common format for the genre during the 1970s. The use of videotape also gave All in the Family the look and feel of early live television, including the original live broadcasts of The Honeymooners, to which All in the Family is sometimes compared.



For the show's final season, the practice of being taped before a live audience changed to playing the already taped and edited show to an audience and recording their laughter to add to the original sound track. Thus, the voice-over during the end credits was changed from Rob Reiner's "All in the Family was recorded on tape before a live audience" to Carroll O'Connor's "All in the Family was played to a studio audience for live responses". (Typically, the audience would be gathered for a taping of One Day at a Time, and get to see All In the Family as a bonus.) Throughout its run, Norman Lear took pride in the fact that canned laughter was never used (mentioning this on many occasions); the laughter heard in the episodes was genuine.




Also from Wikipedia:




Creator Norman Lear's All in the Family (CBS, 1971–1979) followed suit in 1971. Videotaped live, Lear wanted the studio audience to actually like the performer, with hopes of the two developing a rapport with each other. Lear was not a fan of pretaped audiences, resulting in no laugh track being employed, not even during post-production when Lear could have had the luxury of sweetening any failed jokes (Lear relented somewhat in later seasons, and allowed [sound engineer and laugh track inventer Charles] Douglass to insert an occasional laugh). Lear's decision resulted in the show being a huge success, and officially ushered in the return of live audiences to the U.S. sitcom mainstream. To make his point clear, an announcement proclaimed over the closing credits each week that "All in the Family was recorded on tape before a live audience" (or during the show's final seasons where live audiences no longer attended tapings of the show) "All in the Family was played to a studio audience for live responses."




Why Does C++ Support Hex Assignment, But Lack Binary Assignment? How best to store flags?



I have a set of bit flags that are used in a program I am porting from C to C++.



To begin...




The flags in my program were previously defined as:



/* Define feature flags for this DCD file */
#define DCD_IS_CHARMM 0x01
#define DCD_HAS_4DIMS 0x02
#define DCD_HAS_EXTRA_BLOCK 0x04


...Now I've gather that #defines for constants (versus class constants, etc.) are generally considered bad form.




This raises questions about how best to store bit flags in c++ and why c++ doesn't support assignment of binary text to an int, like it allows for hex numbers to be assigned in this way (via "0x"). These questions are summarized at the end of this post.



I could see one simple solution is to simply create individual constants:



namespace DCD {
const unsigned int IS_CHARMM = 1;
const unsigned int HAS_4DIMS = 2;
const unsigned int HAS_EXTRA_BLOCK = 4;
};



Let's call this idea 1.



Another idea I had was to use an integer enum:



namespace DCD {
enum e_Feature_Flags {
IS_CHARMM = 1,
HAS_4DIMS = 2,
HAS_EXTRA_BLOCK = 8

};
};


But one thing that bothers me about this is that its less intuitive when it comes to higher values, it seems... i.e.



namespace DCD {
enum e_Feature_Flags {
IS_CHARMM = 1,
HAS_4DIMS = 2,

HAS_EXTRA_BLOCK = 8,
NEW_FLAG = 16,
NEW_FLAG_2 = 32,
NEW_FLAG_3 = 64,
NEW_FLAG_4 = 128
};
};


Let's call this approach option 2.




I'm considering using Tom Torf's macro solution:



#define B8(x) ((int) B8_(0x##x))

#define B8_(x) \
( ((x) & 0xF0000000) >( 28 - 7 ) \
| ((x) & 0x0F000000) >( 24 - 6 ) \
| ((x) & 0x00F00000) >( 20 - 5 ) \
| ((x) & 0x000F0000) >( 16 - 4 ) \

| ((x) & 0x0000F000) >( 12 - 3 ) \
| ((x) & 0x00000F00) >( 8 - 2 ) \
| ((x) & 0x000000F0) >( 4 - 1 ) \
| ((x) & 0x0000000F) >( 0 - 0 ) )


converted to inline functions, e.g.



#include 
#include

....

/* TAKEN FROM THE C++ LITE FAQ [39.2]... */
class BadConversion : public std::runtime_error {
public:
BadConversion(std::string const& s)
: std::runtime_error(s)
{ }
};


inline double convertToUI(std::string const& s)
{
std::istringstream i(s);
unsigned int x;
if (!(i >> x))
throw BadConversion("convertToUI(\"" + s + "\")");
return x;
}
/** END CODE **/


inline unsigned int B8(std::string x) {
unsigned int my_val = convertToUI(x.insert(0,"0x").c_str());
return ((my_val) & 0xF0000000) >( 28 - 7 ) |
((my_val) & 0x0F000000) >( 24 - 6 ) |
((my_val) & 0x00F00000) >( 20 - 5 ) |
((my_val) & 0x000F0000) >( 16 - 4 ) |
((my_val) & 0x0000F000) >( 12 - 3 ) |
((my_val) & 0x00000F00) >( 8 - 2 ) |
((my_val) & 0x000000F0) >( 4 - 1 ) |
((my_val) & 0x0000000F) >( 0 - 0 );

}

namespace DCD {
enum e_Feature_Flags {
IS_CHARMM = B8("00000001"),
HAS_4DIMS = B8("00000010"),
HAS_EXTRA_BLOCK = B8("00000100"),
NEW_FLAG = B8("00001000"),
NEW_FLAG_2 = B8("00010000"),
NEW_FLAG_3 = B8("00100000"),

NEW_FLAG_4 = B8("01000000")
};
};


Is this crazy? Or does it seem more intuitive? Let's call this choice 3.



So to recap, my over-arching questions are:



1. Why doesn't c++ support a "0b" value flag, similar to "0x"?
2. Which is the best style to define flags...
i. Namespace wrapped constants.
ii. Namespace wrapped enum of unsigned ints assigned directly.
iii. Namespace wrapped enum of unsigned ints assigned using readable binary string.




Thanks in advance! And please don't close this thread as subjective, because I really want to get help on what the best style is and why c++ lacks built in binary assignment capability.






EDIT 1



A bit of additional info. I will be reading a 32-bit bitfield from a file and then testing it with these flags. So bear that in mind when you post suggestions.


Answer



Prior to C++14, binary literals had been discussed off and on over the years, but as far as I know, nobody had ever written up a serious proposal to get it into the standard, so it never really got past the stage of talking about it.




For C++ 14, somebody finally wrote up a proposal, and the committee accepted it, so if you can use a current compiler, the basic premise of the question is false--you can use binary literals, which have the form 0b01010101.



In C++11, instead of adding binary literals directly, they added a much more general mechanism to allow general user-defined literals, which you could use to support binary, or base 64, or other kinds of things entirely. The basic idea is that you specify a number (or string) literal followed by a suffix, and you can define a function that will receive that literal, and convert it to whatever form you prefer (and you can maintain its status as a "constant" too...)



As to which to use: if you can, the binary literals built into C++14 or above are the obvious choice. If you can't use them, I'd generally prefer a variation of option 2: an enum with initializers in hex:



namespace DCD {
enum e_Feature_Flags {
IS_CHARMM = 0x1,

HAS_4DIMS = 0x2,
HAS_EXTRA_BLOCK = 0x8,
NEW_FLAG = 0x10,
NEW_FLAG_2 = 0x20,
NEW_FLAG_3 = 0x40,
NEW_FLAG_4 = 0x80
};
};



Another possibility is something like:



#define bit(n) (1<<(n))

enum e_feature_flags = {
IS_CHARM = bit(0),
HAS_4DIMS = bit(1),
HAS_EXTRA_BLOCK = bit(3),
NEW_FLAG = bit(4),
NEW_FLAG_2 = bit(5),

NEW_FLAG_3 = bit(6),
NEW_FLAG_4 = bit(7)
};

android - NetworkOnMainThreadException error in jellybean




I've been trying to get this to work for the last week or so and still have no idea what the problem is. it works on android 2.1 but not on 4.1. ive got this string in a service that check for updates in my app.



latestVersion = Integer.parseInt(getHttpString(urlLatestVersion));


its called in checkForUpdate(); which is called in onStart(Intent intent, int startId);.




private String getHttpString(String urlString) throws IOException {
InputStream in = null;
int response = -1;

URL url = new URL(urlString);
URLConnection conn = url.openConnection();

if (!(conn instanceof HttpURLConnection))
throw new IOException("Not an HTTP connection");


try {
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();

response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();

}
} catch (Exception ex) {
ex.printStackTrace();
//
//main error currently lies here
// TODO fix errors that accures on android 4.0 and above.
//
}
if (in != null) {
StringBuilder sb = new StringBuilder();

String line;

try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(in, "UTF-8"));
while ((line = reader.readLine()) != null) {
sb.append(line); // .append("\n");
}
} finally {
in.close();

}
return sb.toString();
} else
return "";

}


this is the error from the logcat




W/System.err( 7077): android.os.NetworkOnMainThreadException
W/System.err( 7077): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
W/System.err( 7077): at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
W/System.err( 7077): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
W/System.err( 7077): at java.net.InetAddress.getAllByName(InetAddress.java:214)
W/System.err( 7077): at libcore.net.http.HttpConnection.(HttpConnection.java:70)
W/System.err( 7077): at libcore.net.http.HttpConnection.(HttpConnection.java:50)
W/System.err( 7077): at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:341)
W/System.err( 7077): at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:87)
W/System.err( 7077): at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)

W/System.err( 7077): at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:315)
W/System.err( 7077): at libcore.net.http.HttpEngine.connect(HttpEngine.java:310)
W/System.err( 7077): at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:289)
W/System.err( 7077): at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:239)
W/System.err( 7077): at libcore.net.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:80)
W/System.err( 7077): at com.lukemovement.roottoolbox.pro.Update.getHttpString(Update.java:166)
W/System.err( 7077): at com.lukemovement.roottoolbox.pro.Update.checkForUpdate(Update.java:98)
W/System.err( 7077): at com.lukemovement.roottoolbox.pro.Update.onStart(Update.java:75)
W/System.err( 7077): at android.app.Service.onStartCommand(Service.java:450)
W/System.err( 7077): at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2620)

W/System.err( 7077): at android.app.ActivityThread.access$1900(ActivityThread.java:143)
W/System.err( 7077): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1306)
W/System.err( 7077): at android.os.Handler.dispatchMessage(Handler.java:99)
W/System.err( 7077): at android.os.Looper.loop(Looper.java:137)
W/System.err( 7077): at android.app.ActivityThread.main(ActivityThread.java:4935)
W/System.err( 7077): at java.lang.reflect.Method.invokeNative(Native Method)
W/System.err( 7077): at java.lang.reflect.Method.invoke(Method.java:511)
W/System.err( 7077): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)
W/System.err( 7077): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:558)
W/System.err( 7077): at dalvik.system.NativeStart.main(Native Method)

I/Example update( 7077): Invalid int: ""


so has android given up on being backwards compatible or have just just forgotten to add this bit in?



ive read that i need to use AsyncTask. but i cant seem to get it to work for me, could anyone help me with this please?


Answer



From Android API v15, it requires no heavy process working on main thread.
So you should move your logic to another thread like bellow source code:




new Thread(new Runnable() {
public void run() {
// your logic
}
}).start();


More information please refer: Responsiveness


css - Show mat-icon on hover




I have mat-list in my html template:





add {{ item.title }}



I want to display mat-icon only on mat-list-item hover. So I come up with this css:



mat-icon {
display: none;

}

mat-list-item:hover + mat-icon {
display: block;
}


But for some reason it is does not work



However if I do try to change the background color it is works:




mat-list-item:hover {
background-color: #3f51b5;
}


It is probably something to do with mat-icon
Thoughts?


Answer



try this




mat-icon{
display: none;
}

mat-list-item:hover mat-icon{
display: block;
}



you do not need + adjacent selectors



demo


c# - How do I round a decimal value to 2 decimal places (for output on a page)



When displaying the value of a decimal currently with .ToString(), it's accurate to like 15 decimal places, and since I'm using it to represent dollars and cents, I only want the output to be 2 decimal places.



Do I use a variation of .ToString() for this?



Answer



decimalVar.ToString ("#.##"); // returns "" when decimalVar == 0


or



decimalVar.ToString ("0.##"); // returns "0"  when decimalVar == 0

Why does Google's R style guide recommend




I read the Google style guide for R. For "Assignment", they say:





Use <-, not =, for assignment.



GOOD:
x <- 5



BAD:
x = 5




Can you tell me what the difference is between these two methods of assignment, and why one is to be preferred over the other?



Answer



I believe there are two reasons. One is that <- and = have slightly different meanings depending on context. For example, compare the behavior of the statements:



printx <- function(x) print(x)
printx(x="hello")
printx(x<-"hello")


In the second case, printx(x<-"hello") will also assign to the parent scope, whereas printx(x="hello") will only set the parameter.




The other reason is for historical purposes. Both R, S and the "APL" languages they were based on only allowed arrow key for assignment (which historically was only one character). Ref: http://blog.revolutionanalytics.com/2008/12/use-equals-or-arrow-for-assignment.html


php - Can't use function return value in write context Laravel 4



I'm getting the Can't use function return value in write context error on line 430 in my code, but I can't understand why I'm getting this error..



Strange thing is, I only get this error on the server (PHP 5.3) and not on my localhost (PHP 5.5.10)




return  Redirect::route('account-activate-user', (empty(Input::get('code'))) ? '{code}' : e(Input::get('code')))
->with('global', 'De activatie-code is niet geldig.');


Does anyone have the solution to this problem?


Answer



It happens because you're using empty() with the return value of a function (Input::get()), when it only accepts a variable. Considering how Input::get() works, i.e. you can pass a 2nd parameter as a default value when the input isn't set, you can skip the empty() check altogether and just use:



return  Redirect::route('account-activate-user', Input::get('code', '{code}'))

->with('global', 'De activatie-code is niet geldig.');


or, closer to your code:



return  Redirect::route('account-activate-user', (Input::has('code') ? '{code}' : e(Input::get('code')))
->with('global', 'De activatie-code is niet geldig.');

python - Change data type of columns in Pandas




I want to convert a table, represented as a list of lists, into a Pandas DataFrame. As an extremely simplified example:



a = [['a', '1.2', '4.2'], ['b', '70', '0.03'], ['x', '5', '0']]
df = pd.DataFrame(a)


What is the best way to convert the columns to the appropriate types, in this case columns 2 and 3 into floats? Is there a way to specify the types while converting to DataFrame? Or is it better to create the DataFrame first and then loop through the columns to change the type for each column? Ideally I would like to do this in a dynamic way because there can be hundreds of columns and I don't want to specify exactly which columns are of which type. All I can guarantee is that each columns contains values of the same type.


Answer



You have three main options for converting types in pandas:





  1. to_numeric() - provides functionality to safely convert non-numeric types (e.g. strings) to a suitable numeric type. (See also to_datetime() and to_timedelta().)


  2. astype() - convert (almost) any type to (almost) any other type (even if it's not necessarily sensible to do so). Also allows you to convert to categorial types (very useful).


  3. infer_objects() - a utility method to convert object columns holding Python objects to a pandas type if possible.




Read on for more detailed explanations and usage of each of these methods.









The best way to convert one or more columns of a DataFrame to numeric values is to use pandas.to_numeric().



This function will try to change non-numeric objects (such as strings) into integers or floating point numbers as appropriate.



Basic usage



The input to to_numeric() is a Series or a single column of a DataFrame.




>>> s = pd.Series(["8", 6, "7.5", 3, "0.9"]) # mixed string and numeric values
>>> s
0 8
1 6
2 7.5
3 3
4 0.9
dtype: object

>>> pd.to_numeric(s) # convert everything to float values

0 8.0
1 6.0
2 7.5
3 3.0
4 0.9
dtype: float64


As you can see, a new Series is returned. Remember to assign this output to a variable or column name to continue using it:




# convert Series
my_series = pd.to_numeric(my_series)

# convert column "a" of a DataFrame
df["a"] = pd.to_numeric(df["a"])


You can also use it to convert multiple columns of a DataFrame via the apply() method:



# convert all columns of DataFrame

df = df.apply(pd.to_numeric) # convert all columns of DataFrame

# convert just columns "a" and "b"
df[["a", "b"]] = df[["a", "b"]].apply(pd.to_numeric)


As long as your values can all be converted, that's probably all you need.



Error handling




But what if some values can't be converted to a numeric type?



to_numeric() also takes an errors keyword argument that allows you to force non-numeric values to be NaN, or simply ignore columns containing these values.



Here's an example using a Series of strings s which has the object dtype:



>>> s = pd.Series(['1', '2', '4.7', 'pandas', '10'])
>>> s
0 1
1 2

2 4.7
3 pandas
4 10
dtype: object


The default behaviour is to raise if it can't convert a value. In this case, it can't cope with the string 'pandas':



>>> pd.to_numeric(s) # or pd.to_numeric(s, errors='raise')
ValueError: Unable to parse string



Rather than fail, we might want 'pandas' to be considered a missing/bad numeric value. We can coerce invalid values to NaN as follows using the errors keyword argument:



>>> pd.to_numeric(s, errors='coerce')
0 1.0
1 2.0
2 4.7
3 NaN
4 10.0

dtype: float64


The third option for errors is just to ignore the operation if an invalid value is encountered:



>>> pd.to_numeric(s, errors='ignore')
# the original Series is returned untouched


This last option is particularly useful when you want to convert your entire DataFrame, but don't not know which of our columns can be converted reliably to a numeric type. In that case just write:




df.apply(pd.to_numeric, errors='ignore')


The function will be applied to each column of the DataFrame. Columns that can be converted to a numeric type will be converted, while columns that cannot (e.g. they contain non-digit strings or dates) will be left alone.



Downcasting



By default, conversion with to_numeric() will give you either a int64 or float64 dtype (or whatever integer width is native to your platform).




That's usually what you want, but what if you wanted to save some memory and use a more compact dtype, like float32, or int8?



to_numeric() gives you the option to downcast to either 'integer', 'signed', 'unsigned', 'float'. Here's an example for a simple series s of integer type:



>>> s = pd.Series([1, 2, -7])
>>> s
0 1
1 2
2 -7
dtype: int64



Downcasting to 'integer' uses the smallest possible integer that can hold the values:



>>> pd.to_numeric(s, downcast='integer')
0 1
1 2
2 -7
dtype: int8



Downcasting to 'float' similarly picks a smaller than normal floating type:



>>> pd.to_numeric(s, downcast='float')
0 1.0
1 2.0
2 -7.0
dtype: float32








The astype() method enables you to be explicit about the dtype you want your DataFrame or Series to have. It's very versatile in that you can try and go from one type to the any other.



Basic usage



Just pick a type: you can use a NumPy dtype (e.g. np.int16), some Python types (e.g. bool), or pandas-specific types (like the categorical dtype).




Call the method on the object you want to convert and astype() will try and convert it for you:



# convert all DataFrame columns to the int64 dtype
df = df.astype(int)

# convert column "a" to int64 dtype and "b" to complex type
df = df.astype({"a": int, "b": complex})

# convert Series to float16 type
s = s.astype(np.float16)


# convert Series to Python strings
s = s.astype(str)

# convert Series to categorical type - see docs for more details
s = s.astype('category')


Notice I said "try" - if astype() does not know how to convert a value in the Series or DataFrame, it will raise an error. For example if you have a NaN or inf value you'll get an error trying to convert it to an integer.




As of pandas 0.20.0, this error can be suppressed by passing errors='ignore'. Your original object will be return untouched.



Be careful



astype() is powerful, but it will sometimes convert values "incorrectly". For example:



>>> s = pd.Series([1, 2, -7])
>>> s
0 1
1 2

2 -7
dtype: int64


These are small integers, so how about converting to an unsigned 8-bit type to save memory?



>>> s.astype(np.uint8)
0 1
1 2
2 249

dtype: uint8


The conversion worked, but the -7 was wrapped round to become 249 (i.e. 28 - 7)!



Trying to downcast using pd.to_numeric(s, downcast='unsigned') instead could help prevent this error.









Version 0.21.0 of pandas introduced the method infer_objects() for converting columns of a DataFrame that have an object datatype to a more specific type (soft conversions).



For example, here's a DataFrame with two columns of object type. One holds actual integers and the other holds strings representing integers:



>>> df = pd.DataFrame({'a': [7, 1, 5], 'b': ['3','2','1']}, dtype='object')
>>> df.dtypes
a object
b object
dtype: object



Using infer_objects(), you can change the type of column 'a' to int64:



>>> df = df.infer_objects()
>>> df.dtypes
a int64
b object
dtype: object



Column 'b' has been left alone since its values were strings, not integers. If you wanted to try and force the conversion of both columns to an integer type, you could use df.astype(int) instead.


java - Issue when using a custom font - "native typeface cannot be made"



I'm trying to use a font I found on the internet, but the problem is that I get an FC with "native typeface cannot be made".



Here is the code in the getView of my ListVIew:



        holder.tv_SuraName   =(TextView)convertView.findViewById(R.id.Start_Name);
holder.tv_SuraName.setTypeface(Typeface.createFromAsset(mContext.getAssets(), "suralist_font.ttf"));



Can anyone tell me why can I use the custom rom? You can get it HERE .. the file is .ttf


Answer



The font file is either corrupt or unsupported for some reason. You can drop it on the SD card and load it from file, to make sure it's not a problem with your assets.


php - Read session when click back button instead of $_POST value

I have 3 page, and pass value using $_POST method. The reason not using $_GET method is I don't want user go to the url and change the value and able to pass value. From the beginning for t2 and t3 page:




  1. t2 and t3 will check if(isset($_POST)) then save to the session.

  2. When t3.php user click on back button, t3 not passing $_POST data and read session




It is able to work when passing data from t1 to t2 and t2 to t3, but when click on back button from t3 to t2, the browser show "Confirm Form Resubmission". How can I make the page read the session data instead of the $_POST value when user hit the back button?



t1.php






value1:

value2:








t2.php




session_start();

if(isset($_POST)){
unset($_SESSION['t2']);
$_SESSION['t2']=$_POST;
}else if(isset($_SESSION['t2'])){

}else{
header("Location: http://localhost/my_project/t1.php");
}


?>



value1!
value2 .


value1:

value2:









t3.php




session_start();

if(isset($_POST)){
unset($_SESSION['t3']);
$_SESSION['t3']=$_POST;
}else if(isset($_SESSION['t3'])){

}else{
header("Location: http://localhost/my_project/t1.php");

}

?>



value1!
value2 .




c# - I can not put single double quotes ' " ' in a string for regex pattern

I am trying to build regex pattern but the string doesn't take single double quotes.



this is the pattern and it crashes when I add \"




@"(?<\"|\'|\“)(?'first'{0}\s(?'middle'{0}{1}{2}"

regex - Regular Expressions AND

I am really not good with regular expressions and I come here for some assistance :). I am trying to combine regular expressions with something like AND. For example if we have a text file with:



abc1-xyz

abc1-ertxyz


abc1xyz

postxyz

abc1


I would like to match everything that starts with "abc1" AND also contains the letters "xyz" somewhere.



I know that I can start with:




/^abc1/


but I am not sure how to combine so it can also match to contain "xyz".



Thank you for your assistance in advance.

What is a secure way to send an email using Python and Gmail as the provider?




I am trying to send emails to myself using a Python script, and luckily I came across this post:



How to send an email with Gmail as provider using Python?



The trouble is, smtplib sends out the password for the script in plain text and I am skeptical about its security. Further my script contains my username and password in plain text. Are there any good ways to use Python and send emails without having to keep my password as plain text?



I also saw this on StackOverflow:
Python smtplib security
but the answer is not completely helping me resolve this conflict. However, I'm not ready to give up yet.







Some more information: I'm trying to set up my Raspberry Pi as a server that scrapes through a website. When a specific thing about the website changes, I want to be notified via email. However, I don't want to leave my Pi sitting around with a script that has my username and password in plain text.


Answer



The connection uses STARTTLS, so its not being sent over the internet in clear text.



The function server.starttls() starts the encrypted communication with the server on port 465 instead of the normal port 25 for unencrypted SMTP mail traffic.


java.lang.RuntimeException: Unable to start activity ComponentInfo: java.lang.ClassCastException: cannot be cast to android.widget.Button

I tried to get this code working using android studio but the app in the emulator crashes everytime I run it and displays an error which is "App has stopped". I looked at the logcat and got this error.



Logcat:



02-11 12:39:49.826 4852-4852/co5025.example.com.week10 E/AndroidRuntime: FATAL EXCEPTION: main
Process: co5025.example.com.week10, PID: 4852
java.lang.RuntimeException: Unable to start activity ComponentInfo{co5025.example.com.week10/co5025.example.com.week10.MainActivity}: java.lang.ClassCastException: android.support.v7.widget.AppCompatEditText cannot be cast to android.widget.Button
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by: java.lang.ClassCastException: android.support.v7.widget.AppCompatEditText cannot be cast to android.widget.Button
at co5025.example.com.week10.MainActivity.onCreate(MainActivity.java:42)
at android.app.Activity.performCreate(Activity.java:6664)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6077) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755) 



MainActivity.java



package co5025.example.com.week10;

import android.app.FragmentManager;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.support.v4.app.FragmentManager.BackStackEntry;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
EditText editUsername;
EditText editPassword;
TextView errorMessage;
Button butLogin;
private FragmentManager.BackStackEntry v;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);

FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
editPassword = (EditText) findViewById(R.id.edit_password);
editUsername = (EditText) findViewById(R.id.edit_username);
butLogin = (Button) findViewById(R.id.edit_username);
butLogin.setOnClickListener(this);

if (getIntent().getBooleanExtra("EXIT", false)) finish();
}

@Override
public void onClick(View view) {
if (checkPassword()) {
Intent i;
switch (v.getId()) {
case R.id.but_login:
i = new Intent(this, GameActivity.class);
startActivity(i);
break;
}
}else{
errorMessage = (TextView) findViewById(R.id.error_message);
errorMessage.setText("Error: Incorrect Password/Username. Try again!");
}
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();

//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}

return super.onOptionsItemSelected(item);
}

public boolean checkPassword(){
if (editUsername.getText().toString().equals("test") &&
(editPassword.getText().toString().equals("1234")))
return true;
else
return false;
}
}

csv - Blank screen with d3js

I am fairly new to computer programming and d3js. I am trying to replicate this bar graph found on the d3js website http://bl.ocks.org/mbostock/b2fee5dae98555cf78c9e4c5074b87c3.
I copied the code exactly and created a CSV file with the necessary data to create the bar graph. But whenever I try running the code the axis is the only thing that comes up. I am not sure if the error is within the CSV file or how I try to call the data. I just know the error is somewhere on my part.



Here's a sample of the CSV file (condensed):




    id,case,date
10097071,HY285524,06/02/2015 09:41:19 PM
21907,HY291065,06/07/2015 03:50:00 AM
21908,HY291065,06/07/2015 03:50:00 AM
10156667,HY345298,07/18/2015 03:17:00 AM


Here's how I have been trying to call it:



    d3.csv("homicides.csv", type, function(error, data) {

if (error) throw error;

var bins = histogram(data);

y.domain([0, d3.max(bins, function(d) { return d.length; })]);


Any help would be appreciated!

pointers - C: free memory allocated in c

suppose i have a struct:



typedef struct{
char *ID;
char *name;
float price;
int quantity;
} Generic_Properties;


now if i have used malloc to allocate space in the heap for it and saved the address in a pointer, lets call him p1. now i want to free that specific memory block, is it enough to just declare free(p1):



free(p1);


or do i need to separately free ID and name pointers, because I used malloc to allocated space for the string they're pointing to?

php - Is using is_string() a good defense against SQL Injection?

I was trying to look for mitigation of SQL Injection against my web application based on PHP and MySQL. The first rule is to sanitize the query; Hence I am using mysql_real_escape_string() function for that



Here is what my snippet looks like



if (is_string($string)) {

return $mysqli->real_escape_string($string);
} else {
return "";
}


Here, $string would contain the user-input. After this filtering and escaping, I would use INSERT INTO query to insert into database.



This filter, will thwart any malicious user inputs like haha' , inj'' etc as is_string() will detect those string and apply real_escape_string() to escape those evil characters. The only possibility I can think an attacker can do is use a Numeric payload for SQL Injection but I don't know any Numeric payload itself has caused Injection yet so far.




So, will this filter keep away the bad guys or is it bypassable ?



EDIT:
I know Prepared statements are much better and a good coding practice while launching app in production. But for this question, I am specifically looking answer to how anyone can thwart this filter itself because it does seem strong to me!

java - Differences between HashMap and Hashtable?



What are the differences between a HashMap and a Hashtable in Java?



Which is more efficient for non-threaded applications?



Answer



There are several differences between HashMap and Hashtable in Java:




  1. Hashtable is synchronized, whereas HashMap is not. This makes HashMap better for non-threaded applications, as unsynchronized Objects typically perform better than synchronized ones.


  2. Hashtable does not allow null keys or values. HashMap allows one null key and any number of null values.


  3. One of HashMap's subclasses is LinkedHashMap, so in the event that you'd want predictable iteration order (which is insertion order by default), you could easily swap out the HashMap for a LinkedHashMap. This wouldn't be as easy if you were using Hashtable.




Since synchronization is not an issue for you, I'd recommend HashMap. If synchronization becomes an issue, you may also look at ConcurrentHashMap.



web - What is the difference between local storage and cache in the browser?

When we open application segment in the developer console of chrome, we see many things like:




  • Application





    • Manifest

    • service Workers


  • Storage




    • local storage

    • session storage

    • indexed db

    • Web sql


    • Cookies


  • Cache




    • Cache Storage

    • Application Cache





I know that cache is used for saving the resource locally and cookies are for saving the data in the client side for maintaining the session.
Cache stores in key value format.



I want to know exactly what the difference is between them.

Wednesday, January 30, 2019

c# - SQL Injections with replace single-quotation and validate integers












I just want to know, If I replace every ' with '' in user inputs, for instance string.Replace("'","''"), and validate numbers (make sure that they are numbers, and do not contain any other character), is SQL Injection still possible? How?



I'm using dynamic SQL queries, using SqlCommand. Something like this:



cmd.CommandText = "SELECT * FROM myTable WHERE ID = " + theID.ToString();


or



cmd.CommandText = "UPDATE myTable SET title='" + title.Replace("'","''") + "' WHERE ID = " + theID.ToString();



Input integers are automatically validated (checked whether they are a real number) in ASP.NET MVC.


Answer



If this is a legacy project that is coded this way then, whilst not optimal, I'm not currently aware of any way that it can be susceptible to SQL injection as long as every string is treated in that manner and the queries are just simple ones as you have shown.



I cannot state any more certainty than that however. Without using parametrised queries there is always the possibility that there is some vulnerability that you have not yet considered.



Manually escaping the quotes yourself is error prone and can sometimes fail in ways that are difficult to anticipate in advance. For example with the following table




CREATE TABLE myTable(title VARCHAR(100))
INSERT INTO myTable VALUES('Foo')


And stored procedure using dynamic SQL built up with string concatenation



CREATE PROC UpdateMyTable
@newtitle NVARCHAR(100)
AS
/*

Double up any single quotes
*/
SET @newtitle = REPLACE(@newtitle, '''','''''')

DECLARE @UpdateStatement VARCHAR(MAX)

SET @UpdateStatement = 'UPDATE myTable SET title=''' + @newtitle + ''''

EXEC(@UpdateStatement)



You can try the following



Normal update



EXEC UpdateMyTable N'Foo'
SELECT * FROM myTable /*Returns "Foo"*/


SQL Injection attempt foiled




EXEC UpdateMyTable N''';DROP TABLE myTable--'
SELECT * FROM myTable /*Returns "';DROP TABLE myTable--"*/


SQL Injection attempt succeeds and drops the table



EXEC UpdateMyTable N'ʼ;DROP TABLE myTable--'
SELECT * FROM myTable /*Returns "Invalid object name 'myTable'."*/



The issue here is that the third query passes U+02BC instead of the standard apostrophe and then the string is assigned to a varchar(max) after the sanitation occurs which silently converts this to a regular apostrophe.



Until I read the answer here that issue would never have occurred to me.


php - Where is the mysqli prepared statement query error?



I'm trying to create a mysqli prepared statement where I import tables from an odbc connected database into a mysql database, I'm getting this error with 106-column wide table query.




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 '? (ID, column1, column2, column3, column4, ' at line 1"




When I echo out the query here it is...




INSERT INTO ? (ID, column1, column2, column3, column4, ...106 total columns... ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,

?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
?, ?)




$sql = "SELECT * FROM $table WHERE $key = '$acct'";
$link = getODBCConnection();
$result = odbc_do($link, $sql);
$data = array();
while ($row = odbc_fetch_array($result)) {

//store all query rows as array
array_push($data, $row);
}
//insert into mysql table of the same name
//get column count from first row
$columns = count($data[0]);
$params = str_repeat(" ?,",$columns);
$params = rtrim($params,',');
$types = str_repeat("s",$columns+1);
$fields = implode(", ", array_keys($data[0]));

$sql = "INSERT INTO ? ($fields) VALUES ($params) ON DUPLICATE KEY UPDATE";
echo $sql."
";
$link = getSalesConnection();
$stmt = $link->prepare($sql);
var_dump($link->error);
foreach ($data as $row) {
$stmt->bind_param($types, $table, implode(", ",array_values($row)));
$stmt->execute();
}



I've tried this using standard bind_param and also using the call_user_func_array() method. I've tried quoting my parameter strings and the column names, without effect. If there was an error with my bind_param types I should not have an error on the prepare statement should I? But there is some problem with the SQL going to the prepare command that I can't pinpoint. Please help!


Answer



Query parameters can be used in place of scalar values only. You can't parameterize table names, column names, SQL expressions, keywords, lists of values, etc.




  • WRONG: SELECT ?, b, c FROM t WHERE a = 1 ORDER BY b ASC
    The parameter value will be a literal value, not the name of a column.


  • WRONG: SELECT a, b, c FROM ? WHERE a = 1 ORDER BY b ASC
    Syntax error.


  • WRONG: SELECT a, b, c FROM t WHERE ? = 1 ORDER BY b ASC
    The parameter value will be a literal value, not the name of a column.


  • WRONG: SELECT a, b, c FROM t WHERE a IN (?) ORDER BY b ASC
    The parameter value will be a single literal value, not a list of values, even if you pass a string of comma-separated values.



  • WRONG: SELECT a, b, c FROM t WHERE a = 1 ORDER BY ? ASC
    The parameter value will be a literal value, not the name of a column.


  • WRONG: SELECT a, b, c FROM t WHERE a = 1 ORDER BY b ?
    Syntax error.




Basically if you could write a string literal, date literal, or numeric literal in place of the query parameter, it should be okay. Otherwise you have to interpolate the dynamic content into the SQL string before you prepare() it.


codeigniter - find missing extension - php on ubuntu 12.04



Just setup a new installation in ubuntu-12.04,then setup one codeigniter script it said nothing, eventually i found out that curl extension was missing by comparing arrays get_loaded_extensions() with my workmate, so i installed it.



I tried using die inside the framework system files, but nothing came out.
But, now i have installed another script, error_reporting() is set to E_ALL, it just says nothing. What is the best way to figure out missing extensions?


Answer



I went through whole php.ini and finally found that it was




display_errors = off


so i changed it to On, and it worked!!


analysis - What happened to the last of the sins in Se7en? - Movies & TV



I have watched Se7en and followed Gluttony, Greed, Sloth and Lust. But I couldn't place the events of the other sins: Envy, Wrath and Pride.




And also is the scene in which the head of a woman (detective's wife?) is brought, connected to any of these scenes in some way?




Please provide some light on these. I am really confused.


Answer




Envy is killing the wife of the policeman. As mentioned on Wikipedia:




...Doe claims to represent the sin of "Envy"; he was jealous of Mills' normal life, and killed Tracy after failing to "play husband" with her...




Wrath is the policeman killing the murderer. I can't remember pride, I should re-watch it to spot it but the Wikipedia page states:




Some time later, they investigate the death of a young model whose

face had been mutilated. Having chosen to kill herself rather than
live with a disfigured face, she is the victim of "Pride".




The point of the movie was that the killer used the detective to complete the series.


Creating multiline strings in JavaScript



I have the following code in Ruby. I want to convert this code into JavaScript. what's the equivalent code in JS?



text = <<"HERE"
This
Is
A
Multiline
String

HERE

Answer



Update:



ECMAScript 6 (ES6) introduces a new type of literal, namely template literals. They have many features, variable interpolation among others, but most importantly for this question, they can be multiline.



A template literal is delimited by backticks:



var html = `


Some HTML here

`;


(Note: I'm not advocating to use HTML in strings)



Browser support is OK, but you can use transpilers to be more compatible.







Original ES5 answer:



Javascript doesn't have a here-document syntax. You can escape the literal newline, however, which comes close:



"foo \
bar"

Insert data mysqli and php in form 1 and return to new form 2

Hi all I am new to mysqli and php (currently studying and trying to work on a test database- I have not used security measures at this wont be available public) and trying to get the information I have just submitted in the form to display in a new form which will then receive further user input then submitted to database. Here is an example of what I have done so far:



Form 1 (customer table - cust id =primary key)

Customer Details ie name address telephone etc
dynamic drop down box - consists of 4 options.( would like whatever option is selected here to return a particular form)



The form is currently submitting correctly in the database, but I would like once it has submitted to the database to return the customer info (including the customer id as that is the relationship in the new table) and on the form2(service table - service id is primary key) so the user can input further data to the form and submit.



Hope this makes sense, any help would be appreciated.
Thanks



Response 1
Thank you for my response I probably havent made myself very clear.




Form 1 where dynamic dropdown list is - when user submits forms I would like it to return form 2 with the customer info we inserted in form 1



Form 1







test




First Name:
Last Name:


Business Name:


Contact Number:
Alt Number:


Email Address:


Street No:

Street Name:


Suburb:
Postal Code:
State:



**

Type of Service Required:











Query in separate file




$fname=$_POST['firstname'];
$lname=$_POST['lastname'];

$bname=$_POST['businessname'];
$phone=$_POST['number'];
$altphone=$_POST['altno'];
$email=$_POST['email'];
$streetno=$_POST['streetno'];
$street=$_POST['street'];
$suburb=$_POST['suburb'];
$postcode=$_POST['postalcode'];
$state=$_POST['state'];
$service=$_POST['category'];





// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}


$sql = "INSERT INTO customer (contactFirstName,contactLastName,businessName,contactNumber,altNumber,email,streetNo,streetName,suburb,postalCode,state,serviceType)
VALUES ('$fname','$lname','$bname','$phone','$altphone','$email','$streetno','$street','$suburb','$postcode','$state','$service')";



if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "
" . $conn->error;

}
$conn->close();
?>

c++ - Is the default Move constructor defined as noexcept?



It seems that a vector will check if the move constructor is labeled as noexcept before deciding on whether to move or copy elements when reallocating. Is the default move constructor defined as noexcept? I saw the following documentation but it didn't specify this.http://en.cppreference.com/w/cpp/language/move_constructor




Implicitly-declared move constructor




If no user-defined move
constructors are provided for a class type (struct, class, or union),
and all of the following is true: there are no user-declared copy
constructors there are no user-declared copy assignment operators
there are no user-declared move assignment operators there are no
user-declared destructors the implicitly-declared move constructor is
not defined as deleted due to conditions detailed in the next section
then the compiler will declare a move constructor as an inline public
member of its class with the signature T::T(T&&) A class can have
multiple move constructors, e.g. both T::T(const T&&) and T::T(T&&).

If some user-defined move constructors are present, the user may still
force the generation of the implicitly declared move constructor with
the keyword default.



Answer



I think the answer is 15.4/14 (Exception specifications):




An inheriting constructor (12.9) and an implicitly declared special member function (Clause 12) have an exception-specification. If f is an inheriting constructor or an implicitly declared default constructor, copy constructor, move constructor, destructor, copy assignment operator, or move assignment operator, its implicit exception-specification specifies the type-id T if and only if T is allowed by the exception-specification
of a function directly invoked by f’s implicit definition; f allows all exceptions if any function it directly invokes allows all exceptions, and f has the exception-specification noexcept(true) if every function it directly invokes allows no exceptions.





Basically, it Does What You Think, and the implicitly-declared move constructor is noexcept whenever it can be.


android - Why does ListActivity not display last item in ArrayAdapter?

I am using the following code for my main activity:




private TripsData datasource;

@Override
protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

datasource = new TripsData(this);
datasource.open();

List values = datasource.getAllTrips();

ArrayAdapter adapter = new ArrayAdapter(this,
android.R.layout.simple_list_item_1, values);

setListAdapter(adapter);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}


// Will be called via the onClick attribute
// of the buttons in main.xml
public void onClick(View view) {
@SuppressWarnings("unchecked")
ArrayAdapter adapter = (ArrayAdapter) getListAdapter();
Trip trip = null;
//Trip trip_temp;
switch (view.getId()) {
case R.id.add:
trip=newTrip(view);

//trip.setId(trip_temp.getId());
//trip.setName(trip_temp.getName());
adapter.add(trip);
break;

case R.id.delete:
if (getListAdapter().getCount() > 0) {
trip = (Trip) getListAdapter().getItem(0);
datasource.deleteTrip(trip);
adapter.remove(trip);

}
break;
}
adapter.notifyDataSetChanged();
}

@Override
protected void onResume() {
datasource.open();
super.onResume();

}

@Override
protected void onPause() {
datasource.close();
super.onPause();
}

public Trip newTrip(View view){
final Trip trip=new Trip();

//create DialogBox
final Dialog dialog = new Dialog(this);
//modify features BEFORE setting content view
//dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.project_dialog);
//Create EditBoxes for Dialog
final EditText nameEdit=(EditText) dialog.findViewById(R.id.dialog_name_text);
final EditText descEdit=(EditText) dialog.findViewById(R.id.dialog_type_text);
//define button's text
View dialogButton=dialog.findViewById(R.id.dialog_button_create);

TextView text=(TextView) dialogButton;
text.setText("Create");
//Button Creation
Button createButton = (Button) dialogButton;
// if button is clicked, close the custom dialog
createButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Trip trip_temp = datasource.createTrip(nameEdit.getText().toString());
//String[] trips = new String[] { "Cool", "Very nice", "Hate it" };

//int nextInt = new Random().nextInt(3);
// save the new comment to the database
trip.setId(trip_temp.getId());
trip.setName(trip_temp.getName());
//trip = datasource.createTrip(nameEdit.getText().toString());
dialog.dismiss();
}
});
dialog.show();
return trip;

}



The user should be able to input values in the dialog box and the Name would be displayed in the list of created Trips. However, there seems to be a bug when there is only one value in the List because that item is not displayed. I've spent hours on this and can't figure it out.



EDIT:
This is my TripsData code



public class TripsData {




private SQLiteDatabase database;
private TripsDB dbHelper;
private String[] allTrips = { TripsDB.TRIP_COLUMN_ID,
TripsDB.TRIP_COLUMN_TYPE};

public TripsData(Context context){
dbHelper = new TripsDB(context);
}


public void open() throws SQLException{
database = dbHelper.getWritableDatabase();
}

public void close(){
dbHelper.close();
}

public Trip createTrip(String type){
ContentValues values = new ContentValues();

values.put(TripsDB.TRIP_COLUMN_TYPE, type);
long insertId = database.insert(TripsDB.TABLE_TRIPS, null, values);
Cursor cursor = database.query(TripsDB.TABLE_TRIPS,
allTrips, TripsDB.TRIP_COLUMN_ID + " = " + insertId, null, null, null, null);
cursor.moveToFirst();
Trip newTrip = cursorToTrip(cursor);
cursor.close();
return newTrip;
}


public void deleteTrip(Trip trip){
long id = trip.getId();
System.out.println("Project deleted with id: " + id);
database.delete(TripsDB.TABLE_TRIPS, TripsDB.TRIP_COLUMN_ID
+ " = " + id, null);
}

public List getAllTrips(){
List trips = new ArrayList();


Cursor cursor = database.query(TripsDB.TABLE_TRIPS,
allTrips, null, null, null, null, null);

cursor.moveToFirst();
while(!cursor.isAfterLast()){
Trip trip = cursorToTrip(cursor);
trips.add(trip);
cursor.moveToNext();
}
cursor.close();

return trips;
}

private Trip cursorToTrip(Cursor cursor){
Trip trip = new Trip();
trip.setId(cursor.getLong(0));
trip.setName(cursor.getString(1));
return trip;
}

angularjs - Best practice looping through a JavaScript object





I have the following JavaScript object which I need to apply parseFloat to any number value field (in order for ngTable to sort correctly).



I'm having a tough time looping through the Object to do this. I've tried a nested angular.forEach, but I have scoping issues (inner loops don't see outer variables).



What's the best manner to approach this?




The Object names (i.e: Person and PersonDetails) are dynamic. :/



My object:



{
"data": [
{
"Person": {
"id" : "1",

"age": "23",
"days": "5",
"first_name": "Joe",
"last_name": "Smith",
},
"PersonDetails": {
"id": "4",
"name": "Cousin",
"oldest: "2",
}

},
{
"Person": {
"id" : "2",
"age": "18",
"days": "3",
"first_name": "John",
"last_name": "Doe",
},
"PersonDetails": {

"id": "4",
"name": "Second Cousin",
"oldest: "3",
}
}
...
...
]
};


Answer



You can do a test like this:



function representsNumber(str) {
return str === (+str).toString();
}

// E.g. usage
representsNumber('a'); // false
representsNumber([]); // false

representsNumber(1); // false (it IS a number)
representsNumber('1.5'); // true
representsNumber('-5.1'); // true
representsNumber('NaN'); // true


And recurse over all your nodes. Overkill example:



function seeker(o, test, _true, _false) {
_true || (_true = function (e) {return e;});

_false || (_false = function (e) {return e;});
function recursor(o) {
var k;
if (o instanceof Array)
for (k = 0; k < o.length; ++k) // Iterate over an array
if (typeof o[k] !== 'object')
o[k] = test(o[k]) ? _true(o[k]) : _false(o[k]);
else
recursor(o[k]);
else

for (k in o) // Iterate over an object
if (typeof o[k] !== 'object')
o[k] = test(o[k]) ? _true(o[k]) : _false(o[k]);
else
recursor(o[k]);
}
if (typeof o === "object")
return recursor(o), o;
else
return test(o) ? _true(o) : _false(o); // Not an object, just transform

}

// Sample usage
seeker({foo: [{bar: "20"}]}, representsNumber, parseFloat);
// {foo: [{bar: 20}]}

ruby - Match all occurrences of a regex



Is there a quick way to find every match of a regular expression in Ruby? I've looked through the Regex object in the Ruby STL and searched on Google to no avail.


Answer



Using scan should do the trick:



string.scan(/regex/)


Tuesday, January 29, 2019

layout - How to get screen dimensions as pixels in Android



I created some custom elements, and I want to programmatically place them to the upper right corner (n pixels from the top edge and m pixels from the right edge). Therefore I need to get the screen width and screen height and then set position:



int px = screenWidth - m;

int py = screenHeight - n;


How do I get screenWidth and screenHeight in the main Activity?


Answer



If you want the display dimensions in pixels you can use getSize:



Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);

int width = size.x;
int height = size.y;


If you're not in an Activity you can get the default Display via WINDOW_SERVICE:



WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();



If you are in a fragment and want to acomplish this just use Activity.WindowManager (in Xamarin.Android) or getActivity().getWindowManager() (in java).



Before getSize was introduced (in API level 13), you could use the getWidth and getHeight methods that are now deprecated:



Display display = getWindowManager().getDefaultDisplay(); 
int width = display.getWidth(); // deprecated
int height = display.getHeight(); // deprecated


For the use case you're describing however, a margin/padding in the layout seems more appropriate.




Another way is: DisplayMetrics




A structure describing general information about a display, such as its size, density, and font scaling. To access the DisplayMetrics members, initialize an object like this:




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



We can use widthPixels to get information for:




"The absolute width of the display in pixels."




Example:



Log.d("ApplicationTagName", "Display width in px is " + metrics.widthPixels);


javascript - PHP if else condition inside JS file Wordpress theme customizer condition

$('.class1').append( '' );
var button = $('.class1.load-more');



the above is a code from the .js file of WP infinite scroll Wordpress plugin.



Can we somehow put a PHP condition inside a js file:



If( logical condition 1 )  {
$('.class1').append( '' );
var button = $('.class1.load-more');
} elseif( logical condition 2 ) {

$('.class2').append( '' );
var button = $('.class2 .load-more');
}


P.S.: PHP logic should go inside a js file not script<> tags.

c++ faq - The Definitive C++ Book Guide and List

This question attempts to collect the few pearls among the dozens of bad C++ books that are published every year.



Unlike many other programming languages, which are often picked up on the go from tutorials found on the Internet, few are able to quickly pick up C++ without studying a well-written C++ book. It is way too big and complex for doing this. In fact, it is so big and complex, that there are very many very bad C++ books out there. And we are not talking about bad style, but things like sporting glaringly obvious factual errors and promoting abysmally bad programming styles.



Please edit the accepted answer to provide quality books and an approximate skill level — preferably after discussing your addition in the C++ chat room. (The regulars might mercilessly undo your work if they disagree with a recommendation.) Add a short blurb/description about each book that you have personally read/benefited from. Feel free to debate quality, headings, etc. Books that meet the criteria will be added to the list. Books that have reviews by the Association of C and C++ Users (ACCU) have links to the review.



*Note: FAQs and other resources can be found in the C++ tag info and under .

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.

title - Why was this movie called 'The Brothers Bloom'?

This has bugged me since I saw the movie. Why was the movie called 'The Brothers Bloom'?


The brothers are Stephen and Bloom. We are never given their last names and the credits don't show a last name. I would doubt that their last name is Bloom. That would have resulted in 'The Bloom Brothers' though.


Answer


From the IMDb FAQ:



Are the Bloom brothers really brothers?


Yes. At the very beginning of the movie, a caseworker can be seen opening a file cabinet and pulling out the files on young Stephen and Bloom. The file is tagged "Bloom (2)", suggesting that there must be a "Bloom (1)".




Does Bloom have a first name?


The only reference to what Bloom's first name might be comes from a con in which Stephen calls him "Victor." Whether that's his real name or only a contrived name for the con is unknown.



So, it's entirely possible that Bloom wasn't really Brody's first name, but his last name. This would make the title accurate.


I suppose it's not uncommon for people to become known more by their last name than their first. Also, Bloom is certainly not a common first name.


(This question reminds me of the Mario bros., Mario and Luigi.)


sql - How do I split a string so I can access item x?



Using SQL Server, how do I split a string so I can access item x?



Take a string "Hello John Smith". How can I split the string by space and access the item at index 1 which should return "John"?


Answer



You may find the solution in SQL User Defined Function to Parse a Delimited String helpful (from The Code Project).



You can use this simple logic:




Declare @products varchar(200) = '1|20|3|343|44|6|8765'
Declare @individual varchar(20) = null

WHILE LEN(@products) > 0
BEGIN
IF PATINDEX('%|%', @products) > 0
BEGIN
SET @individual = SUBSTRING(@products,
0,
PATINDEX('%|%', @products))

SELECT @individual

SET @products = SUBSTRING(@products,
LEN(@individual + '|') + 1,
LEN(@products))
END
ELSE
BEGIN
SET @individual = @products
SET @products = NULL

SELECT @individual
END
END

How to extend an existing JavaScript array with another array, without creating a new array



There doesn't seem to be a way to extend an existing JavaScript array with another array, i.e. to emulate Python's extend method.



I want to achieve the following:



>>> a = [1, 2]
[1, 2]

>>> b = [3, 4, 5]
[3, 4, 5]
>>> SOMETHING HERE
>>> a
[1, 2, 3, 4, 5]


I know there's a a.concat(b) method, but it creates a new array instead of simply extending the first one. I'd like an algorithm that works efficiently when a is significantly larger than b (i.e. one that does not copy a).



Note: This is not a duplicate of How to append something to an array? -- the goal here is to add the whole contents of one array to the other, and to do it "in place", i.e. without copying all elements of the extended array.



Answer



The .push method can take multiple arguments. You can use the spread operator to pass all the elements of the second array as arguments to .push:



>>> a.push(...b)


If your browser does not support ECMAScript 6, you can use .apply instead:



>>> a.push.apply(a, b)



Or perhaps, if you think it's clearer:



>>> Array.prototype.push.apply(a,b)


Please note that all these solutions will fail with a error if array b is too long (trouble starts at about 100,000 elements, depending on the browser). If you cannot guarantee that b is short enough, you should use a standard loop-based technique described in the other answer.


javascript - document.getElementById vs jQuery $()



Is this:



var contents = document.getElementById('contents');



The same as this:



var contents = $('#contents');


Given that jQuery is loaded?


Answer



Not exactly!!




document.getElementById('contents'); //returns a HTML DOM Object

var contents = $('#contents'); //returns a jQuery Object





In jQuery, to get the same result as document.getElementById, you can access the jQuery Object and get the first element in the object (Remember JavaScript objects act similar to associative arrays).



var contents = $('#contents')[0]; //returns a HTML DOM Object


c# - Why we should use IEnumerable instead of something else?

I have some rows of code:



public IEnumerable GetCardNames()
{
string[]cardname = new string[cards.Count];

for (int i = 0; i < cards.Count; i++)
cardname[i]= cards[i].value + " of " + cards[i].suit + "\n";

return cardname;
}


What I confused about is why it's a better way to use:



public IEnumerable GetCardNames()


than :




public string[] GetCardNames()


or :



public List GetCardNames()


I have read a lot of answers about IEnumerable but I'm still not feel so clear about this one, I mean the benefit of using IEnumerable in this case.

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