Friday, 30 June 2017

How do I declare and initialize an array in Java?



How do I declare and initialize an array in Java?


Answer



You can either use array declaration or array literal (but only when you declare and affect the variable right away, array literals cannot be used for re-assigning an array).



For primitive types:




int[] myIntArray = new int[3];
int[] myIntArray = {1, 2, 3};
int[] myIntArray = new int[]{1, 2, 3};


For classes, for example String, it's the same:



String[] myStringArray = new String[3];
String[] myStringArray = {"a", "b", "c"};

String[] myStringArray = new String[]{"a", "b", "c"};


The third way of initializing is useful when you declare the array first and then initialize it. The cast is necessary here.



String[] myStringArray;
myStringArray = new String[]{"a", "b", "c"};

How to split a multi-line string containing the characters "n" into an array of strings in bash?





I have a string in the following format:




I'm\nNed\nNederlander
I'm\nLucky\nDay
I'm\nDusty\nBottoms


I would like to move this to an array of strings line by line such that:



$ echo "${ARRAY[0]}"
I'm\nNed\nNederlander


$ echo "${ARRAY[1]}"
I'm\nLucky\nDay

$ echo "${ARRAY[2]}"
I'm\nDusty\nBottoms


However, I'm running into problems with the "\n" characters within the string itself. They are represented in the string as two separate characters, the backslash and the 'n', but when I try to do the array split they get interpreted as newlines. Thus typical string splitting with IFS does not work.




For example:



$ read -a ARRAY <<< "$STRING"
$ echo "${#ARRAY[@]}" # print number of elements
2

$ echo "${ARRAY[0]}"
I'mnNednNederla

$ echo "${ARRAY[1]}"

der

Answer



By default, the read builtin allows \ to escape characters. To turn off this behavior, use the -r option. It is not often you will find a case where you do not want to use -r.



string="I'm\nNed\nNederlander
I'm\nLucky\nDay
I'm\nDusty\nBottoms"

arr=()

while read -r line; do
arr+=("$line")
done <<< "$string"


In order to do this in one-line (like you were attempting with read -a), actually requires mapfile in bash v4 or higher:



mapfile -t arr <<< "$string"

