问:
Can't figure out how to make a python coin toss program loop back to a certain point once the whole process of the toss has been completed
I have been banging my head against the wall for a few hours now trying to figure this out so any help is greatly appreciated. What I'm trying to do is loop the program upon a Y input for a Y/N question, specifically when Y is inputed I want it to react the way it does as shown in the sample output.

Here is my code:

```<code>import random
def main():
    name = eval(input("Hello user, please enter your name: "))
    print("Hello", name ,"This program runs a coin toss simulation")
    yn = input("Would you like to run the coin toss simulation?(Y/N):")
    if yn == Y:

    elif yn == N:
        print("Ok have a nice day!")

    heads = 0
    tails = 0
    count = tails + heads
    count = int(input("Enter the amount of times you would like the coin to     flip: "))
    if count <= 0:
        print("Silly rabbit, that won't work")
    while tails + heads < count:
        coin = random.randint(1, 2)
        if coin ==1:

            heads = heads + 1
        elif coin == 2:

            tails = tails + 1
    print("you flipped", count , "time(s)")
    print("you flipped heads", heads , "time(s)")
    print("you flipped tails", tails , "time(s)")
main()
</code>```

Here is the sample output that I'm looking for:

Hello user, please enter your name: Joe
Hello Joe this program runs a coin toss simulation
Would you like to run the coin toss simulation?(Y/N):Y
Enter the amount of times you would like the coin to flip:50
you flipped 50 times
you flipped heads 26 times
you flipped tails 24 times
Would you like to run another coin toss simulation?(Y/N):Y
Enter the amount of times you would like the coin to flip:100
you flipped 100 times
you flipped heads 55 times
you flipped tails 45 times
Would you like to run another coin toss simulation?(Y/N):N
Ok have a nice day!
```

答:
To run your coin toss simulation multiple times you can put it inside a while loop.

Your if yn == Y: test won't work because you haven't defined the variable Y, so when Python tries to execute that line you get a NameError. What you actually should be doing there is to test the value of yn against the string 'Y'.

I've made a couple of other minor adjustments to your code. I got rid of that potentially dangerous eval function call, you don't need it. I've also made a loop that asks for the desired flip count; we break out ofthe loop when count is a positive number.

```<code>import random

def main():
    name = input("Hello user, please enter your name: ")
    print("Hello", name , "This program runs a coin toss simulation")
    yn = input("Would you like to run the coin toss simulation?(Y/N): ")
    if yn != 'Y':
        print("Ok have a nice day!")
        return

    while True:
        heads = tails = 0
        while True:
            count = int(input("Enter the amount of times you would like the coin to flip: "))
            if count <= 0:
                print("Silly rabbit, that won't work")
            else:
                break

        while tails + heads < count:
            coin = random.randint(1, 2)
            if coin ==1:
                heads = heads + 1
            else:
                tails = tails + 1

        print("you flipped", count , "time(s)")
        print("you flipped heads", heads , "time(s)")
        print("you flipped tails", tails , "time(s)")

        yn = input("Would you like to run another coin toss simulation?(Y/N): ")
        if yn != 'Y':
            print("Ok have a nice day!")
            return

main()
</code>```

This code is for Python 3. On Python 2 you should use raw_input in place of input, and you should also put

from future import print_function

at the top of the script so you get the Python 3 print function instead of the old Python 2 print _statement.

There are several improvements that can be made to this code. In particular, it should handle a non-integer being supplied for the count. This version will just crash if it gets bad input. To learn how to fix that, please see Asking the user for input until they give a valid response.

Body:
I have been banging my head against the wall for a few hours now trying to figure this out so any help is greatly appreciated. What I'm trying to do is loop the program upon a Y input for a Y/N question, specifically when Y is inputed I want it to react the way it does as shown in the sample output.

Here is my code:

import random
def main():
    name = eval(input("Hello user, please enter your name: "))
    print("Hello", name ,"This program runs a coin toss simulation")
    yn = input("Would you like to run the coin toss simulation?(Y/N):")
    if yn == Y:

    elif yn == N:
        print("Ok have a nice day!")

    heads = 0
    tails = 0
    count = tails + heads
    count = int(input("Enter the amount of times you would like the coin to     flip: "))
    if count <= 0:
        print("Silly rabbit, that won't work")
    while tails + heads < count:
        coin = random.randint(1, 2)
        if coin ==1:

            heads = heads + 1
        elif coin == 2:

            tails = tails + 1
    print("you flipped", count , "time(s)")
    print("you flipped heads", heads , "time(s)")
    print("you flipped tails", tails , "time(s)")
main()

Here is the sample output that I'm looking for:

Hello user, please enter your name: Joe
Hello Joe this program runs a coin toss simulation
Would you like to run the coin toss simulation?(Y/N):Y
Enter the amount of times you would like the coin to flip:50
you flipped 50 times
you flipped heads 26 times
you flipped tails 24 times
Would you like to run another coin toss simulation?(Y/N):Y
Enter the amount of times you would like the coin to flip:100
you flipped 100 times
you flipped heads 55 times
you flipped tails 45 times
Would you like to run another coin toss simulation?(Y/N):N
Ok have a nice day!

Body:
To run your coin toss simulation multiple times you can put it inside a while loop.

Your if yn == Y: test won't work because you haven't defined the variable Y, so when Python tries to execute that line you get a NameError. What you actually should be doing there is to test the value of yn against the string 'Y'.

I've made a couple of other minor adjustments to your code. I got rid of that potentially dangerous eval function call, you don't need it. I've also made a loop that asks for the desired flip count; we break out ofthe loop when count is a positive number.

import random

def main():
    name = input("Hello user, please enter your name: ")
    print("Hello", name , "This program runs a coin toss simulation")
    yn = input("Would you like to run the coin toss simulation?(Y/N): ")
    if yn != 'Y':
        print("Ok have a nice day!")
        return

    while True:
        heads = tails = 0
        while True:
            count = int(input("Enter the amount of times you would like the coin to flip: "))
            if count <= 0:
                print("Silly rabbit, that won't work")
            else:
                break

        while tails + heads < count:
            coin = random.randint(1, 2)
            if coin ==1:
                heads = heads + 1
            else:
                tails = tails + 1

        print("you flipped", count , "time(s)")
        print("you flipped heads", heads , "time(s)")
        print("you flipped tails", tails , "time(s)")

        yn = input("Would you like to run another coin toss simulation?(Y/N): ")
        if yn != 'Y':
            print("Ok have a nice day!")
            return

main()

This code is for Python 3. On Python 2 you should use raw_input in place of input, and you should also put

from future import print_function

at the top of the script so you get the Python 3 print function instead of the old Python 2 print _statement.

There are several improvements that can be made to this code. In particular, it should handle a non-integer being supplied for the count. This version will just crash if it gets bad input. To learn how to fix that, please see Asking the user for input until they give a valid response.


来源: stackexchange

问:
Convert DateOffset to local datetime
I need to display the Datetimeoffset field as date time in my view. Currently when i apply displayformat it doesnt do anything. I am looking for DD/MM/yyyy and seconds format

```<code> [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
        public DateTimeOffset CreatedDate { get; set; }
</code>```

My view currently shows     /Date(1490029476910)/

How do I handle the formatting and display the local time using the viewmodel

答:
You can use data annotation called [DataType(DataType.Date)] and ApplyFormatInEditMode = true, DataFormatString ="{0:d}"

Eg :

```<code>[DataType(DataType.Date)]
        [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString ="{0:d}")]
        [Required(AllowEmptyStrings = false, ErrorMessage = "DataDate cannot be empty")]
        public DateTime? DataDate { get; set; }
</code>```

ContentLicense: CC BY-SA 3.0

Title: Convert DateOffset to local datetime

Body:
I need to display the Datetimeoffset field as date time in my view. Currently when i apply displayformat it doesnt do anything. I am looking for DD/MM/yyyy and seconds format

 [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
        public DateTimeOffset CreatedDate { get; set; }

My view currently shows     /Date(1490029476910)/

How do I handle the formatting and display the local time using the viewmodel

Body:
You can use data annotation called [DataType(DataType.Date)] and ApplyFormatInEditMode = true, DataFormatString ="{0:d}"

Eg :

[DataType(DataType.Date)]
        [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString ="{0:d}")]
        [Required(AllowEmptyStrings = false, ErrorMessage = "DataDate cannot be empty")]
        public DateTime? DataDate { get; set; }


问:
Python custom modules management
I have a script (dump_ora_shelve.py) which retrieves the data from shelve-storage by specifying the key, e.g.:

```<code>def get_shelve_users(field):
    import shelve
    db = shelve.open('oracle-shelve')
    for key in db:
        if key == field:
             return db[key]
    db.close()