matrix - n-dimensional c++ array. How`s that possible?



I became confused when GCC allowed me to do this:



int t[10][10][10][10][10];



I realize int i[N][N] is an NxN matrix where the first N means the row, and the second means the column. Also, the third N in int i[N][N][N] means depth, giving us a 3d dimensional array.



I do not understand what int i[N][N][N][N] and beyond mean.



The fourth dimension is time, but that does not apply here.



So, could this mean that when I get to the third one, I could let the logic go away?


Answer



I find a library analogy very useful to visualizing arrays of multiple dimensions:





  • 8-dimensional array is a library

  • 7-dimensional array is a floor in a library

  • 6-dimensional array is a room on a floor in a library

  • 5-dimensional array is a bookcase in a room on a floor in a library

  • 4-dimensional array is a shelf in a bookcase in a room on a floor in a library

  • 3-dimensional array is a book on a shelf in a bookcase in a room on a floor in a library

  • 2-dimensional array is a page in a book on a shelf in a bookcase in a room on a floor in a library

  • 1-dimensional array is a line on a page in a book on a shelf in a bookcase in a room on a floor in a library

  • 0-dimensional array is a character in a line on a page in a book on a shelf in a bookcase in a room on a floor in a library



How to get size of mysql database?



How to get size of a mysql database?
Suppose the target database is called "v3".


Answer



Run this query and you'll probably get what you're looking for:




SELECT table_schema "DB Name",
ROUND(SUM(data_length + index_length) / 1024 / 1024, 1) "DB Size in MB"
FROM information_schema.tables
GROUP BY table_schema;


This query comes from the mysql forums, where there are more comprehensive instructions available.


javascript - Required Drop Down Box in html5 form

Following is my code from dropdown. I am trying to make sure that person has to select option from dropdown but not "Please select an option...". I can submit form without giving me error. I want to sent error that please select option if person has not selected any option from dropdown.











New in HTML. What should I do ? I don't mind using jquery or javascript for solution.



Thanks

How do you generate random strings in C++?

Answer


Answer




I am looking for methods to generate random strings in C++.Here is my code:



string randomStrGen(int length) {
static string charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
string result;

result.resize(length);

srand(time(NULL));
for (int i = 0; i < length; i++)
result[i] = charset[rand() % charset.length()];

return result;
}



But the seed(time(NULL)) is not random enough.Are there any other better way to generate random strings in C++?


Answer



Don't call srand() on each function call - only call it once at first function call or program startup. You migh want to have a flag indicating whethersrand() has already been called.



The sugested method is good except that you misuse srand() and get predictably bad results.


php - mysqli: can it prepare multiple queries in one statement?

I would like to know if i can prepare one mysqli statement that executes multiple queries:


mysqli->prepare(query1 ...1,2,3 param...; query2...4,5 param...);
or
mysqli->prepare(insert into ...1,2,3 param...; insert into...4,5 param...);
and after all
mysqli->bind_param("sssss", 1, 2, 3, 4, 5);

In that way it make error: Call to a member function bind_param() on a non-object in...


$stmt = $sql->getQueryPrepare("INSERT INTO user (id_user, username, pw, email) VALUES (?,?,?,?); INSERT INTO process (id_user, idp) VALUES (?,?);");
$stmt->bind_param("ssssss",$id, $username, $pw, $email, $id, $idp);
$stmt->execute();
$stmt->close();

cinematography - History and reasoning behind average length of a feature film


I've personally always really enjoyed 'shorts', and always wondered why feature length films are the length they are, especially given my experience that most people's attention spans only last 30-40 minutes at most; meaning I get the feeling most people would not mind shorter films.


What is the history for the feature length film durations, and has there been any research on the fitness/effect of this duration?


Answer


Thats a very interesting question. Though I couldn't find a precise answer, here are some interesting takes on t he subject that I learned while researching.


From this article on wikipedia:



A feature film is a film that runs for 40 minutes or longer, according
to the Academy of Motion Picture Arts and Sciences, American Film
Institute, and British Film Institute, though the Screen Actors Guild
states that it is 80 minutes or longer.


The majority of feature films are between 90 and 210 minutes long. The
Story of the Kelly Gang was the first feature film based on length,
and was released in 1906. The first feature-length adaptation was Les
Misérables which was released in 1909.


Feature films for children are usually between 60 and 120 minutes.



Cinemablend has an interesting article on this very topic:



There's a school of thought that says 90 minutes is the perfect length
for a movie-- the length of 3 TV episodes, just enough time to get in,
tell your story, and get out without wasting any more of the
audience's time. There are countless examples that prove the rule,
economically told stories that feel perfect and tight without a second
wasted.



Finally, there is an answer on wikianswers which has a different take:



Most movie scripts are 120 pages and a page translates to roughly a
minute of film, hence most films being about just under 2 hours. It's
quite genre dependent as comedies and animations are rarely more than
90 minutes, but summer blockbusters and thrillers are usually about 2
hours.



java - Unfortunately my app has stopped in Android Emulator




I've been looking for an answer for hours now, but my calculator wont work at all :(



I appreciate if you could help me. I've posted the manifest code below. Inform me if you need to see the MainActivity.java or anything else :)



    
package="com.example.elof_calc_2000_dragonslayerxx"
android:versionCode="1"
android:versionName="1.0" >

android:minSdkVersion="15"
android:targetSdkVersion="17" />

android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
android:name="com.example.elof_calc_2000_dragonslayerxx.MainActivity"
android:label="@string/app_name" >











The errors shown on Logcat



03-16 18:09:59.890: E/AndroidRuntime(895): FATAL EXCEPTION: main
03-16 18:09:59.890: E/AndroidRuntime(895): Process: com.example.elof_calc_2000_dragonslayerxx, PID: 895
03-16 18:09:59.890: E/AndroidRuntime(895): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.elof_calc_2000_dragonslayerxx/com.example.elof_calc_2000_dragonslayerxx.MainActivity}: java.lang.NullPointerException
03-16 18:09:59.890: E/AndroidRuntime(895): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
03-16 18:09:59.890: E/AndroidRuntime(895): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
03-16 18:09:59.890: E/AndroidRuntime(895): at android.app.ActivityThread.access$800(ActivityThread.java:135)
03-16 18:09:59.890: E/AndroidRuntime(895): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
03-16 18:09:59.890: E/AndroidRuntime(895): at android.os.Handler.dispatchMessage(Handler.java:102)
03-16 18:09:59.890: E/AndroidRuntime(895): at android.os.Looper.loop(Looper.java:136)
03-16 18:09:59.890: E/AndroidRuntime(895): at android.app.ActivityThread.main(ActivityThread.java:5017)
03-16 18:09:59.890: E/AndroidRuntime(895): at java.lang.reflect.Method.invokeNative(Native Method)
03-16 18:09:59.890: E/AndroidRuntime(895): at java.lang.reflect.Method.invoke(Method.java:515)
03-16 18:09:59.890: E/AndroidRuntime(895): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
03-16 18:09:59.890: E/AndroidRuntime(895): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
03-16 18:09:59.890: E/AndroidRuntime(895): at dalvik.system.NativeStart.main(Native Method)
03-16 18:09:59.890: E/AndroidRuntime(895): Caused by: java.lang.NullPointerException
03-16 18:09:59.890: E/AndroidRuntime(895): at com.example.elof_calc_2000_dragonslayerxx.MainActivity.onClickListeners(MainActivity.java:49)
03-16 18:09:59.890: E/AndroidRuntime(895): at com.example.elof_calc_2000_dragonslayerxx.MainActivity.onCreate(MainActivity.java:22)
03-16 18:09:59.890: E/AndroidRuntime(895): at android.app.Activity.performCreate(Activity.java:5231)
03-16 18:09:59.890: E/AndroidRuntime(895): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
03-16 18:09:59.890: E/AndroidRuntime(895): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
03-16 18:09:59.890: E/AndroidRuntime(895): ... 11 more
03-16 18:16:23.316: E/AndroidRuntime(1100): FATAL EXCEPTION: main
03-16 18:16:23.316: E/AndroidRuntime(1100): Process: com.example.elof_calc_2000_dragonslayerxx, PID: 1100
03-16 18:16:23.316: E/AndroidRuntime(1100): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.elof_calc_2000_dragonslayerxx/com.example.elof_calc_2000_dragonslayerxx.MainActivity}: java.lang.NullPointerException
03-16 18:16:23.316: E/AndroidRuntime(1100): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
03-16 18:16:23.316: E/AndroidRuntime(1100): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
03-16 18:16:23.316: E/AndroidRuntime(1100): at android.app.ActivityThread.access$800(ActivityThread.java:135)
03-16 18:16:23.316: E/AndroidRuntime(1100): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
03-16 18:16:23.316: E/AndroidRuntime(1100): at android.os.Handler.dispatchMessage(Handler.java:102)
03-16 18:16:23.316: E/AndroidRuntime(1100): at android.os.Looper.loop(Looper.java:136)
03-16 18:16:23.316: E/AndroidRuntime(1100): at android.app.ActivityThread.main(ActivityThread.java:5017)
03-16 18:16:23.316: E/AndroidRuntime(1100): at java.lang.reflect.Method.invokeNative(Native Method)
03-16 18:16:23.316: E/AndroidRuntime(1100): at java.lang.reflect.Method.invoke(Method.java:515)
03-16 18:16:23.316: E/AndroidRuntime(1100): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
03-16 18:16:23.316: E/AndroidRuntime(1100): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
03-16 18:16:23.316: E/AndroidRuntime(1100): at dalvik.system.NativeStart.main(Native Method)
03-16 18:16:23.316: E/AndroidRuntime(1100): Caused by: java.lang.NullPointerException
03-16 18:16:23.316: E/AndroidRuntime(1100): at com.example.elof_calc_2000_dragonslayerxx.MainActivity.onClickListeners(MainActivity.java:49)
03-16 18:16:23.316: E/AndroidRuntime(1100): at com.example.elof_calc_2000_dragonslayerxx.MainActivity.onCreate(MainActivity.java:22)
03-16 18:16:23.316: E/AndroidRuntime(1100): at android.app.Activity.performCreate(Activity.java:5231)
03-16 18:16:23.316: E/AndroidRuntime(1100): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
03-16 18:16:23.316: E/AndroidRuntime(1100): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
03-16 18:16:23.316: E/AndroidRuntime(1100): ... 11 more

Answer



Here are your key lines



03-16 18:16:23.316: E/AndroidRuntime(1100): Caused by: java.lang.NullPointerException
03-16 18:16:23.316: E/AndroidRuntime(1100): at com.example.elof_calc_2000_dragonslayerxx.MainActivity.onClickListeners(MainActivity.java:49)


You have a NullPointerException on line 49 of your MainActivity. You can post that for further help. Whatever code is there ensure that it is initialized (and thus not null) before you call it.


php -

I have this HTML












This with addition os some css gives this resoult:



button group for input



I use this code to only allow one active:



 $(".btn-group > .btn").click(function(){
$(this).siblings().removeClass("active");
$(this).addClass("active");

});


But it is just visual, and when I try to input vía php POST (within a form) I don't get nothing.



If i change to type=radio, the PHP works fine, but it is uglier.



¿Any magical idea to make it work keeping it fancy?



The php code for testing is:







MegaUltraTest






Thank you.

In Go, if type T2 is based on type T1, is there any sort of "inheritance" from T1 to T2?



If type T2 is based on type T1, other than sharing the same data fields, is there any relationship between T1 and T2?




package main
import "fmt"

type T1 struct { s string }

func (v *T1) F1() string { return v.s }

type T2 T1
func (v *T2) F2() string { return v.s }

func main() {
var t1 = T1{ "xyz" }
var t2 = T2{ "pdq" }
s0 := t2.F1() // error - expected ok
s1 := ((*T1)(&t2)).F1() // ok - expected

s2 := ((*T2)(&t1)).F2() // ok - not expected
fmt.Println( s0, s1, s2 )
}


My understanding here is lacking




  1. was hoping that T2 would inherit T1's methods, but such is not the case.


  2. was expecting T2 could be coerced into T1, since it was derived from T1



  3. was surprised that T1 could be coerced into T2, but so it is.


  4. it seems that the relationship between T1 and T2 is completely symmetrical - I cannot find anything that breaks the symmetry despite the fact one is actually derived from the other - or is this an illusion?




(NOTE: I am not criticizing or judging - I entirely respect decisions made - just verifying I understand what is there that for me is counter-intuitive - I'm sure I'm not the only one!)


Answer



Go does not support object-oriented type inheritance.



Is Go an object-oriented language?




Why is there no type inheritance?



A method is bound to a single specific type.




A method declaration binds an
identifier to a method. The method is
said to be bound to the base type and
is visible only within selectors for
that type.





You can convert between types T1 and T2.




A value x can be converted to type
T [when] x's type and T have
identical underlying types.





For example,



package main

import (
"fmt"
)

type T1 struct{ i int }


func (t T1) String() string { return "T1" }

type T2 T1

func (t T2) String() string { return "T2" }

func main() {
t1 := T1{1}
t2 := T2{2}
fmt.Println(t1, t2)

c1 := T1(t2)
c2 := T2(t1)
fmt.Println(c1, c2)
t1 = T1(c2)
t2 = T2(c1)
fmt.Println(t1, t2)
}

Output:
T1 T2

T1 T2
T1 T2

assembly - How can I store 1byte value in 64bit register only using 64bit registers?



I need to write a pixelization assembly code ONLY using %rax, %rbx, %rcx, %rdx, %rsi, and %rdi (also %rsp and %rbp)




So I've first wrote code in C and changed any other registers into 64 bit registers, but at the point below when I change the register it gives Segmentation default



C code:



*temp = b;
*(temp + 1) = g;
*(temp + 2) = r;


Assembly code By gcc:




movq    -48(%rbp), %rax  
movl %eax, %edx
movq -16(%rbp), %rax
movb %dl, (%rax)
movq -16(%rbp), %rax
addq $1, %rax
movq -56(%rbp), %rdx
movb %dl, (%rax)
movq -16(%rbp), %rax

addq $2, %rax
movq -64(%rbp), %rdx
movb %dl, (%rax)


Changed %dl to %rdx:



movq    -16(%rbp), %rax
movq -48(%rbp), %rdx
movzbq (%rdx), %rbx

movq %rbx, (%rax)
movq -16(%rbp), %rax
addq $1, %rax
movq -56(%rbp), %rdx
movzbq (%rdx), %rbx
movq %rbx, (%rax)
movq -16(%rbp), %rax
addq $2, %rax
movq -64(%rbp), %rdx
movzbq (%rdx), %rbx

movq %rbx, (%rax)

Answer



I think you want to do something like:



 t = r & 0xff;
u = *temp & ~ 0xfful;
*temp = u | t;
t = (g & 0xff) << 8;
u = *temp & ~ 0xff00ul;

*temp = u | t;
t = (b & 0xff) << 16;
u = *temp & ~0xff00000ull;
*temp = u | t;


You should be able to write this with 64bit regs only. You should also be able to find a whole bunch of ways to make this way smaller than this.


unresolved externals Error in C++ Project



I wrote my project using a simple editor and I compile them by using Microsoft vc++ compiler through command line interface, I am getting the following error:




/out:Main.exe Main.obj



Main.obj : error LNK2019: unresolved
external symbol "public: void
__thiscall Ac count::debit(int)" (?debit@Account@@QAEXH@Z) referenced
in function _main



Main.obj : error LNK2019: unresolved

external symbol "public: int
__thiscall Acc ount::getBalance(void)" (?getBalance@Account@@QAEHXZ)
referenced in function _main



Main.obj : error LNK2019: unresolved
external symbol "public: __thiscall
Account ::Account(int)"
(??0Account@@QAE@H@Z) referenced in
function _main Main.exe : fatal error
LNK1120: 3 unresolved externals





Here is the code:



//File : Account.h
class Account{
public:
Account( int );
void credit( int );
void debit( int );

int getBalance();
private:
int balance;
};




//File:Account.cpp


#include
using std::cout;
using std::endl;

#include "Account.h"

Account::Account( int initialbalance ){
balance = 0;

if( initialbalance > 0 )

balance = initialbalance;

if ( initialbalance < 0 )
cout<<"Initial Balance is empty\n"<}

void Account::credit( int amount ){
balance = balance + amount;
}


void Account::debit( int amount ){
if( amount <= balance )
balance = balance - amount;
else
cout<<"Debit amount exceed balance amount\n"<}

int Account::getBalance(){
return balance;
}





//File : Main.cpp
#include
using std::cout;
using std::endl;
using std::cin;


#include "Account.h"

int main(){
Account obj(50);

cout<<"Account balance Rs. "< int withdraw;

cout<<"Withdrawal amount for your account\n"< cin>>withdraw;


cout<<"Withdrawing ....."< obj.debit( withdraw );

cout<<"Final account balance : "<

return 0;
}



I have first compiled Account.cpp by using "cl /LD Account.cpp" , then when i try to compile "Main.cpp" I get these error , to be specific I want to know how to use a compiled .dll or .obj file in my client code that uses these compiled files when their source code is not available .



Thanks in advance.


Answer



Apparently you have forgotten to include the Account.obj in your command line arguments: /out:Main.exe Main.obj Account.obj


c - Is typecast required in malloc?

I assume you mean something like this:


int *iptr = (int*)malloc(/* something */);


And in C, you do not have to (and should not) cast the return pointer from malloc. It's a void * and in C, it is implicitly converted to another pointer type.


int *iptr = malloc(/* something */);


Is the preferred form.


This does not apply to C++, which does not share the same void * implicit cast behavior.

c++ - Generic object with common baseclass to std::function

Im trying to create a signal handling class with a Qt inspired interface like this



class MessageConsumer {};

class MessageHandler {
public:
static int Connect(int, MessageConsumer* obj, std::function handler) {

// Add callback to handler
}
};

class A : public MessageConsumer {
public:
void handleIt(void) {
// Do stuff
}
};


int main(void) {
A a;
MessageHandler::Connect(1, &a, &A::handleIt);
return 0;
}


But keep getting the compiler error




main.cpp: In function ”int main()”:
main.cpp:71:46: error: no matching function ”MessageHandler::Connect(int, A*, void (A::)())”
MessageHandler::Connect(1, &a, &A::handleIt);
^
main.cpp:53:5: anm: candidate: static int MessageHandler::Connect(int, MessageConsumer
, std::function)
int MessageHandler::Connect(int, MessageConsumer* obj, std::function handler) {
^~~~~~~~~~~~~~
main.cpp:53:5: anm: no known conversion for argument 3 from ”void (A::*)()” to ”std::function”



Is there a way to solve this error without defining templates, i do not want use templating in the interface, i.e.




MessageHandler::Connect(1, &a, &A::handleIt)

javascript - setTimeout only sees last value in array?








I have an array of ids which I loop over and want to use in a function called by setTimeout, however when "func" below is executed it only seems to see the last id stored in the array.
I have been trying to uses closures to fix the issue but have had no success.



  // loop over array an call setTimeout for loading an image
for (var i = 0; i < idlist.length; i++) {
// variable i want use in function
var lookup = idlist[i];


var func = function() {
alert(lookup); // this is always the last value in the "idlist" array
};

setTimeout(func, 500);
}

plot explanation - How did Sherlock survive the fall? - Movies & TV

In Sherlock, BBC Series, Season 2 Episode 3 - The Reichenbach Fall, how did Sherlock survive the fall? I've read some theories online regarding this, but in this interview, Steven Moffat says "There is a clue everybody's missed". He also says "Yes. We had to have Holmes dying in Watson's arms – and get away with that, which we have."




So how? Does anybody know yet?

android - Concurrently accessing different members of the same object in Java



I am familiar with many of the mechanisms and idioms surrounding concurrency in Java. Where I am confused is with a simple concept: concurrent access of different members of the same object.




I have a set of variables which can be accessed by two threads, in this case concerning graphical information within a game engine. I need to be able to modify the position of an object in one thread and read it off in another. The standard approach to this problem is to write the following code:



private int xpos;
private object xposAccess;

public int getXpos() {
int result;
synchronized (xposAccess) {
result = xpos;

}
return result;
}

public void setXpos(int xpos) {
synchronized (xposAccess) {
this.xpos = xpos;
}
}



However, I'm writing a real-time game engine, not a 20 questions application. I need things to work fast, especially when I access and modify them as often as I do the position of a graphical asset. I want to remove the synchronized overhead. Even better, I'd like to remove the function call overhead altogether.



private int xpos;
private int bufxpos;
...

public void finalize()
{
bufxpos = xpos;

...
}


Using locks, I can make the threads wait on each other, and then call finalize() while the object is neither being accessed nor modified. After this quick buffering step, both threads are free to act on the object, with one modifying/accessing xpos and one accessing bufxpos.



I have already had success using a similar method where the information was copied in to a second object, and each thread acted on a separate object. However, both members are still part of the same object in the above code, and some funny things begin to happen when both my threads access the object concurrently, even when acting on different members. Unpredictable behaviour, phantom graphical objects, random errors in screen position, etc. To verify that this was indeed a concurrency issue, I ran the code for both threads in a single thread, where it executed flawlessly.



I want performance above all else, and I am considering buffering the critical data in to separate objects. Are my errors caused by concurrent access of the same objects? Is there a better solution for concurrency?




EDIT: If you are doubting my valuation of performance, I should give you more context. My engine is written for Android, and I use it to draw hundreds or thousands of graphic assets. I have a single-threaded solution working, but I have seen a near doubling in performance since implementing the multi-threaded solution, despite the phantom concurrency issues and occasional uncaught exceptions.



EDIT: Thanks for the fantastic discussion about multi-threading performance. In the end, I was able to solve the problem by buffering the data while the worker threads were dormant, and then allowing them each their own set of data within the object to operate on.


Answer



If you are dealing with just individual primitives, such as AtomicInteger, which has operations like compareAndSet, are great. They are non-blocking and you can get a good deal of atomicity, and fall back to blocking locks when needed.



For atomically setting accessing variables or objects, you can leverage non-blocking locks, falling back to traditional locks.



However, the simplest step forward from where you are in your code is to use synchronized but not with the implicit this object, but with several different member objects, one per partition of members that need atomic access: synchronized(partition_2) { /* ... */ }, synchronized(partition_1) { /* ... */ }, etc. where you have members private Object partition1;, private Object partition2; etc.




However, if the members cannot be partitioned, then each operation must acquire more than one lock. If so, use the Lock object linked earlier, but make sure that all operation acquires the locks it needs in some universal order, otherwise your code might deadlock.



Update: Perhaps it is genuinely not possible to increase the performance if even volatile presents an unacceptable hit to performance. The fundamental underlying aspect, which you cannot work around, is that mutual exclusion necessarily implies a tradeoff with the substantial benefits of a memory hierarchy, i. e. caches. The fastest per-processor-core memory cache cannot hold variables that you are synchronizing. Processor registers are arguably the fastest "cache" and even if the processor is sophisticated enough to keep the closest caches consistent, it still precludes keeping values in registers. Hopefully this helps you see that it is a fundamental block to performance and there is no magic wand.



In case of mobile platforms, the platform is deliberately designed against letting arbitrary apps run as fast as possible, because of battery life concerns. It is not a priority to let any one app exhaust battery in a couple of hours.



Given the first factor, the best thing to do would be redesign your app so that it doesn't need as much mutual exclusion -- consider tracking x-pos inconsistently except if two objects come close to each other say within a 10x10 box. So you have locking on a coarse grid of 10x10 boxes and as long an object is within it you track position inconsistently. Not sure if that applies or makes sense for your app, but it is just an example to convey the spirit of an algorithm redesign rather than search for a faster synchronization method.


Why is reading lines from stdin much slower in C++ than Python?




I wanted to compare reading lines of string input from stdin using Python and C++ and was shocked to see my C++ code run an order of magnitude slower than the equivalent Python code. Since my C++ is rusty and I'm not yet an expert Pythonista, please tell me if I'm doing something wrong or if I'm misunderstanding something.






(TLDR answer: include the statement: cin.sync_with_stdio(false) or just use fgets instead.



TLDR results: scroll all the way down to the bottom of my question and look at the table.)







C++ code:



#include 
#include

using namespace std;

int main() {
string input_line;
long line_count = 0;

time_t start = time(NULL);
int sec;
int lps;

while (cin) {
getline(cin, input_line);
if (!cin.eof())
line_count++;
};


sec = (int) time(NULL) - start;
cerr << "Read " << line_count << " lines in " << sec << " seconds.";
if (sec > 0) {
lps = line_count / sec;
cerr << " LPS: " << lps << endl;
} else
cerr << endl;
return 0;
}


// Compiled with:
// g++ -O3 -o readline_test_cpp foo.cpp


Python Equivalent:



#!/usr/bin/env python
import time
import sys


count = 0
start = time.time()

for line in sys.stdin:
count += 1

delta_sec = int(time.time() - start_time)
if delta_sec >= 0:
lines_per_sec = int(round(count/delta_sec))
print("Read {0} lines in {1} seconds. LPS: {2}".format(count, delta_sec,

lines_per_sec))


Here are my results:



$ cat test_lines | ./readline_test_cpp
Read 5570000 lines in 9 seconds. LPS: 618889

$cat test_lines | ./readline_test.py
Read 5570000 lines in 1 seconds. LPS: 5570000



I should note that I tried this both under Mac OS X v10.6.8 (Snow Leopard) and Linux 2.6.32 (Red Hat Linux 6.2). The former is a MacBook Pro, and the latter is a very beefy server, not that this is too pertinent.



$ for i in {1..5}; do echo "Test run $i at `date`"; echo -n "CPP:"; cat test_lines | ./readline_test_cpp ; echo -n "Python:"; cat test_lines | ./readline_test.py ; done
Test run 1 at Mon Feb 20 21:29:28 EST 2012
CPP: Read 5570001 lines in 9 seconds. LPS: 618889
Python:Read 5570000 lines in 1 seconds. LPS: 5570000
Test run 2 at Mon Feb 20 21:29:39 EST 2012
CPP: Read 5570001 lines in 9 seconds. LPS: 618889

Python:Read 5570000 lines in 1 seconds. LPS: 5570000
Test run 3 at Mon Feb 20 21:29:50 EST 2012
CPP: Read 5570001 lines in 9 seconds. LPS: 618889
Python:Read 5570000 lines in 1 seconds. LPS: 5570000
Test run 4 at Mon Feb 20 21:30:01 EST 2012
CPP: Read 5570001 lines in 9 seconds. LPS: 618889
Python:Read 5570000 lines in 1 seconds. LPS: 5570000
Test run 5 at Mon Feb 20 21:30:11 EST 2012
CPP: Read 5570001 lines in 10 seconds. LPS: 557000
Python:Read 5570000 lines in 1 seconds. LPS: 5570000






Tiny benchmark addendum and recap



For completeness, I thought I'd update the read speed for the same file on the same box with the original (synced) C++ code. Again, this is for a 100M line file on a fast disk. Here's the comparison, with several solutions/approaches:



Implementation      Lines per second
python (default) 3,571,428

cin (default/naive) 819,672
cin (no sync) 12,500,000
fgets 14,285,714
wc (not fair comparison) 54,644,808

Answer



By default, cin is synchronized with stdio, which causes it to avoid any input buffering. If you add this to the top of your main, you should see much better performance:



std::ios_base::sync_with_stdio(false);



Normally, when an input stream is buffered, instead of reading one character at a time, the stream will be read in larger chunks. This reduces the number of system calls, which are typically relatively expensive. However, since the FILE* based stdio and iostreams often have separate implementations and therefore separate buffers, this could lead to a problem if both were used together. For example:



int myvalue1;
cin >> myvalue1;
int myvalue2;
scanf("%d",&myvalue2);


If more input was read by cin than it actually needed, then the second integer value wouldn't be available for the scanf function, which has its own independent buffer. This would lead to unexpected results.




To avoid this, by default, streams are synchronized with stdio. One common way to achieve this is to have cin read each character one at a time as needed using stdio functions. Unfortunately, this introduces a lot of overhead. For small amounts of input, this isn't a big problem, but when you are reading millions of lines, the performance penalty is significant.



Fortunately, the library designers decided that you should also be able to disable this feature to get improved performance if you knew what you were doing, so they provided the sync_with_stdio method.


Thursday, 29 June 2017

marvel cinematic universe - Which related films do I need to watch before watching Avengers Assemble?

I am going to watch "The Avengers", and I was wondering do I need to have watched any of the films such as Thor, Iron Man, Captain America etc to understand Avengers?


php - Good cryptographic hash functions











I am making a website, and I need a secure algorithm to store passwords.
I was first thinking of bcrypt, but then I found out my host did not support it and I am not able to change host.



My host allow this encryption:




  • Standard DES




And these hashes:




  • MD5

  • md2, md4 & md5

  • sha1, sha256, sha384 & sha512

  • ripemd128, ripemd160, ripemd256 and ripemd360

  • whirlpool

  • tiger128,3, tiger160,3, tiger192,3, tiger128,4, tiger160,4 & tiger192,4

  • snefru


  • gost

  • adler32

  • crc32 & crc32b

  • haval128,3, haval160,3, haval192,3, haval224,3, haval256,3, haval128,4, haval160,4, haval192,4, haval224,3, haval256,4, haval128,5, haval160,5, haval192,5, haval224,5 & haval256,5



So, can anyone of you fix a good algorithm with that and a salt, please?


Answer



You shouldn't store encrypted (or even unencryped) passwords at all. Instead, use salted hashes (stretched, e.g. with PBKDF2), preferably SHA2-512.




For reference, here is a classification of the listed hashes (See wikipedia for details):



Encryption (not a hash function): DES
Non-cryptographic checksums (laughable): adler32, crc32, crc32b
Broken: MD2, MD4, MD5,SHA1
Probably broken: Tiger, snefru, GOST, HAVAL*
Probably safe: SHA2-256/384/512, RIPEMD-128/256, RIPEMD-160/320, WHIRLPOOL



Note that the strength refers to the attack of finding any password that matches a known hash (preimage attack). Also, the above sorting is paranoid, instantly discarding any hash with any known vulnerabilities.


c++ - errors at building a cpp code using visual studio

i am new to visual studio fro C++, and i followed a visual tutorial to learn how to import opeCV librar into mircrosoft visual studio, after i followed the tutorial i tried to build the code and i received the below posted errors.



build Errors:



1>drawing.obj : error LNK2019: unresolved external symbol "public: __thiscall cv::_InputArray::_InputArray(class cv::Mat const &)" (??0_InputArray@cv@@QAE@ABVMat@1@@Z) referenced in function _main

1>drawing.obj : error LNK2019: unresolved external symbol "public: static class cv::MatExpr __cdecl cv::Mat::zeros(int,int,int)" (?zeros@Mat@cv@@SA?AVMatExpr@2@HHH@Z) referenced in function _main
1>drawing.obj : error LNK2019: unresolved external symbol "public: void __thiscall cv::Mat::deallocate(void)" (?deallocate@Mat@cv@@QAEXXZ) referenced in function "public: void __thiscall cv::Mat::release(void)" (?release@Mat@cv@@QAEXXZ)
1>drawing.obj : error LNK2019: unresolved external symbol "public: void __thiscall cv::Mat::copySize(class cv::Mat const &)" (?copySize@Mat@cv@@QAEXABV12@@Z) referenced in function "public: __thiscall cv::Mat::Mat(class cv::Mat const &)" (??0Mat@cv@@QAE@ABV01@@Z)
1>drawing.obj : error LNK2019: unresolved external symbol "void __cdecl cv::line(class cv::Mat &,class cv::Point_,class cv::Point_,class cv::Scalar_ const &,int,int,int)" (?line@cv@@YAXAAVMat@1@V?$Point_@H@1@1ABV?$Scalar_@N@1@HHH@Z) referenced in function _main
1>drawing.obj : error LNK2019: unresolved external symbol "void __cdecl cv::rectangle(class cv::Mat &,class cv::Point_,class cv::Point_,class cv::Scalar_ const &,int,int,int)" (?rectangle@cv@@YAXAAVMat@1@V?$Point_@H@1@1ABV?$Scalar_@N@1@HHH@Z) referenced in function _main
1>drawing.obj : error LNK2019: unresolved external symbol "void __cdecl cv::circle(class cv::Mat &,class cv::Point_,int,class cv::Scalar_ const &,int,int,int)" (?circle@cv@@YAXAAVMat@1@V?$Point_@H@1@HABV?$Scalar_@N@1@HHH@Z) referenced in function _main
1>drawing.obj : error LNK2019: unresolved external symbol "void __cdecl cv::ellipse(class cv::Mat &,class cv::Point_,class cv::Size_,double,double,double,class cv::Scalar_ const &,int,int,int)" (?ellipse@cv@@YAXAAVMat@1@V?$Point_@H@1@V?$Size_@H@1@NNNABV?$Scalar_@N@1@HHH@Z) referenced in function _main
1>drawing.obj : error LNK2019: unresolved external symbol "void __cdecl cv::fillPoly(class cv::Mat &,class cv::Point_ const * *,int const *,int,class cv::Scalar_ const &,int,int,class cv::Point_)" (?fillPoly@cv@@YAXAAVMat@1@PAPBV?$Point_@H@1@PBHHABV?$Scalar_@N@1@HHV31@@Z) referenced in function _main
1>drawing.obj : error LNK2019: unresolved external symbol "void __cdecl cv::polylines(class cv::Mat &,class cv::Point_ const * *,int const *,int,bool,class cv::Scalar_ const &,int,int,int)" (?polylines@cv@@YAXAAVMat@1@PAPBV?$Point_@H@1@PBHH_NABV?$Scalar_@N@1@HHH@Z) referenced in function _main
1>drawing.obj : error LNK2019: unresolved external symbol "void __cdecl cv::putText(class cv::Mat &,class std::basic_string,class std::allocator > const &,class cv::Point_,int,double,class cv::Scalar_,int,int,bool)" (?putText@cv@@YAXAAVMat@1@ABV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@V?$Point_@H@1@HNV?$Scalar_@N@1@HH_N@Z) referenced in function _main

1>drawing.obj : error LNK2019: unresolved external symbol "class cv::Size_ __cdecl cv::getTextSize(class std::basic_string,class std::allocator > const &,int,double,int,int *)" (?getTextSize@cv@@YA?AV?$Size_@H@1@ABV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@HNHPAH@Z) referenced in function _main
1>drawing.obj : error LNK2019: unresolved external symbol "int __cdecl cv::_interlockedExchangeAdd(int *,int)" (?_interlockedExchangeAdd@cv@@YAHPAHH@Z) referenced in function "public: __thiscall cv::Mat::Mat(class cv::Mat const &)" (??0Mat@cv@@QAE@ABV01@@Z)
1>drawing.obj : error LNK2019: unresolved external symbol "class cv::MatExpr __cdecl cv::operator-(class cv::Mat const &,class cv::Scalar_ const &)" (??Gcv@@YA?AVMatExpr@0@ABVMat@0@ABV?$Scalar_@N@0@@Z) referenced in function _main
1>drawing.obj : error LNK2019: unresolved external symbol "int __cdecl cv::waitKey(int)" (?waitKey@cv@@YAHH@Z) referenced in function _main
1>drawing.obj : error LNK2019: unresolved external symbol "void __cdecl cv::imshow(class std::basic_string,class std::allocator > const &,class cv::_InputArray const &)" (?imshow@cv@@YAXABV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@ABV_InputArray@1@@Z) referenced in function _main
1>c:\users\abakri\documents\visual studio 2013\Projects\OpenCV_App_00\Debug\OpenCV_App_00.exe : fatal error LNK1120: 17 unresolved externals


please let me know how to solve it.

sorting - How to sort a HashMap in Java

How are we able to sort a HashMap?



I want to sort on the basis of a value in the ArrayList.

linux - How to use PREFETCHT0 Instruction in my C code?



I want to prefetch certain addresses (which are address of certain elements of a huge array) in my C program and see the effect of that on time taken.




The instruction about PREFETCH i found here PREFETCH0. But I am not aware of how to use it in C using inline assembly. It would be of great help if some body can give some idea how should I use this instruction with the address as argument, in C program.


Answer



Don't write it using inline assembly which would make the compiler's job harder. GCC has a built-in extension (See gcc builtins docs for more details) for prefetch you should use instead:



__builtin_prefetch(const void*)


This will generate code using the prefetch instructions of your target, but with more scope for the compiler to be smart about it.



As a simple example of the difference between inline ASM and gcc's builtin consider the following two files, test1.c:




void foo(double *d, unsigned len) {
for (unsigned i = 0; i < len; ++i) {
__builtin_prefetch(&d[i]);
d[i] = d[i] * d[i];
}
}


And test2.c:




void foo(double *d, unsigned len) {
for (unsigned i = 0; i < len; ++i) {
asm("prefetcht0 (%0)"
: /**/
: "g"(&d[i])
: /**/
);
d[i] = d[i] * d[i];
}

}


(Note that if you benchmark that I'm 99% sure that a third version with no prefetch would be faster than both of the above, because you've got predictable access patterns and so the only thing that it really achieves is adding more bytes of instructions and a few more cycles)



If we compile both with -O3 on x86_64 and diff the generated output we see:



        .file   "test1.c"                                       |          .file   "test2.c"
.text .text
.p2align 4,,15 .p2align 4,,15

.globl foo .globl foo
.type foo, @function .type foo, @function
foo: foo:
.LFB0: .LFB0:
.cfi_startproc .cfi_startproc
testl %esi, %esi # len testl %esi, %esi # len
je .L1 #, je .L1 #,
leal -1(%rsi), %eax #, D.1749 | leal -1(%rsi), %eax #, D.1745
leaq 8(%rdi,%rax,8), %rax #, D.1749 | leaq 8(%rdi,%rax,8), %rax #, D.1745
.p2align 4,,10 .p2align 4,,10

.p2align 3 .p2align 3
.L4: .L4:
movsd (%rdi), %xmm0 # MEM[base: _8, offset: 0B], D. | #APP
prefetcht0 (%rdi) # ivtmp.6 | # 3 "test2.c" 1
> prefetcht0 (%rdi) # ivtmp.6
> # 0 "" 2
> #NO_APP
> movsd (%rdi), %xmm0 # MEM[base: _8, offset: 0B], D.
addq $8, %rdi #, ivtmp.6 addq $8, %rdi #, ivtmp.6
mulsd %xmm0, %xmm0 # D.1748, D.1748 | mulsd %xmm0, %xmm0 # D.1747, D.1747

movsd %xmm0, -8(%rdi) # D.1748, MEM[base: _8, offset: | movsd %xmm0, -8(%rdi) # D.1747, MEM[base: _8, offset:
cmpq %rax, %rdi # D.1749, ivtmp.6 | cmpq %rax, %rdi # D.1745, ivtmp.6
jne .L4 #, jne .L4 #,
.L1: .L1:
rep ret rep ret
.cfi_endproc .cfi_endproc
.LFE0: .LFE0:
.size foo, .-foo .size foo, .-foo
.ident "GCC: (Ubuntu 4.8.4-2ubuntu1~14.04.3) 4.8.4" .ident "GCC: (Ubuntu 4.8.4-2ubuntu1~14.04.3) 4.8.4"
.section .note.GNU-stack,"",@progbits .section .note.GNU-stack,"",@progbits



Even in this simple case the compiler in question (GCC 4.8.4) has taken advantage of the fact that it's allowed to reorder things and chosen, presumably on the basis of an internal model of the target processors, to move the prefetch after the initial load has happened. If I had to guess it's slightly faster to do the load and prefetch in that order in some scenarios. Presumably the penalty for a miss and a hit is lower with this order. Or the ordering like this works better with branch predictions. It doesn't really matter why the compiler chose to do this though, the point is that it's exceedingly complex to fully understand the impact of even trivial changes to generated code on modern processors in real applications. By using builtin functions instead of inline assembly you benefit from the compiler's knowledge today and any improvements that show up in the future. Even if you spend two weeks studying and benchmarking this simple case the odds are fairly good that you'll not beat future compilers and you may even end up with a code base that can't benefit from future improvements.



Those problems are before we even begin to discuss portability of your code - with builtin functions they fall into one of two categories normally when on an architecture without support either graceful degradation or enabling emulation. Applications with lots of x86 inline assembly were harder to port to x86_64 when that came along.


Get android:versionName manifest element in code



I want to know how to parse the AndroidManifest.xml file in order to get the Application Version Number through code. android:versionName



Answer



No need to parse the AndroidManifest.xml file for this.



You can get this by using:



try
{
String app_ver = this.getPackageManager().getPackageInfo(this.getPackageName(), 0).versionName;
}
catch (NameNotFoundException e)

{
Log.e(tag, e.getMessage());
}


Use this inside your onCreate() method.


Declaring user-defined class types inside a C++ 'for' loop

Here are questions related to declaring built-in type variables inside a for loop:





But I would like to narrow down this subject and ask about declaring user-defined class type variables, which are inherited or made using composition and have non-trivial constructors/destructor with dynamic memory allocation/deallocation (new/delete).



a)  int count = 0;
while(count < 1000000)
{
myClass myObj = some value;
++count;
}

b) int count = 0;
myClass myObj;
while(count < 1000000)
{
myObj = some value;
++count;
}

c) {
int count = 0;
myClass myObj;
while(count < 1000000)
{
myObj = some value;
++count;
}
}



  1. If I have to use a user-defined class variable inside a loop which is best practise for that, declare it inside or outside loop?



If it will be declared inside a loop the chain of constructors and destructors will be called per each iteration, but we will have advantages of restricted scope (a).



If a variable we had declared outside of loop, only the assignment operator will be called per each iteration, but this variable will be accessible out of loop scope (b).




  1. Are compilers smart enough to optimize complex data types declaration as a loop local variable? Does memory allocation happen once and then the same space is reused on each iteration?


  2. If best practices is, to declare variable outside a loop, is it a good idea to put the loop inside scope to restrict the scope (C)?


javascript - how does arrow function with spread operator work

How does this work:


 const invert = fn => (...args) => -fn(...args);

Specifically, what is happening with (...args). It behaves as if it is separating the arguments from the function after the first fat arrow, but I suspect there is a better, more specific, explanation. Thanks.

java - How do servlets work? Instantiation, sessions, shared variables and multithreading



Suppose, I have a webserver which holds numerous servlets. For information passing among those servlets I am setting session and instance variables.




Now, if 2 or more users send request to this server then what happens to the session variables? Will they all be common for all the users or they will be different for each user. If they are different, then how was the server able to differentiate between different users?



One more similar question, if there are n users accessing a particular servlet, then this servlet gets instantiated only the first time the first user accessed it or does it get instantiated for all the users separately? In other words, what happens to the instance variables?


Answer



ServletContext



When the servlet container (like Apache Tomcat) starts up, it will deploy and load all its web applications. When a web application is loaded, the servlet container creates the ServletContext once and keeps it in the server's memory. The web app's web.xml and all of included web-fragment.xml files is parsed, and each , and found (or each class annotated with @WebServlet, @WebFilter and @WebListener respectively) is instantiated once and kept in the server's memory as well. For each instantiated filter, its init() method is invoked with a new FilterConfig.



When a Servlet has a or @WebServlet(loadOnStartup) value greater than 0, then its init() method is also invoked during startup with a new ServletConfig. Those servlets are initialized in the same order specified by that value (1 is 1st, 2 is 2nd, etc). If the same value is specified for more than one servlet, then each of those servlets is loaded in the same order as they appear in the web.xml, web-fragment.xml, or @WebServlet classloading. In the event the "load-on-startup" value is absent, the init() method will be invoked whenever the HTTP request hits that servlet for the very first time.




When the servlet container is finished with all of the above described initialization steps, then the ServletContextListener#contextInitialized() will be invoked.



When the servlet container shuts down, it unloads all web applications, invokes the destroy() method of all its initialized servlets and filters, and all ServletContext, Servlet, Filter and Listener instances are trashed. Finally the ServletContextListener#contextDestroyed() will be invoked.



HttpServletRequest and HttpServletResponse



The servlet container is attached to a web server that listens for HTTP requests on a certain port number (port 8080 is usually used during development and port 80 in production). When a client (e.g. user with a web browser, or programmatically using URLConnection) sends an HTTP request, the servlet container creates new HttpServletRequest and HttpServletResponse objects and passes them through any defined Filter in the chain and, eventually, the Servlet instance.



In the case of filters, the doFilter() method is invoked. When the servlet container's code calls chain.doFilter(request, response), the request and response continue on to the next filter, or hit the servlet if there are no remaining filters.




In the case of servlets, the service() method is invoked. By default, this method determines which one of the doXxx() methods to invoke based off of request.getMethod(). If the determined method is absent from the servlet, then an HTTP 405 error is returned in the response.



The request object provides access to all of the information about the HTTP request, such as its URL, headers, query string and body. The response object provides the ability to control and send the HTTP response the way you want by, for instance, allowing you to set the headers and the body (usually with generated HTML content from a JSP file). When the HTTP response is committed and finished, both the request and response objects are recycled and made available for reuse.



HttpSession



When a client visits the webapp for the first time and/or the HttpSession is obtained for the first time via request.getSession(), the servlet container creates a new HttpSession object, generates a long and unique ID (which you can get by session.getId()), and stores it in the server's memory. The servlet container also sets a Cookie in the Set-Cookie header of the HTTP response with JSESSIONID as its name and the unique session ID as its value.



As per the HTTP cookie specification (a contract any decent web browser and web server must adhere to), the client (the web browser) is required to send this cookie back in subsequent requests in the Cookie header for as long as the cookie is valid (i.e. the unique ID must refer to an unexpired session and the domain and path are correct). Using your browser's built-in HTTP traffic monitor, you can verify that the cookie is valid (press F12 in Chrome / Firefox 23+ / IE9+, and check the Net/Network tab). The servlet container will check the Cookie header of every incoming HTTP request for the presence of the cookie with the name JSESSIONID and use its value (the session ID) to get the associated HttpSession from server's memory.




The HttpSession stays alive until it has been idle (i.e. not used in a request) for more than the timeout value specified in , a setting in web.xml. The timeout value defaults to 30 minutes. So, when the client doesn't visit the web app for longer than the time specified, the servlet container trashes the session. Every subsequent request, even with the cookie specified, will not have access to the same session anymore; the servlet container will create a new session.



On the client side, the session cookie stays alive for as long as the browser instance is running. So, if the client closes the browser instance (all tabs/windows), then the session is trashed on the client's side. In a new browser instance, the cookie associated with the session wouldn't exist, so it would no longer be sent. This causes an entirely new HttpSession to be created, with an entirely new session cookie being used.



In a nutshell




  • The ServletContext lives for as long as the web app lives. It is shared among all requests in all sessions.

  • The HttpSession lives for as long as the client is interacting with the web app with the same browser instance, and the session hasn't timed out at the server side. It is shared among all requests in the same session.


  • The HttpServletRequest and HttpServletResponse live from the time the servlet receives an HTTP request from the client, until the complete response (the web page) has arrived. It is not shared elsewhere.

  • All Servlet, Filter and Listener instances live as long as the web app lives. They are shared among all requests in all sessions.

  • Any attribute that is defined in ServletContext, HttpServletRequest and HttpSession will live as long as the object in question lives. The object itself represents the "scope" in bean management frameworks such as JSF, CDI, Spring, etc. Those frameworks store their scoped beans as an attribute of its closest matching scope.



Thread Safety



That said, your major concern is possibly thread safety. You should now know that servlets and filters are shared among all requests. That's the nice thing about Java, it's multithreaded and different threads (read: HTTP requests) can make use of the same instance. It would otherwise be too expensive to recreate, init() and destroy() them for every single request.



You should also realize that you should never assign any request or session scoped data as an instance variable of a servlet or filter. It will be shared among all other requests in other sessions. That's not thread-safe! The below example illustrates this:




public class ExampleServlet extends HttpServlet {

private Object thisIsNOTThreadSafe;

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Object thisIsThreadSafe;

thisIsNOTThreadSafe = request.getParameter("foo"); // BAD!! Shared among all requests!
thisIsThreadSafe = request.getParameter("foo"); // OK, this is thread safe.

}
}


See also:




Create a 100 number vector with random values in R rounded to 2 decimals

I need to do a pretty simple task,but since im not versed in R I don't know exactly how to. I have to create a vector of 100 numbers with random values from 0 to 1 with 2 DECIMAL numbers. I've tried this:



 x2 <- runif(100, 0.0, 1.0)


and it works great, but the numbers have 8 decimal numbers and I need them with only 2.

go - Creating a Constant Type and Restricting the Type's Values



I have a question about types of constants which are restricted to certain values and how you accomplish that in Go. Say I create a type unary which has two constant values Positive(1) and Negative(-1) and I want to restrict the user of that type (unary) from creating other values of type unary. Do I achieve this by creating a package and making the values Positive and Negative visible and making the type unary restricted to the containing package? See code below for example



package unary


type unary int////not visible outside of the package unary

const (
Positive unary = 1//visible outside of the package unary
Negative unary = -1//visible outside of the package unary
)

func (u unary) String() string {//visible outside of the package unary
if u == Positive {

return "+"
}
return "-"
}

func (u unary) CalExpr() int {//visible outside of the package unary
if u == Positive {
return 1
}
return -1

}


Is this the correct way to restrict a type to certain constant values?


Answer



Flaws



Your proposed solution is not safe in a way you want it to be. One can use untyped integer constants to create new values of unary having a different int value than 1 or -1. See this example:



p := unary.Positive

fmt.Printf("%v %d\n", p, p)

p = 3
fmt.Printf("%v %d\n", p, p)


Output will be:



+ 1
- 3



We could change p's value to store the int value 3 which is obviously not equal to Positive nor to Negative. This is possible because Spec: Assignability:




A value x is assignable to a variable of type T ("x is assignable to T") in any of these cases:




  • ...

  • x is an untyped constant representable by a value of type T.





3 is an untyped constant, and it is representable by a value of type unary which has underlying type int.



In Go you can't have "safe" constants of which "outsider" packages cannot create new values of, for the above mentioned reason. Because if you want to declare constants in your package, you can only use expressions that have "untyped" versions–which may be used by other packages too in assignments (just as in our example).



Unexported struct



If you want to fulfill the "safe" part, you may use unexported structs, but then they cannot be used in constant declarations.




Example:



type unary struct {
val int
}

var (
Positive = unary{1}
Negative = unary{-1}

)

func (u unary) String() string {
if u == Positive {
return "+"
}
return "-"
}

func (u unary) CalExpr() int {

return u.val
}


Attempting to change its value:



p := unary.Positive

p.val = 3 // Error: p.val undefined (cannot refer to unexported field or method val)


p = unary.unary{3} // Error: cannot refer to unexported name unary.unary
// Also error: implicit assignment of unexported field 'val' in unary.unary literal


Note that since we're now using a struct, we can further simplify our code by adding the string representation of our values to the struct:



type unary struct {
val int
str string
}


var (
Positive = unary{1, "+"}
Negative = unary{-1, "-"}
)

func (u unary) String() string { return u.str }

func (u unary) CalExpr() int { return u.val }



Note that this solution still has a "flaw": it uses exported global variables, whose values can be changed by other packages. It's true that other packages cannot create and assign new values, but they can do so with existing values, e.g.:



unary.Positive = unary.Negative


If you want to protect yourself from such misuse, you also have to make such global variables unexported. And then of course you have to create exported functions to expose those values, for example:



var (
positive = unary{1}

negative = unary{-1}
)

func Positive() unary { return positive }

func Negative() unary { return negative }


Then acquiring/using the values:




p := unary.Positive()


Interface



Care must be taken if you plan to use an interface type for your "constants". An example can be seen in Kaveh Shahbazian's answer. An unexported method is used to prevent others from implementing the interface, giving you the illusion that others truly can't implement it:



type Unary interface {
fmt.Stringer
CalExpr() int

disabler() // implementing this interface outside this package is disabled
}

var (
Positive Unary = unary(1) // visible outside of the package unary
Negative Unary = unary(-1) // visible outside of the package unary
)

type unary int // not visible outside of the package unary


func (u unary) disabler() {}

func (u unary) String() string { /* ... */ }

func (u unary) CalExpr() int { /* ... */ }


This is not the case however. With a dirty trick, this can be circumvented. The exported Unary type can be embedded, and an existing value can be used in order to implement the interface (along with the unexported method), and we can add our own implementations of the exported methods, doing / returning whatever we want to.



Here is how it may look like:




type MyUn struct {
unary.Unary
}

func (m MyUn) String() string { return "/" }

func (m MyUn) CalExpr() int { return 3 }



Testing it:



p := unary.Positive
fmt.Printf("%v %d\n", p, p)

p = MyUn{p}
fmt.Printf("%v %d\n", p, p.CalExpr())


Output:




+ 1
/ 3


Special case



As Volker mentioned in his comment, in your special case you could just use



type unary bool


const (
Positive unary = true
Negative unary = false
)


As the type bool has two possible values: true and false, and we've used all. So there are no other values that could be "exploited" to create other values of our constant type.



But know that this can only be used if the number of constants is equal to the number of possible values of the type, so the usability of this technique is very limited.




Also keep in mind that this does not prevent such misuses when a type of unary is expected, and someone accidentally passes an untyped constant like true or false.


java - Android get text from html

I get a special html code:



< ;p > ;This is < ;a href=" ;http://www.test.hu" ;> ;a test link< ;/a> ;  and this is & ;nbsp;a sample text with special char: & ;#233;va < ;/p> ;


(There isn't space before ; char, but if I don't insert space the stackoverflow format it)



It's not a normally html code, but if I paste in a empty html page, the browser show it with normal tags:




<_p_>This is <_a_ href="http://www.test.hu">a test link<_/a_> and this is  a sample text with special char: éva <_/p_>



This code will be shown in a browser:




This is a test link And this is a sample text with special char: éva





So I want to get this text, but I can't use Html.fromHtml, because the component what I use doesn't support Spanned. I wanted to try StringEscapeUtils, but I couldn't import it.



How can I replace special chars and remove tags?

Why does this regular expression kill the Java regex engine?




I have this naive regex "<([\s]|[^<])+?>" (excluding the quotation marks). It seems so
straightforward but it is indeed evil when it works against the below HTML text. It sends the Java regular expression engine to an infinite loop.



I have another regex ("<.+?>"), which does somewhat the same thing, but it doesn't kill anything. Do you know why this happens?






it even keeps looping with an online Java regex tool (such as www.fileformat.info/tool/regex.htm) or a utility like RegexBuddy.


Answer



The reason the Java regex engine crashes is that this part of your regex causes a (indeed!):



[\s]|[^<]



What happens here is that every character matched by \s can also be matched by [^<]. That means there are two ways to match each whitespace character. If we represent the two character classes with A and B:



A|B


Then a string of three spaces could be matched as AAA, AAB, ABA, ABB, BAA, BAB, BBA, or BBB. In other words the complexity of this part of the regex is 2^N. This will kill any regex engine that doesn't have any safeguards against what I call catastrophic backtracking.



When using alternation (vertical bar) in a regex, always make sure the alternatives are mutually exclusive. That is, at most one of the alternatives may be allowed to match any given bit of text.


spotify - Spotipy: How do I search by both artist and song



Given a song title and an artist name, I am trying to find the correct song using Spotipy. However, I do not see a way to search by both song title and artist: it's either one or the other:



   sp.search(q="Money", type="track", limit=10)
sp.search(q="Pink Floyd", type="artist", limit=10)



The problem with this is that I get a bunch of irrelevant results, especially if I search by track(example: top result for money is "Rent Money" by Future not "Money" by Pink Floyd). I could extend the limit and filter out irrelevant results, but considering I'll be doing this on a large scale, I'd rather just query Spotify correctly, take the first result, and move on. Is there any way to query on both track name and artist at the same time using Spotipy?


Answer



Try looking at https://developer.spotify.com/web-api/search-item/



I think that you're misunderstanding type. I always want to return a track list so type is "track". In other words this defines the type of entities to be returned.



The query filter can be completely generic like "Money" or can be focussed to certain parameters like "artist:Floyd track:Money". This can be immensely powerful as you can look at albums, date fields, popularity and all sorts.



I commonly use

let q = String.init(format:"artist:%@ track:%@",artistName,trackName)



Don't forget to %-encode the string!


php - SQL-safe method

Answer


Answer





Context: I'm trying to convince a friend to switch to using parameterized queries to prevent SQL injections and other malicious attempts as that is the standards these days but he has this mentality of "If it's not broken, don't fix it."



Here's the code he currently uses:




function sql_safe($text) {
return str_replace("'", "''", $text);
}


Is there a way for me to break this function to illustrate to him that this approach is not advisable anymore? I've been trying but I can't break it myself so now I'm turning to you guys for help.



Additional Info



It's being used as a general means to protect the system from SQL injections so that user inputs are escaped properly. But I feel like his approach could break at certain scenarios which I haven't figured out yet.



Answer



Here's your code:



function sql_safe($text) {
return str_replace("'", "''", $text);
}
echo "SELECT * FROM db WHERE field = '" . sql_safe($argv[1]) . "';\n";



And here's the most obvious way of breaking it:



$ php ./x.php "\' OR TRUE; -- MySQL"
SELECT * FROM db WHERE field = '\'' OR TRUE; -- MySQL';


has covered the topic of SQL injection extensively over the years. See for example Can I protect against SQL Injection by escaping single-quote and surrounding user input with single-quotes? . There's a neat trick in there that exploits "maximum length of string" to truncate just one of the replacement ''s.


javascript - How do I make a "public static field" in an ES6 class?



I'm making a Javascript class and I'd like to have a public static field like in Java. This is the relevant code:



export default class Agent {
CIRCLE: 1,

SQUARE: 2,
...


This is the error I get:



line 2, col 11, Class properties must be methods. Expected '(' but instead saw ':'.


It looks like ES6 modules don't allow this. Is there a way to get the desired behavior or do I have to write a getter?



Answer



You make "public static field" using accessor and a "static" keyword:



class Agent {
static get CIRCLE() {
return 1;
}
static get SQUARE() {
return 2;
}

}

Agent.CIRCLE; // 1


Looking at a spec, 14.5 — Class Definitions — you'd see something suspiciously relevant :)




ClassElement[Yield] :
  MethodDefinition[?Yield]
  static MethodDefinition[?Yield] ;





So from there you can follow to 14.5.14 — Runtime Semantics: ClassDefinitionEvaluation — to double check if it really does what it looks like it does. Specifically, step 20:





  1. For each ClassElement m in order from methods


    1. If IsStatic of m is false, then



      1. Let status be the result of performing PropertyDefinitionEvaluation for m with arguments proto and false.


    2. Else,


      1. Let status be the result of performing PropertyDefinitionEvaluation for m with arguments F and false.


    3. If status is an abrupt completion, then



      1. Set the running execution context’s LexicalEnvironment to lex.

      2. Return status.






IsStatic is defined earlier in 14.5.9





ClassElement : static MethodDefinition
Return true.




So PropertyMethodDefinition is called with "F" (constructor, function object) as an argument, which in its turn creates an accessor method on that object.



This already works in at least IETP (tech preview), as well as 6to5 and Traceur compilers.


javascript - Getting the ID of the element that fired an event




Is there any way to get the ID of the element that fires an event?



I'm thinking something like:





















Except of course that the var test should contain the id "aaa", if the event is fired from the first form, and "bbb", if the event is fired from the second form.



Answer



In jQuery event.target always refers to the element that triggered the event, where event is the parameter passed to the function. http://api.jquery.com/category/events/event-object/



$(document).ready(function() {
$("a").click(function(event) {
alert(event.target.id);
});
});



Note also that this will also work, but that it is not a jQuery object, so if you wish to use a jQuery function on it then you must refer to it as $(this), e.g.:



$(document).ready(function() {
$("a").click(function(event) {
// this.append wouldn't work
$(this).append(" Clicked");
});
});

Wednesday, 28 June 2017

jquery - javascript formatting opinion: ' vs "

From the point of view of someone who occasionally uses one language to write code in another, using the single quote is preferable. For instance, when I use VB6 to drive Octave or Agena (as I was doing yesterday), I have to use a doubled double-quote to escape a single double-quote. For example,



T "CACos", CACos(CReset(-P_I, 2)), CParse(script("octave", str.Subst("printf(""%s"",num2str(acos(complex([1],[2]))));", -P_I, 2)))


Were I driving Javascript, I'd use the single quote option.

java - Find substring within a string





I wrote a code to find a substring within a string in java but i want to know is there a short way to do this or is there a inbuilt function to do this.



Here's the code :



import java.util.*;

class substr
{
public static void main (String args [])
{
String str1 = new String();
String str2 = new String();
String str3 = new String();
int check=1,k;
Scanner obj= new Scanner (System.in);
System.out.println("Enter a string");

str1=obj.nextLine();
System.out.println("Enter Sub String");
str2=obj.nextLine();
int len=str1.length();
System.out.println(check);
for( int c = 0 ; c < len&&check!=0 ; c++ )
{
for( int i = 1 ; i <= len - c&& check!=0 ; i++ )
{
str3 = str1.substring(c, c+i);

if (str2.equals(str3))
{
check=0;
}
}
}
System.out.println(check);
if (check==0)
{
System.out.println("Sub String");

}
else if ( check==1)
{
System.out.println("No");
}
}
}

Answer



If you are asking for a way to do what your code does (check if a string is substring of another string), you can use String#contains:




if(str1.contains(str2)) {
System.out.println("Sub String");
} else {
System.out.println("No");
}




You can also use String#indexOf:


if(str1.indexOf(str2)>=0) {
System.out.println("Sub String");
} else {
System.out.println("No");
}

android - How do I center text horizontally and vertically in a TextView?




How do I center the text horizontally and vertically in a TextView, so that it appears exactly in the middle of the TextView in Android?


Answer



I'm assuming you're using XML layout.



    android:layout_width="match_parent" 
android:layout_height="match_parent"
android:gravity="center"
android:text="@string/**yourtextstring**"
/>



You can also use gravity center_vertical or center_horizontal according to your need.



and as @stealthcopter commented
in java: .setGravity(Gravity.CENTER);


casting - Why wasn&#39;t Tobey Maguire in The Amazing Spider-Man? - Movies &amp; TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...