</code>```

The data is retrieved just fine:

```<code>print(get_shelve_users('db_users'))
> {'SYS': 'sysdba'}
print(get_shelve_users('oratab'))
> ['orcl:/u01/app']
</code>```

There is another script which should do the same thing (retrieve the data with key specified) that has dump_ora_shelve imported, but the value returns is Null:

```<code>from before_OOP.dump_ora_shelve import get_shelve_users
print(get_shelve_users('db_users'))
> Null
print(get_shelve_users('oratab'))
> Null
</code>```

The file being imported is located one level above from the file it is importing to.

Please note if I copy both files to the same location import and then function works just fine.

答:
When running the second script your working directory will be the directory where that script is located. That working directory is kept even when you import and use a file from a different package/directory.

So if your dump_ora_shelve.py script and shelve is located in a different  directory/package it will not open the correct file.

If you provide the full path to 'oracle-shelve' in dump_ora_shelve.py it should work.

Update:

In your 'dump_ora_shelve.py' file:

```<code>ABS_DIR = os.path.dirname(os.path.abspath(__file__))
</code>```

This gives you the absoulte path of the directory of ''dump_ora_shelve.py'.  Join with name of your DB:

```<code>shelve_db = os.path.join(ABS_DIR, 'oracle-shelve')
</code>```

And finally:

```<code>db = shelve.open(shelve_db)
</code>```

This assumes that your 'oracle-shelve' is in the same directory as 'dump_ora_shelve.py'

Title: Python custom modules management

Body:
I have a script (dump_ora_shelve.py) which retrieves the data from shelve-storage by specifying the key, e.g.:

def get_shelve_users(field):
    import shelve
    db = shelve.open('oracle-shelve')
    for key in db:
        if key == field:
             return db[key]
    db.close()

The data is retrieved just fine:

print(get_shelve_users('db_users'))
> {'SYS': 'sysdba'}
print(get_shelve_users('oratab'))
> ['orcl:/u01/app']

There is another script which should do the same thing (retrieve the data with key specified) that has dump_ora_shelve imported, but the value returns is Null:

from before_OOP.dump_ora_shelve import get_shelve_users
print(get_shelve_users('db_users'))
> Null
print(get_shelve_users('oratab'))
> Null

The file being imported is located one level above from the file it is importing to.

Please note if I copy both files to the same location import and then function works just fine.

Body:
When running the second script your working directory will be the directory where that script is located. That working directory is kept even when you import and use a file from a different package/directory.

So if your dump_ora_shelve.py script and shelve is located in a different  directory/package it will not open the correct file.

If you provide the full path to 'oracle-shelve' in dump_ora_shelve.py it should work.

Update:

In your 'dump_ora_shelve.py' file:

ABS_DIR = os.path.dirname(os.path.abspath(__file__))

This gives you the absoulte path of the directory of ''dump_ora_shelve.py'.  Join with name of your DB:

shelve_db = os.path.join(ABS_DIR, 'oracle-shelve')

And finally:

db = shelve.open(shelve_db)

This assumes that your 'oracle-shelve' is in the same directory as 'dump_ora_shelve.py'


问:
how to plot rgb color histogram of image with objective c
i want to show image RGB colour histogram in cocoa application. Please suggest possible way to do it with objective c or any third party library available to achieve this.</p>

答:
well this is a problem as RGB colors are 3D space so their histogram would lead to 4D plot which is something we do not really comprehend.

So the solution to this is to convert the 4D plot to 3D plot somehow. This can be done by sorting the colors by something that has some meaning. I will not speculate and describe what I am using. I use HSV color space and ignore the V value. This way I lose a lot of color shade info but it is still enough to describe colors for my purposes. This is how it looks like:

You can also use more plots with different V to cover more colors. For more info see:

HSV histogram

Anyway you can use any gradient sorting or any shape of your plot that is completely on you.

If you want pure RGB then you could adapt this and use RGB cube surface or map it on sphere and ignore the length from (0,0,0) (use unit vectors) something like this:

So if you R,G,B are in <0,1> you convert that to <-1,+1> then compute the spherical coordinates (ignoring radius) and you got your 2 variables instead of 3 which you can use as a plot (either as 2D globe base or 3D sphere ...).

Here C++ code how to do this (made from the HSV histogram):

picture pic0,pic1,pic2,zed;

const int na=360,nb=180,nb2=nb>>1; // size of histogram table
int his[na][nb];
DWORD w;

int a,b,r,g,x,y,z,l,i,n;
double aa,bb,da,db,dx,dy,dz,rr;
color c;

pic2=pic0;                      // copy input image pic0 to pic2
for (a=0;a<na;a++)              // clear histogram
 for (b=0;b<nb;b++)
  his[a][b]=0;
for (y=0;y<pic2.ys;y++)         // compute it
 for (x=0;x<pic2.xs;x++)
    {
    c=pic2.p[y][x];
    r=c.db[picture::_r]-128;
    g=c.db[picture::_g]-128;
    b=c.db[picture::_b]-128;
    l=sqrt(r*r+g*g+b*b);        // convert RGB -> spherical a,b angles
    if (!l) { a=0; b=0; }
    else{
        a=double(double(na)*acos(double(b)/double(l))/(2.0*M_PI));
        if (!r) b=0; else b=double(double(nb)*atan(double(g)/double(r))/(M_PI)); b+=nb2;
        while (a<0) a+=na; while (a>=na) a-=na;
        if (b<0) b=0; if (b>=nb) b=nb-1;
        }
    his[a][b]++;            // update color usage count ...
    }
for (n=0,a=0;a<na;a++)      // max probability
 for (b=0;b<nb;b++)
  if (n<his[a][b]) n=his[a][b];

// draw the colored RGB sphere and histogram
zed =pic1; zed .clear(9999);    // zed buffer for 3D
           pic1.clear(0);       // image of histogram
da=2.0*M_PI/double(na);
db=M_PI/double(nb);
for (aa=0.0,a=0;a<na;a++,aa+=da)
 for (bb=-M_PI,b=0;b<nb;b++,bb+=db)
    {
    // normal
    dx=cos(bb)*cos(aa);
    dy=cos(bb)*sin(aa);
    dz=sin(bb);
    // color of surface (darker)
    rr=75.0;
    c.db[picture::_r]=double(rr*dx)+128;
    c.db[picture::_g]=double(rr*dy)+128;
    c.db[picture::_b]=double(rr*dz)+128;
    c.db[picture::_a]=0;
    // histogram center
    x=pic1.xs>>1;
    y=pic1.ys>>1;
    // surface position
    rr=64.0;
    z=rr;
    x+=double(rr*dx);
    y+=double(rr*dy);
    z+=double(rr*dz);
    if (zed.p[y][x].dd>=z){ pic1.p[y][x]=c; zed.p[y][x].dd=z; }
    // ignore lines if zero color count
    if (!his[a][b]) continue;
    // color of lines (bright)
    rr=125.0;
    c.db[picture::_r]=double(rr*dx)+128;
    c.db[picture::_g]=double(rr*dy)+128;
    c.db[picture::_b]=double(rr*dz)+128;
    c.db[picture::_a]=0;
    // line length
    l=(xs*his[a][b])/(n*3);
    for (double xx=x,yy=y,zz=z;l>=0;l--)
        {
        if (zed.p[y][x].dd>=z){ pic1.p[y][x]=c; zed.p[y][x].dd=z; }
        xx+=dx; yy+=dy; zz+=dz; x=xx; y=yy; z=zz;
        if (x<0) break; if (x>=xs) break;
        if (y<0) break; if (y>=ys) break;
        }
    }
```

input image is pic0, output image is pic1 (histogram graph)

pic2 is copy of pic0 (remnant of old code)

zed is the Zed buffer for 3D display avoiding Z sorting ...

I use my own picture class for images so some members are:

 xs,ys size of image in pixels

 p[y][x].dd is pixel at (x,y) position as 32 bit integer type

 clear(color) - clears entire image

 resize(xs,ys) - resizes image to new resolution

As the sphere is a 3D object you should add rotation to it so all the surface is visible in time (or rotate with mouse or whatever) ...

Body:
well this is a problem as RGB colors are 3D space so their histogram would lead to 4D plot which is something we do not really comprehend.

So the solution to this is to convert the 4D plot to 3D plot somehow. This can be done by sorting the colors by something that has some meaning. I will not speculate and describe what I am using. I use HSV color space and ignore the V value. This way I lose a lot of color shade info but it is still enough to describe colors for my purposes. This is how it looks like:

You can also use more plots with different V to cover more colors. For more info see:

HSV histogram

Anyway you can use any gradient sorting or any shape of your plot that is completely on you.

If you want pure RGB then you could adapt this and use RGB cube surface or map it on sphere and ignore the length from (0,0,0) (use unit vectors) something like this:

So if you R,G,B are in <0,1> you convert that to <-1,+1> then compute the spherical coordinates (ignoring radius) and you got your 2 variables instead of 3 which you can use as a plot (either as 2D globe base or 3D sphere ...).

Here C++ code how to do this (made from the HSV histogram):

picture pic0,pic1,pic2,zed;

const int na=360,nb=180,nb2=nb>>1; // size of histogram table
int his[na][nb];
DWORD w;

int a,b,r,g,x,y,z,l,i,n;
double aa,bb,da,db,dx,dy,dz,rr;
color c;

pic2=pic0;                      // copy input image pic0 to pic2
for (a=0;a<na;a++)              // clear histogram
 for (b=0;b<nb;b++)
  his[a][b]=0;
for (y=0;y<pic2.ys;y++)         // compute it
 for (x=0;x<pic2.xs;x++)
    {
    c=pic2.p[y][x];
    r=c.db[picture::_r]-128;
    g=c.db[picture::_g]-128;
    b=c.db[picture::_b]-128;
    l=sqrt(r*r+g*g+b*b);        // convert RGB -> spherical a,b angles
    if (!l) { a=0; b=0; }
    else{
        a=double(double(na)*acos(double(b)/double(l))/(2.0*M_PI));
        if (!r) b=0; else b=double(double(nb)*atan(double(g)/double(r))/(M_PI)); b+=nb2;
        while (a<0) a+=na; while (a>=na) a-=na;
        if (b<0) b=0; if (b>=nb) b=nb-1;
        }
    his[a][b]++;            // update color usage count ...
    }
for (n=0,a=0;a<na;a++)      // max probability
 for (b=0;b<nb;b++)
  if (n<his[a][b]) n=his[a][b];

// draw the colored RGB sphere and histogram
zed =pic1; zed .clear(9999);    // zed buffer for 3D
           pic1.clear(0);       // image of histogram
da=2.0*M_PI/double(na);
db=M_PI/double(nb);
for (aa=0.0,a=0;a<na;a++,aa+=da)
 for (bb=-M_PI,b=0;b<nb;b++,bb+=db)
    {
    // normal
    dx=cos(bb)*cos(aa);
    dy=cos(bb)*sin(aa);
    dz=sin(bb);
    // color of surface (darker)
    rr=75.0;
    c.db[picture::_r]=double(rr*dx)+128;
    c.db[picture::_g]=double(rr*dy)+128;
    c.db[picture::_b]=double(rr*dz)+128;
    c.db[picture::_a]=0;
    // histogram center
    x=pic1.xs>>1;
    y=pic1.ys>>1;
    // surface position
    rr=64.0;
    z=rr;
    x+=double(rr*dx);
    y+=double(rr*dy);
    z+=double(rr*dz);
    if (zed.p[y][x].dd>=z){ pic1.p[y][x]=c; zed.p[y][x].dd=z; }
    // ignore lines if zero color count
    if (!his[a][b]) continue;
    // color of lines (bright)
    rr=125.0;
    c.db[picture::_r]=double(rr*dx)+128;
    c.db[picture::_g]=double(rr*dy)+128;
    c.db[picture::_b]=double(rr*dz)+128;
    c.db[picture::_a]=0;
    // line length
    l=(xs*his[a][b])/(n*3);
    for (double xx=x,yy=y,zz=z;l>=0;l--)
        {
        if (zed.p[y][x].dd>=z){ pic1.p[y][x]=c; zed.p[y][x].dd=z; }
        xx+=dx; yy+=dy; zz+=dz; x=xx; y=yy; z=zz;
        if (x<0) break; if (x>=xs) break;
        if (y<0) break; if (y>=ys) break;
        }
    }

input image is pic0, output image is pic1 (histogram graph)

pic2 is copy of pic0 (remnant of old code)

zed is the Zed buffer for 3D display avoiding Z sorting ...

I use my own picture class for images so some members are:

 xs,ys size of image in pixels

 p[y][x].dd is pixel at (x,y) position as 32 bit integer type

 clear(color) - clears entire image

 resize(xs,ys) - resizes image to new resolution

As the sphere is a 3D object you should add rotation to it so all the surface is visible in time (or rotate with mouse or whatever) ...


问:
How to extract values enclosed inside curly braces in PHP?
I have the following values inside curly braces.

{ "address": "test@test.com", "did_you_mean": null, "is_valid": true, "parts": { "display_name": null, "domain": "test.com", "local_part": "test" }}

I need to get the value of "is_valid". I tried json_decode to get the value. But it didn't help me to find the result. Anyone please help me to find a solution.

答:
Why json_decode didn't work ?
I tested it with that code and works perfectly:</p>

```<code>$str= '{ "address": "test@test.com", "did_you_mean": null, "is_valid": true, "parts": { "display_name": null, "domain": "test.com", "local_part": "test" }}';
$obj = json_decode($str);

echo $obj->is_valid;
</code>```

Body:
Why json_decode didn't work ?
I tested it with that code and works perfectly:

$str= '{ "address": "test@test.com", "did_you_mean": null, "is_valid": true, "parts": { "display_name": null, "domain": "test.com", "local_part": "test" }}';
$obj = json_decode($str);

echo $obj->is_valid;


问:
Searching Up the Scope vs Accessing the DOM - Speed Performance
I am learning javaScript and there are still many doubts. I've already tried to search this one but maybe I am using the wrong words. I am always delaying this but since the size of the project I am working on is becoming larger than I expected I need to be clarified.

I am aware that are costs in terms of speed in both searching up the scope and accessing the Dom. But I don't know which one is slower than the other.

Is it faster...

a) to go up the scope chain to grab the variable with the jQuery object, but go to the Dom just once

or

b) Not go up the scope chain, but go to the Dom again

```<code>var $el = $("#el");

//$el is used on this scope (and so, the question makes some sense:))

$el (...)

// some or lot's of code

function a() {

   // some or lot's of code

   function b(){

      // some or lot's of code

      function c() {

         a) $el (...)
         b) var $el = $("#el");
            $el (...)

      }

  }

}
</code>```

答:
If I understanded your question, you are asking about performance accessing elements in jQuery. Here you have some tips:

Every time you have to get the reference to a jQuery object ($("#el") in your example) has a operational cost. In terms of performance, you should always try to declare the minimun necessary elements to your needs.

Accessing siblings (siblings()), parents (closest(), parent()) or children (children(), find()) is a good option if is just for a few operations, but if you are going to use that elements many times, its better reference them with a direct selector like $("#el-child") or ("#el .child").

If you declare a var like $el = $("#el") you get a reference of the node in its current state. Sometimes this node has being updated, removed, re-created, or something else, and this reference wont keep trak of them, so you have to call this $el = $("#el") again so, as I said before, it depends how your website logic works.

Note: sorry about my english, I know it's not good at all hehe

Body:
I am learning javaScript and there are still many doubts. I've already tried to search this one but maybe I am using the wrong words. I am always delaying this but since the size of the project I am working on is becoming larger than I expected I need to be clarified.

I am aware that are costs in terms of speed in both searching up the scope and accessing the Dom. But I don't know which one is slower than the other.

Is it faster...

a) to go up the scope chain to grab the variable with the jQuery object, but go to the Dom just once

or

b) Not go up the scope chain, but go to the Dom again

var $el = $("#el");

//$el is used on this scope (and so, the question makes some sense:))

$el (...)

// some or lot's of code

function a() {

   // some or lot's of code

   function b(){

      // some or lot's of code

      function c() {

         a) $el (...)
         b) var $el = $("#el");
            $el (...)

      }

  }

}


问:
Highcharts series update with animation
I can update the data value of a spider chart and see it animated using this method:

```<code>chart.series[i].setData(newSeries[i].data);
</code>```

But, as the series in a spider chart consists not only of data but also other fields, as in

```<code>series: [{
            name: 'Allocated Budget',
            data: [43000, 19000, 60000, 35000, 17000, 10000],
            pointPlacement: 'on'
        }, {
            name: 'Actual Spending',
            data: [50000, 39000, 42000, 31000, 26000, 14000],
            pointPlacement: 'on'
        }]
</code>```

Along with the data, when I need to change the value name: 'Actual Spending' , how can I update the series with animation?

Because, for example if I call:

```<code>chart.series[i].update({series: newSeries[i] , name : newName});
</code>```

There won't be any animation.

If it is still unclear... Well, sometimes a jsfiddle is worth a 100 words.

答:
Since the correct answer did not work for me with multiple series, I had to do it more similar to this:

First update the names since it's a quicker operation without animation.

```<code>// Pass false to skip redraw (since there are multiple operations, for better performance)
chart.series[0].update({name:'new title 0'}, false);
chart.series[1].update({name:'new title 1'}, false);
chart.series[2].update({name:'new title 2'}, false);
chart.series[3].update({name:'new title 3'}, false);

// Redraw the name changes before updating the data.
chart.redraw();

// Update the series data with animation, passing false to redraw here as well.
chart.series[0].setData(newData, false);
chart.series[1].setData(newData1, false);
chart.series[2].setData(newData2, false);
chart.series[3].setData(newData3, false);

// Now we redraw the series data
chart.redraw();
</code>```

Title: Highcharts series update with animation

Body:
I can update the data value of a spider chart and see it animated using this method:

chart.series[i].setData(newSeries[i].data);

But, as the series in a spider chart consists not only of data but also other fields, as in

series: [{
            name: 'Allocated Budget',
            data: [43000, 19000, 60000, 35000, 17000, 10000],
            pointPlacement: 'on'
        }, {
            name: 'Actual Spending',
            data: [50000, 39000, 42000, 31000, 26000, 14000],
            pointPlacement: 'on'
        }]

Along with the data, when I need to change the value name: 'Actual Spending' , how can I update the series with animation?

Because, for example if I call:

chart.series[i].update({series: newSeries[i] , name : newName});

There won't be any animation.

If it is still unclear... Well, sometimes a jsfiddle is worth a 100 words.

Body:
Since the correct answer did not work for me with multiple series, I had to do it more similar to this:

First update the names since it's a quicker operation without animation.

// Pass false to skip redraw (since there are multiple operations, for better performance)
chart.series[0].update({name:'new title 0'}, false);
chart.series[1].update({name:'new title 1'}, false);
chart.series[2].update({name:'new title 2'}, false);
chart.series[3].update({name:'new title 3'}, false);

// Redraw the name changes before updating the data.
chart.redraw();

// Update the series data with animation, passing false to redraw here as well.
chart.series[0].setData(newData, false);
chart.series[1].setData(newData1, false);
chart.series[2].setData(newData2, false);
chart.series[3].setData(newData3, false);

// Now we redraw the series data
chart.redraw();


问:
Better SQL Replace
I wanted to know if there is a better way of writing this Update.

```<code>update Alumni_Export_New
set phone = replace(replace(replace(replace(phone,'-',''),' ',''),')',''),'(','')
from tbl
</code>```

I have a stored procedure in MSSQL 2005 to clean the phone field in a table and thought there should be a better way of doing this then what I have.

答: Use CLR integration and Regular Expressions.</p>

ContentLicense: CC BY-SA 2.5

Title: Better SQL Replace

Body:
I wanted to know if there is a better way of writing this Update.

update Alumni_Export_New
set phone = replace(replace(replace(replace(phone,'-',''),' ',''),')',''),'(','')
from tbl

I have a stored procedure in MSSQL 2005 to clean the phone field in a table and thought there should be a better way of doing this then what I have.


问:
Apache Flink - implementing a stream processor with potentially very large state
I wish to project a potentially very large state from a stream of events. This is how I might implement this in an imperative fashion:

```<code>class ImperativeFooProcessor {

  val state: mutable.Map[UUID, BarState] = mutable.HashMap.empty[UUID, BarState]

  def handle(event: InputEvent) = {
    event match {
      case FooAdded(fooId, barId) => {
        // retrieve relevant state and do some work on it
        val barState = state(barId)

        // let the world know about what may have happened
        publish(BarOccured(fooId, barId))
        // or maybe rather
        publish(BazOccured(fooId, barId))
      }
      case FooRemoved(fooId, barId) => {
        // retrieve relevant state and do some work on it
        val barState = state(barId)

        // let the world know about what may have happened
        publish(BarOccured(fooId, barId))
        // or maybe rather
        publish(BazOccured(fooId, barId))
      }
    }
  }

  private def publish(event: OutputEvent): Unit = {
    // push event to downstream sink
  }
}
</code>```

In the worst case the size of BarState will grow with the number of times its been mentioned by FooAdded

The number of unique barId's is very small relative to the total number of events for each barId.

How would I begin to represent this processing structure in Flink?

How do I work with the fact that each BarState can potentially get very large?

答:
Flink maintains state in so-called state backends. There are state backends (MemoryStateBackend and FsStateBackend) that operated on the JVM heap of the worker processes. These backends are not suited to handle large state.

Flink also features a RocksDBStateBackend, which is based on RocksDB. RocksDB is used as a local database (no need to set it up as an external service) on each worker node and writes state data to disk. Hence, it can handle very large state exceeding the memory.

Flink offers a KeyedStream which is a stream which is partitioned on a certain attribute. In your case, you probably want that all access to the same id go to the same state instance, so you would use barId as a key. Then, the state is partitioned across all parallel worker threads based on the barId. This is basically a distributed key-value store or map. So you would not need to represent the state as a map, because it is automatically distributed by Flink.

Body:
I wish to project a potentially very large state from a stream of events. This is how I might implement this in an imperative fashion:

class ImperativeFooProcessor {

  val state: mutable.Map[UUID, BarState] = mutable.HashMap.empty[UUID, BarState]

  def handle(event: InputEvent) = {
    event match {
      case FooAdded(fooId, barId) => {
        // retrieve relevant state and do some work on it
        val barState = state(barId)

        // let the world know about what may have happened
        publish(BarOccured(fooId, barId))
        // or maybe rather
        publish(BazOccured(fooId, barId))
      }
      case FooRemoved(fooId, barId) => {
        // retrieve relevant state and do some work on it
        val barState = state(barId)

        // let the world know about what may have happened
        publish(BarOccured(fooId, barId))
        // or maybe rather
        publish(BazOccured(fooId, barId))
      }
    }
  }

  private def publish(event: OutputEvent): Unit = {
    // push event to downstream sink
  }
}

In the worst case the size of BarState will grow with the number of times its been mentioned by FooAdded

The number of unique barId's is very small relative to the total number of events for each barId.

How would I begin to represent this processing structure in Flink?

How do I work with the fact that each BarState can potentially get very large?


问:
datastax driver connection = apache ignite and cassandra(you may want to increase the driver number of per-host connections)
Components: apache ignite + apache cassandra. Use defaut datastax driver.
After doing several operation(about 3-5 billions entities put to cache) we get a situation when datastax driver always reconnects to cassandra from ignite.

```<code>2017-02-16 13:29:21.287  INFO 160487 --- [ sys-#441%null%] m.r.t.d.c.m.p.c.c.p.RetryPolicyImpl      :  init cluster
2017-02-16 13:29:21.288  INFO 160487 --- [ sys-#441%null%] com.datastax.driver.core.Cluster         : New Cassandra host <our host> added
2017-02-16 13:29:21.307  INFO 160487 --- [ sys-#441%null%] m.r.t.d.c.m.p.c.c.p.RetryPolicyImpl      :  close cluster
2017-02-16 13:29:23.516  INFO 160487 --- [ sys-#441%null%] com.datastax.driver.core.ClockFactory    : Using native clock to generate timestamps.
2017-02-16 13:29:23.537  INFO 160487 --- [ sys-#441%null%] c.d.d.c.p.DCAwareRoundRobinPolicy        : Using data-center name 'datacenter1' for DCAw
</code>```

And this process is endless and it can be interrupted by server restarted.

Infrastructure :
1 server ignite - ~Xmx30g and 8 cores.
25 clients ignites ~Xmx1g and 8 cores.
1 node cassandra.
Batch size(entities which will be put to cache and then cassandra) is about 1-2M.

Config datasource =>

```<code> public DataSource dataSource() {
        DataSource dataSource = new DataSource();
        dataSource.setUser(login);
        dataSource.setPassword(pass);
        dataSource.setPort(port);
        dataSource.setContactPoints(host);
        dataSource.setRetryPolicy(retryPolicy);
        dataSource.setFetchSize(10_000);
        dataSource.setReconnectionPolicy(new ConstantReconnectionPolicy(1000));
        dataSource.setLoadBalancingPolicy(DCAwareRoundRobinPolicy.builder().withUsedHostsPerRemoteDc(0).build());
        dataSource.setSocketOptions(new SocketOptions().setReadTimeoutMillis(100_000).setConnectTimeoutMillis(100_00));
        return dataSource;
    }
</code>```

config cache =>

```<code> CacheConfiguration<KeyIgnite, Long> cfg = new CacheConfiguration<>();
        cfg
                .setName(area)
                .setRebalanceMode(CacheRebalanceMode.SYNC)
                .setStartSize(1_000_000)
                .setAtomicityMode(CacheAtomicityMode.ATOMIC)
                .setIndexedTypes(KeyIgnite.class, Long.class)
                .setCacheMode(CacheMode.PARTITIONED)
                .setBackups(0);

        if (!clientMode) {

            CassandraCacheStoreFactory<KeyIgnite, Long> csFactory = new CassandraCacheStoreFactory<>();
            csFactory.setDataSource(ds);
            csFactory.setPersistenceSettings(kv);

//            CassandraCacheStoreFactoryDwh<KeyIgnite, Long> csFactory = new CassandraCacheStoreFactoryDwh<>(ds, kv,params);

            cfg
                    .setCacheStoreFactory(csFactory)
                    .setReadThrough(true)
                    .setWriteThrough(true);
        }

        cfg.setExpiryPolicyFactory(TouchedExpiryPolicy.factoryOf(new Duration(TimeUnit.DAYS, 5)));
        return cfg;
</code>```

ignite config =>:

```<code>   TcpDiscoveryMulticastIpFinder finder = new TcpDiscoveryMulticastIpFinder();
        finder.setAddresses(adresses);

        return Ignition.start(
                new IgniteConfiguration()
                        .setClientMode(clientMode)
                        .setDiscoverySpi(new TcpDiscoverySpi().setIpFinder(finder).setNetworkTimeout(10000))
                        .setFailureDetectionTimeout(50000)
                        .setPeerClassLoadingEnabled(false)
                        .setLoadBalancingSpi(new RoundRobinLoadBalancingSpi())

        );
</code>```

When we have done several iteration of putting items to cache we have gotten this case.

after including debug level i have gotten this record:

```<code>2017-02-17 17:48:41.570 DEBUG 24816 --- [ sys-#184%null%] com.datastax.driver.core.RequestHandler  : [1071994376-1] Error querying ds-inmemorydb-02t/10.216.28.34:9042 : com.datastax.driver.core.exceptions.DriverException: Timeout while trying to acquire available connection (you may want to increase the driver number of per-host connections)
</code>```

答: The timeout increase on the driver helped</p>

Body:
Components: apache ignite + apache cassandra. Use defaut datastax driver.
After doing several operation(about 3-5 billions entities put to cache) we get a situation when datastax driver always reconnects to cassandra from ignite.

2017-02-16 13:29:21.287  INFO 160487 --- [ sys-#441%null%] m.r.t.d.c.m.p.c.c.p.RetryPolicyImpl      :  init cluster
2017-02-16 13:29:21.288  INFO 160487 --- [ sys-#441%null%] com.datastax.driver.core.Cluster         : New Cassandra host <our host> added
2017-02-16 13:29:21.307  INFO 160487 --- [ sys-#441%null%] m.r.t.d.c.m.p.c.c.p.RetryPolicyImpl      :  close cluster
2017-02-16 13:29:23.516  INFO 160487 --- [ sys-#441%null%] com.datastax.driver.core.ClockFactory    : Using native clock to generate timestamps.
2017-02-16 13:29:23.537  INFO 160487 --- [ sys-#441%null%] c.d.d.c.p.DCAwareRoundRobinPolicy        : Using data-center name 'datacenter1' for DCAw

And this process is endless and it can be interrupted by server restarted.

Infrastructure :
1 server ignite - ~Xmx30g and 8 cores.
25 clients ignites ~Xmx1g and 8 cores.
1 node cassandra.
Batch size(entities which will be put to cache and then cassandra) is about 1-2M.

Config datasource =>

 public DataSource dataSource() {
        DataSource dataSource = new DataSource();
        dataSource.setUser(login);
        dataSource.setPassword(pass);
        dataSource.setPort(port);
        dataSource.setContactPoints(host);
        dataSource.setRetryPolicy(retryPolicy);
        dataSource.setFetchSize(10_000);
        dataSource.setReconnectionPolicy(new ConstantReconnectionPolicy(1000));
        dataSource.setLoadBalancingPolicy(DCAwareRoundRobinPolicy.builder().withUsedHostsPerRemoteDc(0).build());
        dataSource.setSocketOptions(new SocketOptions().setReadTimeoutMillis(100_000).setConnectTimeoutMillis(100_00));
        return dataSource;
    }

config cache =>

 CacheConfiguration<KeyIgnite, Long> cfg = new CacheConfiguration<>();
        cfg
                .setName(area)
                .setRebalanceMode(CacheRebalanceMode.SYNC)
                .setStartSize(1_000_000)
                .setAtomicityMode(CacheAtomicityMode.ATOMIC)
                .setIndexedTypes(KeyIgnite.class, Long.class)
                .setCacheMode(CacheMode.PARTITIONED)
                .setBackups(0);

        if (!clientMode) {

            CassandraCacheStoreFactory<KeyIgnite, Long> csFactory = new CassandraCacheStoreFactory<>();
            csFactory.setDataSource(ds);
            csFactory.setPersistenceSettings(kv);

//            CassandraCacheStoreFactoryDwh<KeyIgnite, Long> csFactory = new CassandraCacheStoreFactoryDwh<>(ds, kv,params);

            cfg
                    .setCacheStoreFactory(csFactory)
                    .setReadThrough(true)
                    .setWriteThrough(true);
        }

        cfg.setExpiryPolicyFactory(TouchedExpiryPolicy.factoryOf(new Duration(TimeUnit.DAYS, 5)));
        return cfg;

ignite config =>:

   TcpDiscoveryMulticastIpFinder finder = new TcpDiscoveryMulticastIpFinder();
        finder.setAddresses(adresses);

        return Ignition.start(
                new IgniteConfiguration()
                        .setClientMode(clientMode)
                        .setDiscoverySpi(new TcpDiscoverySpi().setIpFinder(finder).setNetworkTimeout(10000))
                        .setFailureDetectionTimeout(50000)
                        .setPeerClassLoadingEnabled(false)
                        .setLoadBalancingSpi(new RoundRobinLoadBalancingSpi())

        );

When we have done several iteration of putting items to cache we have gotten this case.

after including debug level i have gotten this record:

2017-02-17 17:48:41.570 DEBUG 24816 --- [ sys-#184%null%] com.datastax.driver.core.RequestHandler  : [1071994376-1] Error querying ds-inmemorydb-02t/10.216.28.34:9042 : com.datastax.driver.core.exceptions.DriverException: Timeout while trying to acquire available connection (you may want to increase the driver number of per-host connections)


问:
Conflicted transactions
I have this error when my some transactions conflicted. How can i find what is the thansaction in conflict? (Without sql server profiler).

I am using snapshot isolation level

System.Data.SqlClient.SqlException: Snapshot isolation transaction
aborted due to update conflict. You cannot use snapshot isolation to
access table 'dbo.Users' directly or indirectly in database
'IUMobileDbRelease' to update, delete, or insert the row that has been
modified or deleted by another transaction. Retry the transaction or
change the isolation level for the update/delete statement.

```<code>    System.Data.Entity.Internal.InternalContext.SaveChanges()
</code>```

答:
In EF6, you can enable query logging:

https://msdn.microsoft.com/en-us/library/dn469464(v=vs.113).aspx

For example:

```<code>context.Database.Log = Console.Write;
</code>```

Correlate its output with the exception you get, to narrow it down to a statement.

Title: Conflicted transactions

Body:
I have this error when my some transactions conflicted. How can i find what is the thansaction in conflict? (Without sql server profiler).

I am using snapshot isolation level

System.Data.SqlClient.SqlException: Snapshot isolation transaction
aborted due to update conflict. You cannot use snapshot isolation to
access table 'dbo.Users' directly or indirectly in database
'IUMobileDbRelease' to update, delete, or insert the row that has been
modified or deleted by another transaction. Retry the transaction or
change the isolation level for the update/delete statement.

    System.Data.Entity.Internal.InternalContext.SaveChanges()

Body:
In EF6, you can enable query logging:

https://msdn.microsoft.com/en-us/library/dn469464(v=vs.113).aspx

For example:

context.Database.Log = Console.Write;

Correlate its output with the exception you get, to narrow it down to a statement.


问:
SpringBoot Multiple Data Source JPA
I have following code

Entity

```<code> @Entity
    public class Employee {

        @Id
        @GeneratedValue
        long id;

        @Column(name="first_name")
        String firstName;

        @Column(name="last_name")
        String lastName;

        @Column(name="salary")
        int salary;

        @ManyToOne
        @JoinColumn(name="address")
        Address address;

    ..... setter & getter

    }
</code>```

Repo

```<code>public interface EmpRepository extends JpaRepository<Employee, Long>{}
</code>```

Service

```<code>@Service
public class EmpService {

    @Autowired
    private EmpRepository empRepo;

    @Autowired @Qualifier("primaryEntityManagerFactory") EntityManager em;

    public List<Employee> findAll(){
        return empRepo.findAll();
    }

}
</code>```

Controller

```<code>@RestController
@RequestMapping(value = "/demo")
public class DemoController {

    @Autowired
    private EmpService empService;

    @RequestMapping("/abcd")
    public List<Employee> findAll(){
        return empService.findAll();
    }

}
</code>```

Data Source Configuraion (Primary)

```<code>@Configuration
@EnableJpaRepositories(basePackages="com.example",
entityManagerFactoryRef = "primaryEntityManagerFactory")
public class DataSourceConfiguration {

    @Bean(name="primaryDataSource")
    @Primary
    @ConfigurationProperties(prefix = "datasource.primary")
    public DataSource primaryDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    @Primary
    public JpaTransactionManager transactionManager() {
        JpaTransactionManager tm = new JpaTransactionManager();
        tm.setEntityManagerFactory(primaryEntityManagerFactory().getObject());
        return tm;
    }

    @Bean(name="primaryEntityManagerFactory")
    @Primary
    LocalContainerEntityManagerFactoryBean primaryEntityManagerFactory() {

        HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();
        jpaVendorAdapter.setGenerateDdl(true);

        LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();

        factoryBean.setDataSource(primaryDataSource());
        factoryBean.setJpaVendorAdapter(jpaVendorAdapter);
        factoryBean.setPackagesToScan(DataSourceConfiguration.class.getPackage().getName());

        return factoryBean;
    }

}
</code>```

Secondary Data Source Config

```<code> @Configuration
@EnableJpaRepositories(basePackages="com.example",
entityManagerFactoryRef = "secondaryEntityManagerFactory")
public class DS2Configuration {

    @Bean(name="secondaryDataSource")
    @ConfigurationProperties(prefix = "datasource.secondary")

    public DataSource secondaryDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    public JpaTransactionManager transactionManager() {
        JpaTransactionManager tm = new JpaTransactionManager();
        tm.setEntityManagerFactory(secondaryEntityManagerFactory().getObject());
        return tm;
    }

    @Bean(name="secondaryEntityManagerFactory")
    LocalContainerEntityManagerFactoryBean secondaryEntityManagerFactory() {

        HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();
        jpaVendorAdapter.setGenerateDdl(true);

        LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();

        factoryBean.setDataSource(secondaryDataSource());
        factoryBean.setJpaVendorAdapter(jpaVendorAdapter);
        factoryBean.setPackagesToScan(DataSourceConfiguration.class.getPackage().getName());

        return factoryBean;
    }

}
</code>```

application.properties

```<code>spring.jpa.show-sql = true
spring.jpa.properties.hibernate.show_sql=true
spring.jooq.sql-dialect=MYSQL
logging.level.org.springframework.data=DEBUG

# Primary DataSource configuration
datasource.primary.url=jdbc:mysql://127.0.0.1:3306/jpa
datasource.primary.username=root
datasource.primary.password=root

# Secondary DataSource configuration
datasource.secondary.url=jdbc:mysql://127.0.0.1:3306/jpa2
datasource.secondary.username=root
datasource.secondary.password=root

# Disable Spring DataSource auto-initialization
spring.datasource.initialize=false

server.port=8081
</code>```

When I am actually running function findAll() from EmpService, it is always using primary datasource even when i am specifying  secondary entitymanagefactory as

```<code>@Autowired
    @Qualifier("secondaryEntityManagerFactory")
    EntityManager em;
</code>```

How to resolve this?
P.S. - Please do not share blog links for this.

答:
You need to add @Primary on this method :  primaryEntityManagerFactory()

By the way, I think primaryTransactionManager() and equivalent secondary methods are superfluous, the factory bean methods return the same thing.

You also need to define a transactionManager per entityManager e.g.

```<code>@Bean
@Primary
public JpaTransactionManager transactionManager() {
    JpaTransactionManager tm = new JpaTransactionManager();
    tm.setEntityManagerFactory(yourPrimaryEntityManagerInjected);
    return tm;
}
</code>```

Title: SpringBoot Multiple Data Source JPA

Body:
I have following code

Entity

 @Entity
    public class Employee {

        @Id
        @GeneratedValue
        long id;

        @Column(name="first_name")
        String firstName;

        @Column(name="last_name")
        String lastName;

        @Column(name="salary")
        int salary;

        @ManyToOne
        @JoinColumn(name="address")
        Address address;

    ..... setter & getter

    }

Repo

public interface EmpRepository extends JpaRepository<Employee, Long>{}

Service

@Service
public class EmpService {

    @Autowired
    private EmpRepository empRepo;

    @Autowired @Qualifier("primaryEntityManagerFactory") EntityManager em;

    public List<Employee> findAll(){
        return empRepo.findAll();
    }

}

Controller

@RestController
@RequestMapping(value = "/demo")
public class DemoController {

    @Autowired
    private EmpService empService;

    @RequestMapping("/abcd")
    public List<Employee> findAll(){
        return empService.findAll();
    }

}

Data Source Configuraion (Primary)

@Configuration
@EnableJpaRepositories(basePackages="com.example",
entityManagerFactoryRef = "primaryEntityManagerFactory")
public class DataSourceConfiguration {

    @Bean(name="primaryDataSource")
    @Primary
    @ConfigurationProperties(prefix = "datasource.primary")
    public DataSource primaryDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    @Primary
    public JpaTransactionManager transactionManager() {
        JpaTransactionManager tm = new JpaTransactionManager();
        tm.setEntityManagerFactory(primaryEntityManagerFactory().getObject());
        return tm;
    }

    @Bean(name="primaryEntityManagerFactory")
    @Primary
    LocalContainerEntityManagerFactoryBean primaryEntityManagerFactory() {

        HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();
        jpaVendorAdapter.setGenerateDdl(true);

        LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();

        factoryBean.setDataSource(primaryDataSource());
        factoryBean.setJpaVendorAdapter(jpaVendorAdapter);
        factoryBean.setPackagesToScan(DataSourceConfiguration.class.getPackage().getName());

        return factoryBean;
    }

}

Secondary Data Source Config

 @Configuration
@EnableJpaRepositories(basePackages="com.example",
entityManagerFactoryRef = "secondaryEntityManagerFactory")
public class DS2Configuration {

    @Bean(name="secondaryDataSource")
    @ConfigurationProperties(prefix = "datasource.secondary")

    public DataSource secondaryDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    public JpaTransactionManager transactionManager() {
        JpaTransactionManager tm = new JpaTransactionManager();
        tm.setEntityManagerFactory(secondaryEntityManagerFactory().getObject());
        return tm;
    }

    @Bean(name="secondaryEntityManagerFactory")
    LocalContainerEntityManagerFactoryBean secondaryEntityManagerFactory() {

        HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();
        jpaVendorAdapter.setGenerateDdl(true);

        LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();

        factoryBean.setDataSource(secondaryDataSource());
        factoryBean.setJpaVendorAdapter(jpaVendorAdapter);
        factoryBean.setPackagesToScan(DataSourceConfiguration.class.getPackage().getName());

        return factoryBean;
    }

}

application.properties

spring.jpa.show-sql = true
spring.jpa.properties.hibernate.show_sql=true
spring.jooq.sql-dialect=MYSQL
logging.level.org.springframework.data=DEBUG

# Primary DataSource configuration
datasource.primary.url=jdbc:mysql://127.0.0.1:3306/jpa
datasource.primary.username=root
datasource.primary.password=root

# Secondary DataSource configuration
datasource.secondary.url=jdbc:mysql://127.0.0.1:3306/jpa2
datasource.secondary.username=root
datasource.secondary.password=root

# Disable Spring DataSource auto-initialization
spring.datasource.initialize=false

server.port=8081

When I am actually running function findAll() from EmpService, it is always using primary datasource even when i am specifying  secondary entitymanagefactory as

@Autowired
    @Qualifier("secondaryEntityManagerFactory")
    EntityManager em;

How to resolve this?
P.S. - Please do not share blog links for this.

Body:
You need to add @Primary on this method :  primaryEntityManagerFactory()

By the way, I think primaryTransactionManager() and equivalent secondary methods are superfluous, the factory bean methods return the same thing.

You also need to define a transactionManager per entityManager e.g.

@Bean
@Primary
public JpaTransactionManager transactionManager() {
    JpaTransactionManager tm = new JpaTransactionManager();
    tm.setEntityManagerFactory(yourPrimaryEntityManagerInjected);
    return tm;
}


问:
Jenkins: manually adjust job execution order in queue
Is there any Jenkins plugin providing possibility to adjust job execution sequence in queue?

Thanks.

答:
Even if it's late but if somebody else came across:

See this plugin:

https://wiki.jenkins-ci.org/display/JENKINS/Accelerated+Build+Now+Plugin

You can not tell an order but bring your manually started job to the top of the queue.

Not meeting your question 100% but there is also an issue filed to bring your job to the top of the queue:

See also: https://issues.jenkins-ci.org/browse/JENKINS-1878


问:
Safely Wrapping a Connection Pool
I am trying to implement row level security so our application can enforce more stringent access control.

One of the technologies we are looking into is Oracle's Virtual Private Database, which allows row level security by basically augmenting all queries against specific tables with a where clause predicate. Since we are in a web environment, we need to set up a special context within Oracle, inside a single request's thread. We use connection pooling with a service account.

I started to look into Eclipse Link and Hibernate. Eclipse Link seems to have events that fit perfectly into this model.

This would involve us migrating from hibernate, which is not a problem, but  we would then be bound to EL for these events.

Oracle seems to imply that they implement at the data source level in Web Logic product.

The context is set and cleared by the WebLogic data source code.

Question: Is it more appropriate to do this at the DataSource level with some series of events. What are the events or methods that I should pay the most attention too?

Added Question: How would I extend a connection pool to safely initialize an oracle context with some custom data? I am digging around in Apache, and it seems like extending BasicDataSource doesn't give me access to anything that would allow me to clean up the connection when Spring is done with it.

I need to set up a connection, and clean up a connection as the exit / enter the connection pool. I am hoping for an implementation that is so simple, no one can mess it up by breaking some delicate balance of products.

```<code>- Specifically we are currently using Apache Commons DBCP Basic Data Source
</code>```

This would allow us to use various ways to connect to the database and still have our security enforced. But I don't see a great example or set of events to work with, and rolling my own security life cycle is never a good idea.

答: You can try any object level security mechanism for simplicity, like Spring Security ACL.</p>

Title: Safely Wrapping a Connection Pool

Body:
I am trying to implement row level security so our application can enforce more stringent access control.

One of the technologies we are looking into is Oracle's Virtual Private Database, which allows row level security by basically augmenting all queries against specific tables with a where clause predicate. Since we are in a web environment, we need to set up a special context within Oracle, inside a single request's thread. We use connection pooling with a service account.

I started to look into Eclipse Link and Hibernate. Eclipse Link seems to have events that fit perfectly into this model.

This would involve us migrating from hibernate, which is not a problem, but  we would then be bound to EL for these events.

Oracle seems to imply that they implement at the data source level in Web Logic product.

The context is set and cleared by the WebLogic data source code.

Question: Is it more appropriate to do this at the DataSource level with some series of events. What are the events or methods that I should pay the most attention too?

Added Question: How would I extend a connection pool to safely initialize an oracle context with some custom data? I am digging around in Apache, and it seems like extending BasicDataSource doesn't give me access to anything that would allow me to clean up the connection when Spring is done with it.

I need to set up a connection, and clean up a connection as the exit / enter the connection pool. I am hoping for an implementation that is so simple, no one can mess it up by breaking some delicate balance of products.

- Specifically we are currently using Apache Commons DBCP Basic Data Source

This would allow us to use various ways to connect to the database and still have our security enforced. But I don't see a great example or set of events to work with, and rolling my own security life cycle is never a good idea.


问:
Complete list of JVM options
Besides official documentation I have found only this post. But it is quite old and incomplete (only -XX options available).
For example, I couldn't find -XX:AutoBoxCacheMax option in none of them.

Where the complete list can be found if it exists?

答:
You can use

```<code>java -XX:+UnlockDiagnosticVMOptions -XX:+PrintFlagsFinal -version
</code>```

to print all options and their defaults. If you have a debug build you can use this command to print comments for the various options as well:

```<code>java -XX:+UnlockDiagnosticVMOptions -XX:+UnlockExperimentalVMOptions -XX:+PrintFlagsFinal -XX:+PrintFlagsWithComments -version
</code>```

PS: There are descriptions for most of them in this blog post: http://stas-blogspot.blogspot.bg/2011/07/most-complete-list-of-xx-options-for.html

Title: Complete list of JVM options

Body:
You can use

java -XX:+UnlockDiagnosticVMOptions -XX:+PrintFlagsFinal -version

to print all options and their defaults. If you have a debug build you can use this command to print comments for the various options as well:

java -XX:+UnlockDiagnosticVMOptions -XX:+UnlockExperimentalVMOptions -XX:+PrintFlagsFinal -XX:+PrintFlagsWithComments -version

PS: There are descriptions for most of them in this blog post: http://stas-blogspot.blogspot.bg/2011/07/most-complete-list-of-xx-options-for.html


问:
Finding the right argument for addActionListener
I'm trying to make a button that toggles the state of the button (changes color and text) when pressed. But I can't get the addActionListener to work and I can't find the ToggleState method from my main class. I am new to java and would appreciate your help.

I get the errors
 - “The method addActionListener(ActionListener) in the type AbstractButton is not applicable for the arguments”
- "ActionListener cannot be resolved to a type"

```<code>package Grafiktest;

import javax.swing.*;
import java.awt.*;

public class coolgrafik extends JFrame implements ActionListener {

private static final long serialVersionUID = 1L;
private JPanel panel;
private JLabel label;

public coolgrafik(){

    //super(title);
    setSize(400,60);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    panel = new JPanel();
    panel.setBackground(Color.GRAY);
    label = new JLabel("test");
    panel.add(label);

    MyButton button = new MyButton(Color.green, Color.red, "RUN","STOP");
    panel.add(button);
    button.addActionListener(this);

    add(panel);
}

public static void main(String[] args){
    new coolgrafik().setVisible(true);
    //toggleState(Color.green, Color.red, "RUN","STOP");
}

public void actionPerformed(ActionEvent e) {
    toggleState(Color.green, Color.red, "RUN","STOP");
}
}
</code>```

and this is the button class

```<code>package Grafiktest;

import javax.swing.*;
import java.awt.*;

public class MyButton extends JButton{

private static final long serialVersionUID = 1L;

public MyButton(Color c1, Color c2, String s1, String s2){

    setText(s1);
    setForeground(c1);
    setBackground(c1);
    setOpaque(true);

}

public void toggleState(Color c1, Color c2, String s1, String s2){

    setText(s2);
    setForeground(c2);
    setBackground(c2);
    setOpaque(true);

}
</code>```

}

答:
Let's just stop a second and think about what you're trying to do.  You want to change the state of the button when it's pressed.

The real question is, who's actually responsible for doing that?  Any ActionListener monitoring the button should be focused on carrying out the work they need to do, not managing the button as well, what happens when you have more than one ActionListener attached to the button?  Who becomes responsible for it then?

What about if, instead, we made the button self managing?  That is, the button monitors itself and update its state accordingly

Because you'd need to manage the selected state anyway, I've used a JToggleButton instead, as it has a "selected"/"unselected" state internally.

```<code>public class MyButton extends JToggleButton {

    private static final long serialVersionUID = 1L;

    public class State {
        public Color color;
        public String text;

        public State(Color color, String text) {
            this.color = color;
            this.text = text;
        }

    }

    private final State unselectedState;
    private final State selectedState;

    public MyButton(Color c1, Color c2, String s1, String s2) {

        selectedState = new State(c1, s1);
        unselectedState = new State(c2, s2);

        setContentAreaFilled(false);
        setBorderPainted(false);
        setFocusPainted(false);
        setOpaque(true);

        toggleState();

        getModel().addChangeListener(new ChangeListener() {
            @Override
            public void stateChanged(ChangeEvent e) {
                toggleState();
            }
        });

    }

    public void toggleState() {

        State state = !getModel().isSelected() ? selectedState : unselectedState;

        setText(state.text);
        setForeground(Color.WHITE);
        setBackground(state.color);

    }
}
</code>```

Basically all this does it will configure the button based on the selected state of the ButtonModel.

You could use an ActionListener and register it directly to the button itself in similar fashion, but you'd need to manage which state it's using

Body:
I'm trying to make a button that toggles the state of the button (changes color and text) when pressed. But I can't get the addActionListener to work and I can't find the ToggleState method from my main class. I am new to java and would appreciate your help.

I get the errors
 - “The method addActionListener(ActionListener) in the type AbstractButton is not applicable for the arguments”
- "ActionListener cannot be resolved to a type"

package Grafiktest;

import javax.swing.*;
import java.awt.*;

public class coolgrafik extends JFrame implements ActionListener {

private static final long serialVersionUID = 1L;
private JPanel panel;
private JLabel label;

public coolgrafik(){

    //super(title);
    setSize(400,60);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    panel = new JPanel();
    panel.setBackground(Color.GRAY);
    label = new JLabel("test");
    panel.add(label);

    MyButton button = new MyButton(Color.green, Color.red, "RUN","STOP");
    panel.add(button);
    button.addActionListener(this);

    add(panel);
}

public static void main(String[] args){
    new coolgrafik().setVisible(true);
    //toggleState(Color.green, Color.red, "RUN","STOP");
}

public void actionPerformed(ActionEvent e) {
    toggleState(Color.green, Color.red, "RUN","STOP");
}
}

and this is the button class

package Grafiktest;

import javax.swing.*;
import java.awt.*;

public class MyButton extends JButton{

private static final long serialVersionUID = 1L;

public MyButton(Color c1, Color c2, String s1, String s2){

    setText(s1);
    setForeground(c1);
    setBackground(c1);
    setOpaque(true);

}

public void toggleState(Color c1, Color c2, String s1, String s2){

    setText(s2);
    setForeground(c2);
    setBackground(c2);
    setOpaque(true);

}

}

Body:
Let's just stop a second and think about what you're trying to do.  You want to change the state of the button when it's pressed.

The real question is, who's actually responsible for doing that?  Any ActionListener monitoring the button should be focused on carrying out the work they need to do, not managing the button as well, what happens when you have more than one ActionListener attached to the button?  Who becomes responsible for it then?

What about if, instead, we made the button self managing?  That is, the button monitors itself and update its state accordingly

Because you'd need to manage the selected state anyway, I've used a JToggleButton instead, as it has a "selected"/"unselected" state internally.

public class MyButton extends JToggleButton {

    private static final long serialVersionUID = 1L;

    public class State {
        public Color color;
        public String text;

        public State(Color color, String text) {
            this.color = color;
            this.text = text;
        }

    }

    private final State unselectedState;
    private final State selectedState;

    public MyButton(Color c1, Color c2, String s1, String s2) {

        selectedState = new State(c1, s1);
        unselectedState = new State(c2, s2);

        setContentAreaFilled(false);
        setBorderPainted(false);
        setFocusPainted(false);
        setOpaque(true);

        toggleState();

        getModel().addChangeListener(new ChangeListener() {
            @Override
            public void stateChanged(ChangeEvent e) {
                toggleState();
            }
        });

    }

    public void toggleState() {

        State state = !getModel().isSelected() ? selectedState : unselectedState;

        setText(state.text);
        setForeground(Color.WHITE);
        setBackground(state.color);

    }
}

Basically all this does it will configure the button based on the selected state of the ButtonModel.

You could use an ActionListener and register it directly to the button itself in similar fashion, but you'd need to manage which state it's using


问:
Searching in SQL field WHERE LIKE %$user_id%
I have a small problem.

I have my table as follows:

tbl_groups

```<code>id (int) | teacher_id (int) | student_ids (text)
------------------------------------------------
1        | 14               | 2015,2016,2017
2        | 35               | 15,16,17
3        | 14               | 631
</code>```

student_ids will get filled by a PHP array using implode().

However, when I execute the following query to search the group's id by a student id:

```<code>SELECT `id` FROM `tbl_groups` WHERE `student_ids` LIKE '%15%'
</code>```

I get row 1 and 2 returned. This happens because student_ids "15" will be searched for, and "2015" contains "15" so it will also return it.

How can I prevent this?

答:
You can try this (attention for performance if you have a large table: if you have an index on student_ids, probably it will not be used.  Anyway using LIKE '%xxx%' use it only with "scan" and not with "seek" ):    </p>

```<code>SELECT `id` FROM `tbl_groups` WHERE CONCAT(',',`student_ids`,',') LIKE '%,15,%'
</code>```

Body:
I have a small problem.

I have my table as follows:

tbl_groups

id (int) | teacher_id (int) | student_ids (text)
------------------------------------------------
1        | 14               | 2015,2016,2017
2        | 35               | 15,16,17
3        | 14               | 631

student_ids will get filled by a PHP array using implode().

However, when I execute the following query to search the group's id by a student id:

SELECT `id` FROM `tbl_groups` WHERE `student_ids` LIKE '%15%'

I get row 1 and 2 returned. This happens because student_ids "15" will be searched for, and "2015" contains "15" so it will also return it.

How can I prevent this?

Body:
You can try this (attention for performance if you have a large table: if you have an index on student_ids, probably it will not be used.  Anyway using LIKE '%xxx%' use it only with "scan" and not with "seek" ):

SELECT `id` FROM `tbl_groups` WHERE CONCAT(',',`student_ids`,',') LIKE '%,15,%'


问:
Add timestamp in Powershell output
I have the following code that export a CSV-file from a query.
How do I add a "Get-date" (today) stamp in the end of the file in the filepath?</p>

```<code>$ds.Tables[0] | Export-csv -delimiter ";" -path "C:\temp\TempWarehousingControl.csv" -NoTypeInformation -Force -Encoding UTF8
Get-Content C:\temp\TempWarehousingControl.csv | %{ $_ -replace """""", "NULL"} |%{ $_ -replace """", ""} | out-file -FilePath C:\Batch\Output\WarehousingControl\WarehousingControl.csv -Force -Encoding utf8
</code>```

答:
```<code>$path = "C:\Batch\Output\WarehousingControl\WarehousingControl.csv"
$path = $path.Replace(".csv", "_" + (Get-Date -f "yyy-MM-dd") + ".csv")

$ds.Tables[0] |
    Export-csv -delimiter ";" -path "C:\temp\TempWarehousingControl.csv" -NoTypeInformation -Force -Encoding UTF8

Get-Content C:\temp\TempWarehousingControl.csv |
    %{ $_ -replace """""", "NULL"} |
    %{ $_ -replace """", ""} |
    Out-File -FilePath $path -Force -Encoding utf8
</code>```

Title: Add timestamp in Powershell output

Body:
I have the following code that export a CSV-file from a query.
How do I add a "Get-date" (today) stamp in the end of the file in the filepath?

$ds.Tables[0] | Export-csv -delimiter ";" -path "C:\temp\TempWarehousingControl.csv" -NoTypeInformation -Force -Encoding UTF8
Get-Content C:\temp\TempWarehousingControl.csv | %{ $_ -replace """""", "NULL"} |%{ $_ -replace """", ""} | out-file -FilePath C:\Batch\Output\WarehousingControl\WarehousingControl.csv -Force -Encoding utf8


问:
Where would I put the index.html file in a cloud server hosting environment?
I signed up for a cloud server hosting account since it supports Rails on GoDaddy.  I connected to the IP address through FTP using FileZilla.  The remote site directory has a folder with my username.  I put in an index.html file just to see if it would work, but when I navigate to the IP Address I get a "This site can't be reached error".  Where is the index file supposed to go?</p>

答: It does not matter which cloud server hosting environment you are on, whether it is Alibaba Cloud or any other, the file will be uploaded in directory which is specified in the ftp configuration file. However, if you are using a web server then you need to check the Document root in the configuration file of the web server</p>


问:
DataAnnotations on public fields vs properties in MVC
Why don't DataAnnotations work on public fields? Example:

```<code>namespace Models
{
    public class Product
    {
        [Display(Name = "Name")]
        public string Title; // { get; set; }
    }
}

public ActionResult Test()
{
     return View(new Models.Product() { Title = "why no love?" });
}

@Html.LabelFor(m => m.Title) // will return 'Title' if field, or 'Name' if property
@Html.DisplayFor(m => m.Title)
</code>```

If Title is a field, then the Display attribute seems to have no effect. If Title is changed to a property, it works as expected as displays "Name".

It would seem easy in this example to just change to a property, but I am trying to use the types from F# where they get compiled to a class with fields and not properties.

This was tested in ASP.NET 4 and MVC RC 3.

答:
The reason why DataAnnotations do not work with fields is because the reflection-like mechanism that is used to retrieve the attributes (TypeDescriptor) only supports properties.

While it would not be easy, we could look into making this work with fields if there is enough demand.

Body:
Why don't DataAnnotations work on public fields? Example:

namespace Models
{
    public class Product
    {
        [Display(Name = "Name")]
        public string Title; // { get; set; }
    }
}

public ActionResult Test()
{
     return View(new Models.Product() { Title = "why no love?" });
}

@Html.LabelFor(m => m.Title) // will return 'Title' if field, or 'Name' if property
@Html.DisplayFor(m => m.Title)

If Title is a field, then the Display attribute seems to have no effect. If Title is changed to a property, it works as expected as displays "Name".

It would seem easy in this example to just change to a property, but I am trying to use the types from F# where they get compiled to a class with fields and not properties.

This was tested in ASP.NET 4 and MVC RC 3.


问:
Hibernate Nested SQL Query
There are two tables

Table abc and xyz

Key for abc - customerID

Key for xyz - (customerID, customer_name)

I have a nested query of the following pattern

```<code>"select * from abc whrere customerID in ( select customerID from xyz where customer_name='rohit')"
</code>```

How to query this in Hibernate using Criteria only ?

答:
Solution for the above question.</p>

```<code>Criteria criteria = session.createCriteria(abc.class);
DetachedCriteria detachedCriteria = DetachedCriteria
         .forClass(xyz.class)
         .setProjection(Property.forName("customerID"));
detachedCriteria.add(Restrictions.eq("customerName","rohit"));
criteria.add(Property
                    .forName("customerID")
                    .in(detachedCriteria));
</code>```

Title: Hibernate Nested SQL Query

Body:
There are two tables

Table abc and xyz

Key for abc - customerID

Key for xyz - (customerID, customer_name)

I have a nested query of the following pattern

"select * from abc whrere customerID in ( select customerID from xyz where customer_name='rohit')"

How to query this in Hibernate using Criteria only ?

Body:
Solution for the above question.

Criteria criteria = session.createCriteria(abc.class);
DetachedCriteria detachedCriteria = DetachedCriteria
         .forClass(xyz.class)
         .setProjection(Property.forName("customerID"));
detachedCriteria.add(Restrictions.eq("customerName","rohit"));
criteria.add(Property
                    .forName("customerID")
                    .in(detachedCriteria));


问:
Angular Js redirect with toast message
when I click a button on a html with angular page I need to redirect to other.
I use a javascript function and into it I call $location.path('/newValue')
This work fine, but I can't see toast page 1 success message.
I need show toast message and redirect to page (or show toast message, wait 1 second and redirect to page).
How I can do it?

Thanks

答:
```<code>toastr.info("Toast message here...");
$timeout(function() {
    $location.path('/newValue');
}, 1000);
</code>```

Title: Angular Js redirect with toast message


问:
Any way to set per-solution color options (VS2010)?
Is there any way to configure VS2010 to use different color schemes for different solutions?  On the Macintosh, in the 1990's, I could add wctb resources to documents so they would open with different color schemes.  This made it easier to find the right window to click, and also helped avoid accidentally typing something into the wrong document (otherwise easy to do if one has several similar documents open).  Is there any nice way to achieve a similar effect in VS2010?  I'd mainly like to change the text background color and window background color.

When I was using vs2005 and vbEx2005, I could set vbEx to one scheme and vs to another, but right now I'm using vs2010 for everything.  Is there any nice way to set colors on a per-project basis?

答:
Here's a nice way of doing it.  Select "Macro IDE...", then open up "EnvironmentEvents" and add the following after the "Automatically generated code" region:

```
    Sub handleColorSettings() Handles SolutionEvents.opened, DocumentEvents.documentopening
        Dim myColor As UInt32
        myColor = &HC0FFFF
        Try
            myColor = UInt32.Parse(IO.File.ReadAllText(DTE.Solution.FullName & ".bgcolor.txt"), Globalization.NumberStyles.AllowHexSpecifier)
        Catch ex As Exception

        End Try
        CType(DTE.Properties("FontsAndColors", "TextEditor").Item("FontsAndColorsItems").Object, EnvDTE.FontsAndColorsItems).Item("Plain Text").Background = myColor
    End Sub
```

Any time a project is opened, or a file is opened within a project, the system will look for a file with the name "(fullSolutionName).bgcolor.txt".  If, e.g., the solution is "myThing.sln", the file used will be "myThing.sln.bgcolor.txt".  If such a file is found and it contains a valid hex number, that will be used as the background color.  Otherwise, a default color (&hC0FFFF above, but easily changeable) will be used.

Body:
Here's a nice way of doing it.  Select "Macro IDE...", then open up "EnvironmentEvents" and add the following after the "Automatically generated code" region:

    Sub handleColorSettings() Handles SolutionEvents.opened, DocumentEvents.documentopening
        Dim myColor As UInt32
        myColor = &HC0FFFF
        Try
            myColor = UInt32.Parse(IO.File.ReadAllText(DTE.Solution.FullName & ".bgcolor.txt"), Globalization.NumberStyles.AllowHexSpecifier)
        Catch ex As Exception

        End Try
        CType(DTE.Properties("FontsAndColors", "TextEditor").Item("FontsAndColorsItems").Object, EnvDTE.FontsAndColorsItems).Item("Plain Text").Background = myColor
    End Sub

Any time a project is opened, or a file is opened within a project, the system will look for a file with the name "(fullSolutionName).bgcolor.txt".  If, e.g., the solution is "myThing.sln", the file used will be "myThing.sln.bgcolor.txt".  If such a file is found and it contains a valid hex number, that will be used as the background color.  Otherwise, a default color (&hC0FFFF above, but easily changeable) will be used.


问:
How to create ether wallet?
I want to create users ether wallet through code. is there any api or something to create ether wallet which they can use to transfer & receive ether ?</p>

答:
You can use pyethapp (python based client) for creating ethereum wallet, transferring funds.

Link: https://github.com/ethereum/pyethapp

It has very simple command to create account

```<code>$ pyethapp account new
</code>```

Explore examples also: https://github.com/ethereum/pyethapp/tree/develop/examples

Title: How to create ether wallet?

Body:
You can use pyethapp (python based client) for creating ethereum wallet, transferring funds.

Link: https://github.com/ethereum/pyethapp

It has very simple command to create account

$ pyethapp account new

Explore examples also: https://github.com/ethereum/pyethapp/tree/develop/examples


问:
Is pthread_join() a critical function?
According to POSIX, a Thread ID can be reused if the original bearer thread finished. Therefore, would one need to use a mutex or semaphore when calling pthread_join()? Because, it could happen that the target thread, which one wants to join, already terminated and another thread with the same thread ID was created, before calling pthread_join() in the original thread. This would make the original thread believe that the target thread has not finished, although this is not the case.

答:
I think you'll find this works much the same way as processes in UNIX. A joinable thread is not considered truly finished until something has actually joined it.

This is similar to the UNIX processes in that, even though they've technically exited, enough status information (including the PID, which cannot be re-used yet) hangs around until another process does a wait on it. Only after that point does the PID become available for re-use. This kind of process is called a zombie, since it's dead but not dead.

This is supported by the pthread_join documentation which states:

Failure to join with a thread that is joinable (i.e., one that is not detached), produces a "zombie thread".  Avoid doing this, since each zombie thread consumes some system resources, and when enough zombie threads have accumulated, it will no longer be possible to create new threads (or processes).

and pthread_create, which states:

Only when a terminated joinable thread has been joined are the last of its resources released back to the system.

Title: Is pthread_join() a critical function?


问:
Subversion: base checksum mismatch
I am trying to commit a change in subversion to a file. This file belongs to a directory that is linked to my project via an external, and is pegged at a certain revision.

When I do a commit, I get the error:

```<code>Commit failed
Base checksum mismatch on....
</code>```

I tried to check out the directory again to ensure that it was clean and perform the commit again, but I still receive the same error.

Could it be related to committing to a pegged file? I thought that committing onto a file that is pegged should be possible and essentially branches off this code?

答:
What worked for me is to:

```<code>svn up --set-depth=empty
</code>```

then

```<code>svn up --set-depth=infinity
</code>```

error is gone!

Title: Subversion: base checksum mismatch

Body:
I am trying to commit a change in subversion to a file. This file belongs to a directory that is linked to my project via an external, and is pegged at a certain revision.

When I do a commit, I get the error:

Commit failed
Base checksum mismatch on....

I tried to check out the directory again to ensure that it was clean and perform the commit again, but I still receive the same error.

Could it be related to committing to a pegged file? I thought that committing onto a file that is pegged should be possible and essentially branches off this code?

Body:
What worked for me is to:

svn up --set-depth=empty

then

svn up --set-depth=infinity

error is gone!


问:
Why is SQL Server casting GETDATE() to an other value than CAST('yyyy-mm-dd')?
I'm working with SQL Server for many years and I think I have a really strange thing here.

When I execute these 2 queries:

```<code>SELECT CAST(CAST('2017-03-28' AS DATETIME) AS INT)

SELECT CAST(GETDATE() AS INT), GETDATE()
</code>```

I get these outputs:

```<code>42820
42821   2017-03-28 20:49:10.360
</code>```

So I'm totally clueless about this; how can 28 march 2017 be cast to 42820 and 28 march 2017 20:49 to 42821?

To make it a little more strange, I've figured out that the point for going 1 higher is 12:00 am. I'm really lost...

Can somebody enlighten me?

答: Ok. It's clear how it works. But it's completely new to me.</p>

Body:
I'm working with SQL Server for many years and I think I have a really strange thing here.

When I execute these 2 queries:

SELECT CAST(CAST('2017-03-28' AS DATETIME) AS INT)

SELECT CAST(GETDATE() AS INT), GETDATE()

I get these outputs:

42820
42821   2017-03-28 20:49:10.360

So I'm totally clueless about this; how can 28 march 2017 be cast to 42820 and 28 march 2017 20:49 to 42821?

To make it a little more strange, I've figured out that the point for going 1 higher is 12:00 am. I'm really lost...

Can somebody enlighten me?


问:
C# How to find out particular USB device from multiple connected same USB device?
I have same 2 Logitech webcam devices (c920) . I want to assign this 2 devices into IN-Camera and OUT-Camera since i need transaction of the IN and OUT users.

Now, when i connect the same into the PC. the VID, PID are same since the OEM also same.

So How can i find out the 2 devices each time it's plugged into the PC or after PC restarted by any reason.

So I am looking for some UNIQUE USB descriptor for this USB device's.

need Help on this.

答:
The following code might help to access the hardware IDs of your USB devices:</p>

```<code>using System;
using System.Management;

namespace akWmiDeviceDemo
{
    class Program
    {
        static void Main(string[] args)
        {
        //  inspired by:
        //  https://blogs.msdn.microsoft.com/powershell/2007/02/24/displaying-usb-devices-using-wmi/
            string strComputer = ".";
            ManagementScope scope = new ManagementScope(@"\\" + strComputer + @"\root\cimv2");
            ObjectQuery queryUsbControllers = new ObjectQuery("Select * From Win32_USBControllerDevice");
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, queryUsbControllers);
            ManagementObjectCollection usbControllers = searcher.Get();

            foreach (ManagementObject usbController in usbControllers)
            {
                string dependent = (string)usbController["Dependent"];
                string[] names = dependent.Replace("\"", "").Split(new char [] {'='});
                string strUsbControllerName = names[1];
                ObjectQuery queryUsbDevices = new ObjectQuery("Select * From Win32_PnPEntity Where DeviceID = '" + strUsbControllerName + "'");
                ManagementObjectSearcher deviceSearcher = new ManagementObjectSearcher(scope, queryUsbDevices);
                ManagementObjectCollection usbDevices = deviceSearcher.Get();

                o("");
                o("USB controller = {0}", strUsbControllerName);
                foreach (ManagementObject usbDevice in usbDevices)
                {
                    o("description = {0}", usbDevice["Description"]);
                    o("PnPDeviceID = {0}", usbDevice["PnPDeviceID"]);
                }
            }
        }

        static void o(string format, params object[] args)
        {
            Console.WriteLine(format, args);
        }
    }
}
</code>```

Body:
The following code might help to access the hardware IDs of your USB devices:

using System;
using System.Management;

namespace akWmiDeviceDemo
{
    class Program
    {
        static void Main(string[] args)
        {
        //  inspired by:
        //  https://blogs.msdn.microsoft.com/powershell/2007/02/24/displaying-usb-devices-using-wmi/
            string strComputer = ".";
            ManagementScope scope = new ManagementScope(@"\\" + strComputer + @"\root\cimv2");
            ObjectQuery queryUsbControllers = new ObjectQuery("Select * From Win32_USBControllerDevice");
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, queryUsbControllers);
            ManagementObjectCollection usbControllers = searcher.Get();

            foreach (ManagementObject usbController in usbControllers)
            {
                string dependent = (string)usbController["Dependent"];
                string[] names = dependent.Replace("\"", "").Split(new char [] {'='});
                string strUsbControllerName = names[1];
                ObjectQuery queryUsbDevices = new ObjectQuery("Select * From Win32_PnPEntity Where DeviceID = '" + strUsbControllerName + "'");
                ManagementObjectSearcher deviceSearcher = new ManagementObjectSearcher(scope, queryUsbDevices);
                ManagementObjectCollection usbDevices = deviceSearcher.Get();

                o("");
                o("USB controller = {0}", strUsbControllerName);
                foreach (ManagementObject usbDevice in usbDevices)
                {
                    o("description = {0}", usbDevice["Description"]);
                    o("PnPDeviceID = {0}", usbDevice["PnPDeviceID"]);
                }
            }
        }

        static void o(string format, params object[] args)
        {
            Console.WriteLine(format, args);
        }
    }
}


问:
AngularJS display data of index that has matching value
I am working on a dashboard and am trying to display a certain piece of data. In my scope I have a project which consists of a couple fields and an array of users. The users consist of the following fields:

user_id

user_name

user_email

role

I want to display the user_name of the role which matches a certain value.  Is there a way to do this within my html file or is it recommended to do this in my controller?

My table code looks as follows:

```<code><tbody md-body>
        <tr md-row md-select="project" md-select-id="name" md-auto-select
            ng-repeat="project in projects.data | orderBy : myOrder">
            <td md-cell ng-click="getProject()">{{project.title}}</td>
            <td md-cell><i class="material-icons" style="color: green">radio_button_checked</i></td>
            <td md-cell>{{project.phase}}</td>
            <td md-cell>{{project.budget_indication}}</td>
            <td md-cell>{{project.users}}</td> <!-- Display user with specific role -->
            <td md-cell>{{project.start_date | date:dd/MM/yyyy}}</td>
        </tr>
</tbody>
</code>```

Thanks in advance!

答:
You can use filter:role

{{x.users | filter: role= "User"}}

Here is an example I have taken to get your solution,

<!DOCTYPE html>

Role: {{ role ? role : 'All Data'}}

{{x.users | filter: role= role}}

```

Just change the role to "Admin" and check the filter

Here is the DEMO link which contain ADMIN role

Body:
I am working on a dashboard and am trying to display a certain piece of data. In my scope I have a project which consists of a couple fields and an array of users. The users consist of the following fields:

user_id

user_name

user_email

role

I want to display the user_name of the role which matches a certain value.  Is there a way to do this within my html file or is it recommended to do this in my controller?

My table code looks as follows:

            {{project.title}}
            radio_button_checked
            {{project.phase}}
            {{project.budget_indication}}
            {{project.users}}
            {{project.start_date | date:dd/MM/yyyy}}

Thanks in advance!

Body:
You can use filter:role

<div>{{x.users | filter: role= "User"}}</div>

Here is an example I have taken to get your solution,

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body ng-app="myApp" ng-controller="myCtrl">

Role: {{ role ? role : 'All Data'}}    <br><br>

<div ng-repeat="x in projects">
  <div>{{x.users | filter: role= role}}</div>

</div>

<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.projects = [{
  users:  [
    {
      "Name" : "Alfreds Futterkiste",
      "Country" : "Germany",
      "Role": "User"
    },
    {
      "Name" : "Berglunds snabbköp",
      "Country" : "Sweden",
      "Role": "Admin"
    },
    {
      "Name" : "Centro comercial Moctezuma",
      "Country" : "Mexico",
      "Role": "User"
    },
    {
      "Name" : "Ernst Handel",
      "Country" : "Austria",
      "Role": "Admin"
    }
  ]
  }]

  $scope.role = "User"

  });
</script>

</body>
</html>

Just change the role to "Admin" and check the filter

Here is the DEMO link which contain ADMIN role


问:
game is crash on S3 in unity 5.4
My game is crash on samsung S3 but not on other devices in unity 5.4. Games is working fine in main menu but when it loads gameplay it will crash only on S3.<br>
i have debug on ddms it shows error like heap_msk=3000000 flags=1,onReceive: android.intent.action.CONFIGURATION_CHANGED – </p>

答:
Well it means you are creating too many objects in game play that causing game to crash on low memory devices.

You can sort out this problem by connecting your device and run profiler in unity. That way you can check what causing the problem. If CPU is taking more resources than you need to optimize your code. If overhead is on GPU and if it is a 3d game than you must reduce no of polygons, tris and try to combine meshes and make atlases.

Also you can check if you shaders attached to your camera that will also be visible in profiler. It can tell you that camera render is taking memory.

Hope it helps !

Title: game is crash on S3 in unity 5.4

Body:
My game is crash on samsung S3 but not on other devices in unity 5.4. Games is working fine in main menu but when it loads gameplay it will crash only on S3.

i have debug on ddms it shows error like heap_msk=3000000 flags=1,onReceive: android.intent.action.CONFIGURATION_CHANGED –


问:
When to use ContextCompat class
I want to know when to use ContextCompact class in an application. Basically what is it used for and when to use it? I have read developers site, it says ContextCompact is a "helper for accessing features in Context". But what does this line mean?

答:
basically according to the official developer site it is a Helper for accessing features in Context introduced after API level 4 in a backwards compatible fashion.

You can look into this link for more details. https://developer.android.com/reference/android/support/v4/content/ContextCompat.html

Basically getBackgroundResource or getColor method are deprecated and using ContextCompact is an alternative for that. I hope this helps.

ContentLicense: CC BY-SA 4.0

Title: When to use ContextCompat class


问:
Wrong font displayed in PDF when using wkhtmltopdf
I am using wkhtmltopdf to print reports that are generated inside a react html page. For all the text, the css has the font set to 'Open Sans', sans-serif inside my html I have the following in my header to load the Open Sans font:

```<code><link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
</code>```

This all seems to work fine when I run wkhtmltopdf on my development machine, and I get output looking like this:

However, on my server (on Azure running as a Azure Web App) I get the following output:

As you can see, all the text looks very pixelated, except for the header that is bold for some reason. If you see both the bold and normal text, you can also see that the Open Sans font is not used (easiest to see on the g's).

So the question is twofold:

Why is not the Open Sans font being used on Azure?

Why is the text pixelated? If I change 'Open Sans', sans-serif to just sans-serif it still looks ok in the browser with the default sans-serif font.

Appreciate all help on this!

EDIT

Some additional information. The local PDF is 23Kb and the server PDF is 207Kb. On the server PDF only the Bold text is selectable, and not the rest, so it seems like the non-bold text is treated as an image, and not actual text.

Also, for the local PDF is says under Fonts OpenSansRegular (Embedded Subset), Type: TrueType (CID), Encoding:Identity-H that seems reasonable. However, under the server/Azure PDF it says under Fonts ArialBold (Embedded Subset), Type: TrueType (CID), Encoding:Identity-H.

So for some reason the wrong font is getting embedded, and the non-bold text is treated as an image.

答:
According to document we could know that wkhtmltopdf is not supported on the Azure WebApp currently. And Azure team are working on it.The following is snippet from the document.

PDF generation from HTML

There are multiple libraries used to convert HTML to PDF. Many Windows/.NET specific versions leverage IE APIs and therefore leverage User32/GDI32 extensively. These APIs are largely blocked in the sandbox (regardless of plan) and therefore these frameworks do not work in the sandbox.

There are some frameworks that do not leverage User32/GDI32 extensively (wkhtmltopdf, for example) and we are working on enabling these in Basic+ the same way we enabled SQL Reporting.

Body:
I am using wkhtmltopdf to print reports that are generated inside a react html page. For all the text, the css has the font set to 'Open Sans', sans-serif inside my html I have the following in my header to load the Open Sans font:

<link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">

This all seems to work fine when I run wkhtmltopdf on my development machine, and I get output looking like this:

However, on my server (on Azure running as a Azure Web App) I get the following output:

As you can see, all the text looks very pixelated, except for the header that is bold for some reason. If you see both the bold and normal text, you can also see that the Open Sans font is not used (easiest to see on the g's).

So the question is twofold:

Why is not the Open Sans font being used on Azure?

Why is the text pixelated? If I change 'Open Sans', sans-serif to just sans-serif it still looks ok in the browser with the default sans-serif font.

Appreciate all help on this!

EDIT

Some additional information. The local PDF is 23Kb and the server PDF is 207Kb. On the server PDF only the Bold text is selectable, and not the rest, so it seems like the non-bold text is treated as an image, and not actual text.

Also, for the local PDF is says under Fonts OpenSansRegular (Embedded Subset), Type: TrueType (CID), Encoding:Identity-H that seems reasonable. However, under the server/Azure PDF it says under Fonts ArialBold (Embedded Subset), Type: TrueType (CID), Encoding:Identity-H.

So for some reason the wrong font is getting embedded, and the non-bold text is treated as an image.