问:
HTML5 drag and drop - "dragend" not fired when source element is moved or removed by Angular
I'm using Google's Angular Drag and Drop Lists, but I think the problem is with the underlying HTML5 drag and drop not working with Angular ( v1.6.1 ).

According to MDN ( the note at the bottom, under "Finishing a Drag" ):

"dragend" is not dispatched if the source node is moved or removed during the drag (e.g. on "drop" or "dragover").  bug 460801

I'm altering the Angular model in the "dragover" event to display feedback during the drag operation. I think Angular is moving or removing ( and recreating ) my source element and this is what is stopping "dragend" from firing.

This means I have no way of knowning when the drag operation is finished when unsuccessful ( when successful the "drop" event is fired on the target element )

Any ideas please?

答:
Answering my own question for posterity!

I solved the issue my making sure the Angular digest loop did not run during the drag and drop operation.

This seems to support my theory about the source element being removed and recreated by Angular preventing the dragend event from firing.

I had to fall back to JQuery to provide visual feedback during the drag and drop.

HTH


来源: stackexchange

问:
Certificate Authority for myself/small organisation
I need a small CA software which meet following criteria:

CLI Interface (we all really hate gui things for server software, don't we?)

Issuing certificates for websites. So I just can install one root certificate on client machines to get rid of that warnings)

Issuing user certificates (as p12 and other stuff, so I can authenticate using them) with predefined values.

I was looking at tinyca but it's somewhat outdated and didnt worked for me well.

Openssl can do all of this, so I can code a bunch of shell scripts (or maybe Makefile) to automate this task. So I was wondering if already somebody did this?

答: XCA — A neat little tool, that fit perfectly to my requirements. No CLI though.</p>

ContentLicense: CC BY-SA 2.5


问:
Screen fade not working in Daydream VR since I migrated to Unity 5.6
I'm building a DayDream VR game. I've previously had a script to fade out the screen when the user is clicking somewhere to change levels/scenes.

Since I've migrated to Unity 5.6 / Google VR SDK 1.2, any fading effect stopped working. But it still works in Preview mode on my desktop. This is because they changed the way the Camera works. I've tried different scripts online but none of them work, would anyone have an idea on how to do a screen fade on scene change please?

Here is the current main part of the code:

```<code>// Derived from OVRScreenFade
float elapsedTime = 0.0f;
Color color = fadeColor;
color.a = 0.0f;
fadeMaterial.color = color;
while (elapsedTime < fadeTime)
{
    yield return new WaitForEndOfFrame();
    elapsedTime += Time.deltaTime;
    color.a = Mathf.Clamp01(elapsedTime / fadeTime);
    fadeMaterial.color = color;
}
</code>```

I've also attempted to use Autofade script. As I mentioned they all work when tried the game on my desktop, they just don't work on the Android phone :(.

Any idea why please?

EDIT: Here is some extra code

```<code>public Material fadeMaterial = null; //starts NULL

        //applied to cameras inside a function
        foreach (Camera c in Camera.allCameras)
        {
            var fadeControl = c.gameObject.AddComponent<ScreenFadeControl>();
            fadeControl.fadeMaterial = fadeMaterial;
            fadeControls.Add(fadeControl);
        }
</code>```

FINAL SOLUTION

Using the answer given here, I've created a script file with instructions, feel free to download it and use it if you need the same thing:

https://gist.github.com/xtrimsky/0d58ee4db1964577893353365903b91a

答:
If you want to fade the entire screen I suggest:

In Unity add a Panel (make sure that it covers the whole screen).

Make a new Material and attach it to the Panel.

The Material should have Rendering Mode set to Transparent.

Attach the following Script to the Panel.

```<code>public Material m;
public float _colorSpeed = 0.01f;
private Color c;
private bool start = false;

void Update()
{
    if (start)
    {
        if (c.a < 1.0f)
            c.a = c.a + _colorSpeed;
        m.color = c;
    }
}
public void Fade()
{
    c = m.color;
    c.a = 0.0f;
    start = true;
}
</code>```

Call the Fade() method when necessary.

  Hope that solves your problem!

ContentLicense: CC BY-SA 3.0

Body:
I'm building a DayDream VR game. I've previously had a script to fade out the screen when the user is clicking somewhere to change levels/scenes.

Since I've migrated to Unity 5.6 / Google VR SDK 1.2, any fading effect stopped working. But it still works in Preview mode on my desktop. This is because they changed the way the Camera works. I've tried different scripts online but none of them work, would anyone have an idea on how to do a screen fade on scene change please?

Here is the current main part of the code:

// Derived from OVRScreenFade
float elapsedTime = 0.0f;
Color color = fadeColor;
color.a = 0.0f;
fadeMaterial.color = color;
while (elapsedTime < fadeTime)
{
    yield return new WaitForEndOfFrame();
    elapsedTime += Time.deltaTime;
    color.a = Mathf.Clamp01(elapsedTime / fadeTime);
    fadeMaterial.color = color;
}

I've also attempted to use Autofade script. As I mentioned they all work when tried the game on my desktop, they just don't work on the Android phone :(.

Any idea why please?

EDIT: Here is some extra code

public Material fadeMaterial = null; //starts NULL

        //applied to cameras inside a function
        foreach (Camera c in Camera.allCameras)
        {
            var fadeControl = c.gameObject.AddComponent<ScreenFadeControl>();
            fadeControl.fadeMaterial = fadeMaterial;
            fadeControls.Add(fadeControl);
        }

FINAL SOLUTION

Using the answer given here, I've created a script file with instructions, feel free to download it and use it if you need the same thing:

https://gist.github.com/xtrimsky/0d58ee4db1964577893353365903b91a

Body:
If you want to fade the entire screen I suggest:

In Unity add a Panel (make sure that it covers the whole screen).

Make a new Material and attach it to the Panel.

The Material should have Rendering Mode set to Transparent.

Attach the following Script to the Panel.

public Material m;
public float _colorSpeed = 0.01f;
private Color c;
private bool start = false;

void Update()
{
    if (start)
    {
        if (c.a < 1.0f)
            c.a = c.a + _colorSpeed;
        m.color = c;
    }
}
public void Fade()
{
    c = m.color;
    c.a = 0.0f;
    start = true;
}

Call the Fade() method when necessary.

  Hope that solves your problem!


问:
Angular 2 templates methods vs getters
I'm wondering if there is any benefit to do this:

```<code>  <div>{{getSomething()}}</div>

  export class MyComp {
    getSomething() { return ...}
  }
</code>```

Over this:

```<code> <div>{{getSomething}}</div>

 export class MyComp {
   get getSomething() { return ...}
 }
</code>```

Use methods vs getters to display calculated data.

答:
The difference is in the first case you use a function in expression, but in the second case you use a peoperty. So you can use

```<code><div>{{something}}</div>

export class MyComp {
  get something() { return ...}
}
</code>```

The benefits of using second method is to use encapsulation of the property inside the class and you need to access it outside the class.

Getters and setters are part of ES5 spec. You can read about getter and setter.

Title: Angular 2 templates methods vs getters

Body:
I'm wondering if there is any benefit to do this:

{{getSomething()}}

  export class MyComp {
    getSomething() { return ...}
  }

Over this:

{{getSomething}}

 export class MyComp {
   get getSomething() { return ...}
 }

Use methods vs getters to display calculated data.

Body:
The difference is in the first case you use a function in expression, but in the second case you use a peoperty. So you can use

<div>{{something}}</div>

export class MyComp {
  get something() { return ...}
}

The benefits of using second method is to use encapsulation of the property inside the class and you need to access it outside the class.

Getters and setters are part of ES5 spec. You can read about getter and setter.

ContentLicense: CC BY-SA 4.0


问:
Using django generic views
I am getting an error using the deleteview while create and update view are working fine and I want to redirect my deleteview to my index page My codes are:-

Views.py-

```<code>from django.views import generic
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.core.urlresolvers import reverse_lazy
from .models import Album

class AlbumDelete(DeleteView):
    model = Album
    success_url = reverse_lazy('music:index')
</code>```

urls.py-

```<code>url(r'^album/(?P<pk>[0-9]+)/delete/$', views.AlbumDelete.as_view(),
name='album-delete'),
</code>```

music/index.html -

```<code>`<a href="{% url 'music:album-delete' album.id %}"><span class="glyphicon
glyphicon-trash"></span></a>`
</code>```

Error is

TemplateDoesNotExist at /polls/album/2/delete/

答:
You don't have your default view. Please check docs

Example myapp/author_confirm_delete.html:

```<code><form action="" method="post">{% csrf_token %}
<p>Are you sure you want to delete "{{ object }}"?</p>
<input type="submit" value="Confirm" />
</code>```

Title: Using django generic views

Body:
I am getting an error using the deleteview while create and update view are working fine and I want to redirect my deleteview to my index page My codes are:-

Views.py-

from django.views import generic
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.core.urlresolvers import reverse_lazy
from .models import Album

class AlbumDelete(DeleteView):
    model = Album
    success_url = reverse_lazy('music:index')

urls.py-

url(r'^album/(?P<pk>[0-9]+)/delete/$', views.AlbumDelete.as_view(),
name='album-delete'),

music/index.html -

``

Error is

TemplateDoesNotExist at /polls/album/2/delete/

Body:
You don't have your default view. Please check docs

Example myapp/author_confirm_delete.html:

<form action="" method="post">{% csrf_token %}
<p>Are you sure you want to delete "{{ object }}"?</p>
<input type="submit" value="Confirm" />


问:
Why am I getting a list index out of range error?
I'm not sure why I am getting the following error:

```<code>builtins.IndexError: list index out of range
</code>```

at the following line (line 5):

```<code>C[A[key(a)]] == C[A[key(a)]] + 1
</code>```

An example of input for this code would be A = [2, -2, 1] and key = lambda x: x**2, and in the loop on line 4-5, it takes the key of item at A[a] as the chosen index for array C, and increments the value at that index by 1. For example: C[A[key(0)]], or C[4], is 0, and it is incremented to 1.

```<code>def key_positions(A, key):
    k = key(max(A, key = key))
    C = [0] * (k+1)
    for a in A:
        C[A[key(a)]] == C[A[key(a)]] + 1
    for i in range(0, k):
        sum = C[i]
    return C
</code>```

答:
You are trying to treat key(a) as an index into the list A. Neither a nor key(a) are valid indices in the range [0, len(A)].

If you wanted to count occurrences of key(a), just use that directly as an index into C:

```<code>def key_positions(A, key):
    k = key(max(A, key = key))
    C = [0] * (k+1)
    for a in A:
        C[key(a)] += 1
    for i in range(0, k):
        sum = C[i]
    return C
</code>```

I used += augmented assignment here rather than the more verbose C[key(a)] = C[key(a)] + 1; this saves re-executing the key() function each time.

Calculating the maximum k value is also simpler with:

```<code>k = max(key(a) for a in A)
</code>```

Next, your loop with sum = C[i] is also nonsensical; the loop is redundant as you don't ever use sum and you could have used sum = C[-1] for all that the loop does.

Body:
I'm not sure why I am getting the following error:

builtins.IndexError: list index out of range

at the following line (line 5):

C[A[key(a)]] == C[A[key(a)]] + 1

An example of input for this code would be A = [2, -2, 1] and key = lambda x: x**2, and in the loop on line 4-5, it takes the key of item at A[a] as the chosen index for array C, and increments the value at that index by 1. For example: C[A[key(0)]], or C[4], is 0, and it is incremented to 1.

def key_positions(A, key):
    k = key(max(A, key = key))
    C = [0] * (k+1)
    for a in A:
        C[A[key(a)]] == C[A[key(a)]] + 1
    for i in range(0, k):
        sum = C[i]
    return C

Body:
You are trying to treat key(a) as an index into the list A. Neither a nor key(a) are valid indices in the range [0, len(A)].

If you wanted to count occurrences of key(a), just use that directly as an index into C:

def key_positions(A, key):
    k = key(max(A, key = key))
    C = [0] * (k+1)
    for a in A:
        C[key(a)] += 1
    for i in range(0, k):
        sum = C[i]
    return C

I used += augmented assignment here rather than the more verbose C[key(a)] = C[key(a)] + 1; this saves re-executing the key() function each time.

Calculating the maximum k value is also simpler with:

k = max(key(a) for a in A)

Next, your loop with sum = C[i] is also nonsensical; the loop is redundant as you don't ever use sum and you could have used sum = C[-1] for all that the loop does.


答:
I looked deeper into this and played with typescript Playground.
I declared two classes one with getter and the second with get method as described in your questions.

Lets see how it looks like:

In the first example we declared a method for getting the property value in the following way:

```<code>class Greeter {
  greeting: string;
  constructor(message: string) {
      this.greeting = message;
  }
   getGreeting() {
      return this.greeting;
  }
}
</code>```

Which after translation to javascript it looks like:

```<code>var Greeter = (function () {
   function Greeter(message) {
       this.greeting = message;
   }
   Greeter.prototype.getGreeting = function () {
       return this.greeting;
   };
   return Greeter;
}());
</code>```

And regarding the second example where we declared a getter in the following way:

```<code>class GetterGreeter {
   _greeting: string;
   constructor(message: string) {
       this._greeting = message;
   }
    get greeting() {
       return this._greeting;
   }
}
</code>```

Which after translation looks like:

```<code>var GetterGreeter = (function () {
   function GetterGreeter(message) {
       this._greeting = message;
   }
   Object.defineProperty(GetterGreeter.prototype, "greeting", {
       get: function () {
           return this._greeting;
       },
       enumerable: true,
       configurable: true
   });
   return GetterGreeter;
}());
</code>```

(You can play with the declaration and the translation to javascript here)

As you can see with get method (as in your first example) the method is declared on the prototype and in your second example using the getter pattern typescript uses the defineProperty api.

In both cases we are invoking a method and angular will also call a method during its change detection to identify changes and re-render.

As I see it this is only a syntactic sugar for the same approach and I don't see any performance benefit for one of the methods.

Title: Angular 2 templates methods vs getters

Body:
I looked deeper into this and played with typescript Playground.
I declared two classes one with getter and the second with get method as described in your questions.

Lets see how it looks like:

In the first example we declared a method for getting the property value in the following way:

class Greeter {
  greeting: string;
  constructor(message: string) {
      this.greeting = message;
  }
   getGreeting() {
      return this.greeting;
  }
}

Which after translation to javascript it looks like:

var Greeter = (function () {
   function Greeter(message) {
       this.greeting = message;
   }
   Greeter.prototype.getGreeting = function () {
       return this.greeting;
   };
   return Greeter;
}());

And regarding the second example where we declared a getter in the following way:

class GetterGreeter {
   _greeting: string;
   constructor(message: string) {
       this._greeting = message;
   }
    get greeting() {
       return this._greeting;
   }
}

Which after translation looks like:

var GetterGreeter = (function () {
   function GetterGreeter(message) {
       this._greeting = message;
   }
   Object.defineProperty(GetterGreeter.prototype, "greeting", {
       get: function () {
           return this._greeting;
       },
       enumerable: true,
       configurable: true
   });
   return GetterGreeter;
}());

(You can play with the declaration and the translation to javascript <a href="http://www.typescriptlang.org/play/index.html#src=class%20Greeter%20%7B%0D%0A%20%20%20%20greeting%3A%20string%3B%0D%0A%20%20%20%20constructor(message%3A%20string)%20%7B%0D%0A%20%20%20%20%20%20%20%20this.greeting%20%3D%20message%3B%0D%0A%20%20%20%20%7D%0D%0A%20%20%20%20%20getGreeting()%20%7B%0D%0A%20%20%20%20%20%20%20%20return%20this.greeting%3B%0D%0A%20%20%20%20%7D%0D%0A%7D%0D%0A%0D%0Aclass%20GetterGreeter%20%7B%0D%0A%20%20%20%20_greeting%3A%20string%3B%0D%0A%20%20%20%20constructor(message%3A%20string)%20%7B%0D%0A%20%20%20%20%20%20%20%20this._greeting%20%3D%20message%3B%0D%0A%20%20%20%20%7D%0D%0A%20%20%20%20%20get%20greeting()%20%7B%0D%0A%20%20%20%20%20%20%20%20return%20this._greeting%3B%0D%0A%20%20%20%20%7D%0D%0A%7D" rel="noreferrer">here)

As you can see with get method (as in your first example) the method is declared on the prototype and in your second example using the getter pattern typescript uses the defineProperty api.

In both cases we are invoking a method and angular will also call a method during its change detection to identify changes and re-render.

As I see it this is only a syntactic sugar for the same approach and I don't see any performance benefit for one of the methods.


问:
A strange phenomenon while using the "dmvnorm" function
I want to use this function to calculate but it keeps telling me this problem.My "means" is 1*2,and "covars" is 2*2 array.And the length of "means" and ncols of "covars" is the same.I don't know why...

This is my codes

and this is the wrong message

my inputs are

```<code> weights<-c(1/3,1/3,1/3)
means<-matrix(1:6,nrow=3,byrow=FALSE)
covars<-array(1,dim=c(2,2,3))
EM(d,weights,means,covars,300,3,10,0.0001)
</code>```

and the "d" is

the d is a 300*2 matrix.I capture a little.
I'm so sorry that I don't have a good command of this website and I don't know how to put so many data on it.

Thank you so much!

答:
The only possible cause is your input data d. It must be a two-column matrix as you have a bivariate normal distribution. The following reproduces your error:

```<code>library(mvtnorm)

# 3 columns
dmvnorm(matrix(runif(6), 2, 3)), c(0,0), diag(2))
</code>```

But this is fine

```<code># 2 columns
dmvnorm(matrix(runif(6), 3, 2)), c(0,0), diag(2))
</code>```

I think your d has two rows but many columns.

Body:
I want to use this function to calculate but it keeps telling me this problem.My "means" is 1*2,and "covars" is 2*2 array.And the length of "means" and ncols of "covars" is the same.I don't know why...

This is my codes

and this is the wrong message

my inputs are

 weights<-c(1/3,1/3,1/3)
means<-matrix(1:6,nrow=3,byrow=FALSE)
covars<-array(1,dim=c(2,2,3))
EM(d,weights,means,covars,300,3,10,0.0001)

and the "d" is

the d is a 300*2 matrix.I capture a little.
I'm so sorry that I don't have a good command of this website and I don't know how to put so many data on it.

Thank you so much!

Body:
The only possible cause is your input data d. It must be a two-column matrix as you have a bivariate normal distribution. The following reproduces your error:

library(mvtnorm)

# 3 columns
dmvnorm(matrix(runif(6), 2, 3)), c(0,0), diag(2))

But this is fine

# 2 columns
dmvnorm(matrix(runif(6), 3, 2)), c(0,0), diag(2))

I think your d has two rows but many columns.


问:
What is the difference between "lea eax, [ebx + eax]" and "add eax, ebx" in x86-32 assembly?
GCC made me some assembly code, and inside theres this statement:

```<code>lea eax, [ebx+eax]
</code>```

(Intel Syntax)
Just curious, what would the difference between that, and:

```<code>add eax, ebx
</code>```

Be?

eax, and ebx contains return values from functions :)

```<code>mov eax, DWORD PTR [ebp+8]
mov DWORD PTR [esp], eax
call CALC1
mov ebx, eax.
mov eax, DWORD PTR [ebp+8]
mov DWORD PTR [esp], eax
call CALC2
lea eax, [ebx+eax]
</code>```

答:
You can put the result into another register than EAX, such as lea edx, eax + ebx. add cannot do it.

lea can also have an additional third operand such as lea eax, ebp + esi + 12 which makes it a handier alternative to add instruction.

You can also combine certain (word-sized) multiplication operations with it, such as lea eax, ebp + eax * 8.

Not to mention that it describes the intent better :)

Body:
GCC made me some assembly code, and inside theres this statement:

lea eax, [ebx+eax]

(Intel Syntax)
Just curious, what would the difference between that, and:

add eax, ebx

Be?

eax, and ebx contains return values from functions :)

mov eax, DWORD PTR [ebp+8]
mov DWORD PTR [esp], eax
call CALC1
mov ebx, eax.
mov eax, DWORD PTR [ebp+8]
mov DWORD PTR [esp], eax
call CALC2
lea eax, [ebx+eax]


问:
Explicitly choose which template overload should be used
Can we chose which function template overload should be used in this case?

```<code>struct X { };

struct A { A(X){} };
struct B { B(X){} };

template<class T>
void fun(T, A) { }

template<class T>
void fun(T, B) { }

int main() {
    /* explicitly choose overload */ fun(1, X());
}
</code>```

Error:

```<code>error: call of overloaded 'fun(int, X)' is ambiguous
     /* explicitly choose overload */ fun(1, X());
                                                ^
    candidate: void fun(T, A) [with T = int]
 void fun(T, A) { }
      ^~~
    candidate: void fun(T, B) [with T = int]
 void fun(T, B) { }
      ^~~
</code>```

For normal function it looks like this:

```<code>void fun(A){}
void fun(B){}

int main() {
    ((void(*)(A))(fun))(X());
}
</code>```

Is it possible?

答:
If you choose not to explicitly specify the first parameter type but still want to specify the second you could go along with lambda dedicated for casting purpose (c++14 solution):

```<code>struct X { };

struct A { A(X){} };
struct B { B(X){} };

template<class T>
void fun(T, A) { }

template<class T>
void fun(T, B) { }

int main() {
    [](auto v, auto x){ static_cast<void(*)(decltype(v), A)>(fun)(v, x); }(1, X());
}
</code>```

[live demo]

Body:
Can we chose which function template overload should be used in this case?

struct X { };

struct A { A(X){} };
struct B { B(X){} };

template<class T>
void fun(T, A) { }

template<class T>
void fun(T, B) { }

int main() {
    /* explicitly choose overload */ fun(1, X());
}

Error:

error: call of overloaded 'fun(int, X)' is ambiguous
     /* explicitly choose overload */ fun(1, X());
                                                ^
    candidate: void fun(T, A) [with T = int]
 void fun(T, A) { }
      ^~~
    candidate: void fun(T, B) [with T = int]
 void fun(T, B) { }
      ^~~

For normal function it looks like this:

void fun(A){}
void fun(B){}

int main() {
    ((void(*)(A))(fun))(X());
}

Is it possible?

Body:
If you choose not to explicitly specify the first parameter type but still want to specify the second you could go along with lambda dedicated for casting purpose (c++14 solution):

struct X { };

struct A { A(X){} };
struct B { B(X){} };

template<class T>
void fun(T, A) { }

template<class T>
void fun(T, B) { }

int main() {
    [](auto v, auto x){ static_cast<void(*)(decltype(v), A)>(fun)(v, x); }(1, X());
}

[live demo]


问:
Confusion about flatMapLatest in RxSwift
I learn the sample code in RxSwift. In the file GithubSignupViewModel1.swift, the definition of validatedUsername is:

```<code>validatedUsername = input.username //the username is a textfiled.rx_text
    .flatMapLatest { username -> Observable<ValidationResult> in
        print("-------->1:")
        return validationService.validateUsername(username)
            .observeOn(MainScheduler.instance)
            .catchErrorJustReturn(.Failed(message: "Error contacting server"))
    }
    .shareReplay(1)
</code>```

the validateUsername method is finally called the following method:

```<code>func usernameAvailable(username: String) -> Observable<Bool> {
    // this is ofc just mock, but good enough
    print("-------->2:")
    let URL = NSURL(string: "https://github.com/\(username.URLEscaped)")!
    let request = NSURLRequest(URL: URL)
    return self.URLSession.rx_response(request)
        .map { (maybeData, response) in
            print("-------->3:")
            return response.statusCode == 404
        }
        .catchErrorJustReturn(false)
}
</code>```

Here is my confusion:

whenever I input a character quickly in the username textfield, message -------->1:, -------->2: showed, and a little later message -------->3: showed, but only showed one -------->3: message.

When I input characters slower, message -------->1:, -------->2:, -------->3: showed successively.

But when I change the flatMapLatest to flatMap, how many characters I input, I will get the same number of -------->3: message.

So how did the flatMapLatest work here?

How the flatMapLatest filter the early response from NSURLResponse ?

I read some about the flatMapLatest, but none of them will explain my confusion.

What I saw is something like:

```<code>let a = Variable(XX)
a.asObservable().flatMapLatest(...)
</code>```

When changed a.value to another Variable, the Variable(XX) will not influence the subscriber of a.

But the input.username isn't changed, it is always a testfield.rx_text! So how the flatMapLatest work?

答:
I find this https://github.com/ReactiveX/RxSwift/blob/master/Rx.playground/Pages/Transforming_Operators.xcplaygroundpage/Contents.swift to be useful

Transforms the elements emitted by an Observable sequence into Observable sequences, and merges the emissions from both Observable sequences into a single Observable sequence. This is also useful when, for example, when you have an Observable sequence that itself emits Observable sequences, and you want to be able to react to new emissions from either Observable sequence. The difference between flatMap and flatMapLatest is, flatMapLatest will only emit elements from the most recent inner Observable sequence.

```<code>    let disposeBag = DisposeBag()

    struct Player {
        var score: Variable<Int>
    }

    let  = Player(score: Variable(80))
    let  = Player(score: Variable(90))

    let player = Variable()

    player.asObservable()
        .flatMap { $0.score.asObservable() } // Change flatMap to flatMapLatest and observe change in printed output
        .subscribe(onNext: { print($0) })
        .disposed(by: disposeBag)

    .score.value = 85

    player.value =

    .score.value = 95 // Will be printed when using flatMap, but will not be printed when using flatMapLatest

    .score.value = 100
</code>```

With flatMap, we get

```<code>80
85
90
95
100
</code>```

With flatMapLatest, we get

```<code>80
85
90
100
</code>```

In this example, using flatMap may have unintended consequences. After
  assigning  to player.value, .score will begin to emit
  elements, but the previous inner Observable sequence (.score) will
  also still emit elements. By changing flatMap to flatMapLatest, only
  the most recent inner Observable sequence (.score) will emit
  elements, i.e., setting .score.value to 95 has no effect.

flatMapLatest is actually a combination of the map and switchLatest
  operators.

Also, I find https://www.raywenderlich.com/158205/rxswift-transforming-operators this to be useful

flatMap

keeps up with each and every observable it creates, one for each element added onto the source observable

flatMapLatest

What makes flatMapLatest different is that it will automatically switch to the latest observable and unsubscribe from the the previous one.

Body:
I learn the sample code in RxSwift. In the file GithubSignupViewModel1.swift, the definition of validatedUsername is:

validatedUsername = input.username //the username is a textfiled.rx_text
    .flatMapLatest { username -> Observable<ValidationResult> in
        print("-------->1:")
        return validationService.validateUsername(username)
            .observeOn(MainScheduler.instance)
            .catchErrorJustReturn(.Failed(message: "Error contacting server"))
    }
    .shareReplay(1)

the validateUsername method is finally called the following method:

func usernameAvailable(username: String) -> Observable<Bool> {
    // this is ofc just mock, but good enough
    print("-------->2:")
    let URL = NSURL(string: "https://github.com/\(username.URLEscaped)")!
    let request = NSURLRequest(URL: URL)
    return self.URLSession.rx_response(request)
        .map { (maybeData, response) in
            print("-------->3:")
            return response.statusCode == 404
        }
        .catchErrorJustReturn(false)
}

Here is my confusion:

whenever I input a character quickly in the username textfield, message -------->1:, -------->2: showed, and a little later message -------->3: showed, but only showed one -------->3: message.

When I input characters slower, message -------->1:, -------->2:, -------->3: showed successively.

But when I change the flatMapLatest to flatMap, how many characters I input, I will get the same number of -------->3: message.

So how did the flatMapLatest work here?

How the flatMapLatest filter the early response from NSURLResponse ?

I read some about the flatMapLatest, but none of them will explain my confusion.

What I saw is something like:

let a = Variable(XX)
a.asObservable().flatMapLatest(...)

When changed a.value to another Variable, the Variable(XX) will not influence the subscriber of a.

But the input.username isn't changed, it is always a testfield.rx_text! So how the flatMapLatest work?

Body:
I find this https://github.com/ReactiveX/RxSwift/blob/master/Rx.playground/Pages/Transforming_Operators.xcplaygroundpage/Contents.swift to be useful

Transforms the elements emitted by an Observable sequence into Observable sequences, and merges the emissions from both Observable sequences into a single Observable sequence. This is also useful when, for example, when you have an Observable sequence that itself emits Observable sequences, and you want to be able to react to new emissions from either Observable sequence. The difference between flatMap and flatMapLatest is, flatMapLatest will only emit elements from the most recent inner Observable sequence.

    let disposeBag = DisposeBag()

    struct Player {
        var score: Variable<Int>
    }

    let  = Player(score: Variable(80))
    let  = Player(score: Variable(90))

    let player = Variable()

    player.asObservable()
        .flatMap { $0.score.asObservable() } // Change flatMap to flatMapLatest and observe change in printed output
        .subscribe(onNext: { print($0) })
        .disposed(by: disposeBag)

    .score.value = 85

    player.value =

    .score.value = 95 // Will be printed when using flatMap, but will not be printed when using flatMapLatest

    .score.value = 100

With flatMap, we get

80
85
90
95
100

With flatMapLatest, we get

80
85
90
100

In this example, using flatMap may have unintended consequences. After
  assigning  to player.value, .score will begin to emit
  elements, but the previous inner Observable sequence (.score) will
  also still emit elements. By changing flatMap to flatMapLatest, only
  the most recent inner Observable sequence (.score) will emit
  elements, i.e., setting .score.value to 95 has no effect.

flatMapLatest is actually a combination of the map and switchLatest
  operators.

Also, I find https://www.raywenderlich.com/158205/rxswift-transforming-operators this to be useful

flatMap

keeps up with each and every observable it creates, one for each element added onto the source observable

flatMapLatest

What makes flatMapLatest different is that it will automatically switch to the latest observable and unsubscribe from the the previous one.


问:
How to know the displayed text in UILabel?
I have an UIView containing two UILabels, in order to display a string.
The first UILabel has a fixed size, and if the string is too long and can't hold in this UILabel, I want to display the maximum characters I can in the first UILabel, and display the rest of the string in the second UILabel.

But to make this, I must know the exact part of the string displayed in the first UILabel, which is not easy because of the randomness of the string and the linebreaks.

So, is there a way to get just the text displayed in the first UILabel, without the truncated part of the string?

答:
```<code>if ([_infoMedia.description length] > 270) {
        NSRange labelLimit = [_infoMedia.description rangeOfString:@" " options:NSCaseInsensitiveSearch range:NSMakeRange(270, (_infoMedia.description.length - 270))];
        _descTop.text = [_infoMedia.description substringToIndex:labelLimit.location];
        _descBottom.text = [_infoMedia.description substringFromIndex:(labelLimit.location+1)];
} else {
            _descTop.text = _infoMedia.description;
            _descBottom.text = @"";
}
</code>```

Okay that's a late answer but maybe it could help someone. The code above is approximatively the solution I used in my app.

_descTop is my first label and _descBottom is the second label. 270 is a constant equivalent to a little less than the average maximum number of characters displayed in my first label, _descTop. I calculated it by hand, trying with many different strings, maybe there's a better way to do that but this worked not bad.

If the string I want to display (_infoMedia.description) is larger than 270 characters, I isolate the first 270 characters plus the end of the next word in the string (by searching the next space), in the case where the 270 characters limit would cut the string in the middle of a word. Then I put the first part of the string in my first label, and the second part in the second label.

If not, I only put the globality of the string in the first label.

I know that's a crappy solution, but it worked and I didn't found any better way to do that.

Body:
if ([_infoMedia.description length] > 270) {
        NSRange labelLimit = [_infoMedia.description rangeOfString:@" " options:NSCaseInsensitiveSearch range:NSMakeRange(270, (_infoMedia.description.length - 270))];
        _descTop.text = [_infoMedia.description substringToIndex:labelLimit.location];
        _descBottom.text = [_infoMedia.description substringFromIndex:(labelLimit.location+1)];
} else {
            _descTop.text = _infoMedia.description;
            _descBottom.text = @"";
}

Okay that's a late answer but maybe it could help someone. The code above is approximatively the solution I used in my app.

_descTop is my first label and _descBottom is the second label. 270 is a constant equivalent to a little less than the average maximum number of characters displayed in my first label, _descTop. I calculated it by hand, trying with many different strings, maybe there's a better way to do that but this worked not bad.

If the string I want to display (_infoMedia.description) is larger than 270 characters, I isolate the first 270 characters plus the end of the next word in the string (by searching the next space), in the case where the 270 characters limit would cut the string in the middle of a word. Then I put the first part of the string in my first label, and the second part in the second label.

If not, I only put the globality of the string in the first label.

I know that's a crappy solution, but it worked and I didn't found any better way to do that.


问:
How find a summ of days?
I have a table in SQL Server 2008 with data below:

```<code>organization , number of request, date number of request
organization1, ID1139151,         2017-03-15 13:10:01.000
organization1, ID1139152,         2017-03-15 14:31:05.000
organization2, ID1139153,         2017-03-16 10:38:08.000
organization2, ID1139154,         2017-03-16 09:26:04.000
organization2, ID1139155,         2017-03-16 18:09:15.000
organization2, ID1139156,         2017-03-16 20:14:29.000
organization3, ID1139157,         2017-03-23 11:18:18.000
</code>```

Help me to find a summ of days by every organization with help of SQL query.

Result:

```<code>organization , date number of request
organization1, 2
organization2, 4
organization3, 1
</code>```

Thank you!

```<code>CREATE TABLE Mytable (

   [organization] varchar(50) NOT NULL,

   [number of request] varchar(15) NOT NULL,

   [date_number_of_request] datetime NOT NULL,
     )

INSERT INTO Mytable

VALUES

('organization1','ID1139151','2017-03-15 13:10:01.000'),

('organization1','ID1139152','2017-03-15 14:31:05.000'),

('organization2','ID1139153','2017-03-16 10:38:08.000'),

('organization2','ID1139154','2017-03-16 09:26:04.000'),

('organization2','ID1139155','2017-03-16 18:09:15.000'),

('organization2','ID1139156','2017-03-16 20:14:29.000'),

('organization3','ID1139157','2017-03-23 11:18:18.000');
</code>```

答:
use the concept of group by in sql like below</p>

```<code>Select organization ,count([date_number_of_request]) as 'date number of request'
from Mytable group by organization order by organization
</code>```

Title: How find a summ of days?

Body:
I have a table in SQL Server 2008 with data below:

organization , number of request, date number of request
organization1, ID1139151,         2017-03-15 13:10:01.000
organization1, ID1139152,         2017-03-15 14:31:05.000
organization2, ID1139153,         2017-03-16 10:38:08.000
organization2, ID1139154,         2017-03-16 09:26:04.000
organization2, ID1139155,         2017-03-16 18:09:15.000
organization2, ID1139156,         2017-03-16 20:14:29.000
organization3, ID1139157,         2017-03-23 11:18:18.000

Help me to find a summ of days by every organization with help of SQL query.

Result:

organization , date number of request
organization1, 2
organization2, 4
organization3, 1

Thank you!

CREATE TABLE Mytable (

   [organization] varchar(50) NOT NULL,

   [number of request] varchar(15) NOT NULL,

   [date_number_of_request] datetime NOT NULL,
     )

INSERT INTO Mytable

VALUES

('organization1','ID1139151','2017-03-15 13:10:01.000'),

('organization1','ID1139152','2017-03-15 14:31:05.000'),

('organization2','ID1139153','2017-03-16 10:38:08.000'),

('organization2','ID1139154','2017-03-16 09:26:04.000'),

('organization2','ID1139155','2017-03-16 18:09:15.000'),

('organization2','ID1139156','2017-03-16 20:14:29.000'),

('organization3','ID1139157','2017-03-23 11:18:18.000');

Body:
use the concept of group by in sql like below

Select organization ,count([date_number_of_request]) as 'date number of request'
from Mytable group by organization order by organization


问:
Setting up Spring boot application on Vagrant behind Nginx proxy
I have a Spring boot application running on embedded Tomcat running on Vagrant CentOS box. It running on port 8080, so I can access application in web browser.
I need to set up Nginx proxy server that listen to port 80 and redirect it to my application.

I'm getting this error it the Nginx log:

[crit] 2370#0: *14 connect() to 10.0.15.21:8080 failed (13: Permission
  denied) while connecting to upstream, client: 10.0.15.1, server: ,
  request: "GET / HTTP/1.1", upstream: "http://10.0.15.21:8080/", host:
  "10.0.15.21"

All the set up examples looks pretty much similar and the only answer I could find that might help was this one. However it doesn't change anything.

Here is my server config located in /etc/nginx/conf.d/reverseproxy.conf

```<code>server {
    listen 80;
    location / {
        proxy_pass http://10.0.15.21:8080;
        proxy_set_header  X-Forwarded-Host $host;
        proxy_set_header  X-Forwarded-Server $host;
        proxy_set_header  X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}
</code>```

And here is my nginx.conf file'

```<code>user root;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

include /usr/share/nginx/modules/*.conf;

events {
    worker_connections 1024;
}

http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile            on;
    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 2048;

    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;

    include /etc/nginx/conf.d/*.conf;

}
</code>```

Don't know if this is related, but under journalctl -u nginx I can see this log.

systemd1: Failed to read PID from file /run/nginx.pid: Invalid
  argument

答:
centos has SELinux enabled by default.

You would need to turn if off by running

```<code>setsebool httpd_can_network_connect on
</code>```

There are some information about this on internet if you want to learn more. to make it persistent you can run

```<code>setsebool -P httpd_can_network_connect on
</code>```

Body:
I have a Spring boot application running on embedded Tomcat running on Vagrant CentOS box. It running on port 8080, so I can access application in web browser.
I need to set up Nginx proxy server that listen to port 80 and redirect it to my application.

I'm getting this error it the Nginx log:

[crit] 2370#0: *14 connect() to 10.0.15.21:8080 failed (13: Permission
  denied) while connecting to upstream, client: 10.0.15.1, server: ,
  request: "GET / HTTP/1.1", upstream: "http://10.0.15.21:8080/", host:
  "10.0.15.21"

All the set up examples looks pretty much similar and the only answer I could find that might help was this one. However it doesn't change anything.

Here is my server config located in /etc/nginx/conf.d/reverseproxy.conf

server {
    listen 80;
    location / {
        proxy_pass http://10.0.15.21:8080;
        proxy_set_header  X-Forwarded-Host $host;
        proxy_set_header  X-Forwarded-Server $host;
        proxy_set_header  X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}

And here is my nginx.conf file'

user root;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

include /usr/share/nginx/modules/*.conf;

events {
    worker_connections 1024;
}

http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile            on;
    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 2048;

    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;

    include /etc/nginx/conf.d/*.conf;

}

Don't know if this is related, but under journalctl -u nginx I can see this log.

systemd1: Failed to read PID from file /run/nginx.pid: Invalid
  argument

Body:
centos has SELinux enabled by default.

You would need to turn if off by running

setsebool httpd_can_network_connect on

There are some information about this on internet if you want to learn more. to make it persistent you can run

setsebool -P httpd_can_network_connect on


问:
How to add field in registration form?
In my Prestashop I need not add some field in registration form. I tried in authentication.tpl and registration.tpl but not find any hint to add new
 field.

答:
You can only change the address fields (they appear on registration if you choose the standard registration in Preferences->Customers).
To do this, you need to edit the countries required field:

You can also set some fields in the customers menu, at the bottom (if you have b2b enable it will show other fields)

To add different fields, you need a module or to edit a lot of files to display and save the fields.

NOTE: these screenshots are from 1.6 but 1.7 country address are identical.

EDIT:
Based on your screenshot, you don't have the standard registration option. Not sure it's available in 1.7. Anyway, the phone number field, in Prestashop is related to the addres, and not the customer. It would be easy to remove the other fields, but to add the phone number for the customer and not the address would be a little more tricky and would involve either create an address for that customer, or alter the customer table, class and forms.

One suggestion I can make is to translate the Company field to Phone number, and make it not optional. That would solve one problem.

Title: How to add field in registration form?


问:
I am getting an error message saying that the static field "CELL_TYPE_***" should be accessed in a static way
I am getting an error message when I hover over the 'CELL_TYPE_****' methods in the method getCellData(), saying that 'the static field "CELL_TYPE_***" should be accessed in a static way' and a strike line over them.

        package excelSelenium;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

public class seleniumIntg {
 XSSFWorkbook workbook = null;
 XSSFSheet sheet = null;
 XSSFRow Row = null;
 XSSFCell Cell = null;
 WebDriver driver = null;

 @Test(dataProvider = "getData")
 public void doLogin(String username, String password)
 {
  System.setProperty("webdriver.chrome.driver","C://testing/chromedriver_win32/chromedriver.exe" );
  driver = new ChromeDriver();

  driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
  driver.get("https://login.yahoo.com/config/login?.src=fpctx&.intl=in&.lang=en-IN&.done=https://in.yahoo.com/%3fp=us");
  driver.findElement(By.xpath("//input[@id='login-username']")).sendKeys(username);
  driver.findElement(By.xpath("//div[@class='mbr-login-submit']/button")).click();
  driver.findElement(By.xpath("//input[@id='login-passwd']")).sendKeys(password);

 }
 @DataProvider
 public Object[][] getData() throws IOException
 {
  FileInputStream fis = new FileInputStream("C://Users/Gaurav/Documents/testid.xlsx");
  workbook = new XSSFWorkbook(fis);
  sheet = workbook.getSheet("sheet1");
  int rowCount = sheet.getFirstRowNum()+sheet.getLastRowNum()+1;
  int colCount = sheet.getRow(0).getLastCellNum();
  System.out.println("Row count is:" +rowCount+ "Col count is:" +colCount);
  Object[][] data = new Object[rowCount-1][colCount];
  for(int rNum = 2; rNum<=rowCount; rNum++)
   for(int cNum = 0; cNum<colCount; cNum++)
   {
    System.out.println(getCellData("sheet1",cNum,rNum));
    data[rNum-2][cNum]=getCellData("sheet1",cNum,rNum);

   }
  return data;

 }

 public String getCellData(String sheetName, int colNum, int rowNum)
 {
  try{
  if(rowNum<=0)
   return "";
  int index = workbook.getSheetIndex(sheetName);
  if(index == -1)
   return "";
  sheet =workbook.getSheetAt(index);
  Row = sheet.getRow(rowNum-1);
  if(Row==null)
   return "";
  Cell = Row.getCell(colNum);
  if(Cell==null)
   return "";
  else if(Cell.getCellType()==Cell.CELL_TYPE_STRING)
   return Cell.getStringCellValue();

  else if(Cell.getCellType()==Cell.CELL_TYPE_NUMERIC||Cell.getCellType()==Cell.CELL_TYPE_FORMULA)
   {String CellText = String.valueOf(Cell.getNumericCellValue());
  return CellText;}
  else if(Cell.getCellType()==Cell.CELL_TYPE_BLANK)
   return "";
  else return String.valueOf(Cell.getBooleanCellValue());
 }
  catch(Exception e)
  {
   e.printStackTrace();
   return "row"+rowNum+"col"+colNum+"Does not exist";
  }

 }

  // TODO Auto-generated method stub

}```

答:
In instructions such as :

```<code>else if(Cell.getCellType()==Cell.CELL_TYPE_STRING)
</code>```

despite appearances, Cell is an instance and not a class as you declare this field in your class:

```<code>XSSFCell Cell = null;
</code>```

But static fields and methods have no need to be prefixed by an instance to call them but by the class.

So you should prefix the static fields you are referencing like that :

```<code>else if(Cell.getCellType()==XSSFCell.CELL_TYPE_STRING)
</code>```

To avoid this kind of misleading code that gives the impression that you are using as prefix an instance while you are using actually a class, follow the Java code conventions that say among other things that variable names should start by a lowercase character.

This is better :

```<code>XSSFCell cell = null;
...
else if(cell.getCellType() == XSSFCell.CELL_TYPE_STRING)
</code>```

As a side note, the CELL_TYPE_STRING static field is deprecated since POI 3.15 beta 3.

You are advised to use the enum org.apache.poi.ss.usermodel.CellType.STRING instead of.

Body:
In instructions such as :

else if(Cell.getCellType()==Cell.CELL_TYPE_STRING)

despite appearances, Cell is an instance and not a class as you declare this field in your class:

XSSFCell Cell = null;

But static fields and methods have no need to be prefixed by an instance to call them but by the class.

So you should prefix the static fields you are referencing like that :

else if(Cell.getCellType()==XSSFCell.CELL_TYPE_STRING)

To avoid this kind of misleading code that gives the impression that you are using as prefix an instance while you are using actually a class, follow the Java code conventions that say among other things that variable names should start by a lowercase character.

This is better :

XSSFCell cell = null;
...
else if(cell.getCellType() == XSSFCell.CELL_TYPE_STRING)

As a side note, the CELL_TYPE_STRING static field is deprecated since POI 3.15 beta 3.

You are advised to use the enum org.apache.poi.ss.usermodel.CellType.STRING instead of.


问:
vim create new file and insert text on first line
I have the following function which opens a new file in vim but I want to insert a line of text into the first line of the new file.

```<code>function journ(){
  datestring=`date +"%Y-%m-%d - %H%M%S - Rx2_Px -"`
  notev $datestring Journal
}
</code>```

notev calls this function:

```<code>function notev() {
    vim "$*.md"
}
</code>```

I want the first line of the file to read:

# name_of_file

答:
You can use the + flag to execute arbitrary Ex commands:

```<code>function notev() {
    vim "$*.md" +normal\ i"# $*.md"
}
</code>```

Body:
I have the following function which opens a new file in vim but I want to insert a line of text into the first line of the new file.

function journ(){
  datestring=`date +"%Y-%m-%d - %H%M%S - Rx2_Px -"`
  notev $datestring Journal
}

notev calls this function:

function notev() {
    vim "$*.md"
}

I want the first line of the file to read:

# name_of_file

Body:
You can use the + flag to execute arbitrary Ex commands:

function notev() {
    vim "$*.md" +normal\ i"# $*.md"
}


问:
Align multi-line toggling radio buttons group in bootstrap 4
I am trying to divide 4 radio buttons into two lines using bootstrap 4 alpha6, but I can't:

```<code><div id="payment-table" class="row">
    <div class="col-12">
        <div class="btn-group" data-toggle="buttons">
            <label class="btn btn-primary active">
                <input type="radio" name="paymentMethod" data-id="1" checked autocomplete="off">
                <img src="imgs/cash.png">
            </label>
            <label class="btn btn-primary">
                <input type="radio" name="paymentMethod" data-id="2" autocomplete="off">
                <img src="imgs/visa.png">
            </label>
            <label class="btn btn-primary">
                <input type="radio" name="paymentMethod" data-id="3" autocomplete="off">
                <img src="imgs/split.png" id="split">
            </label>
            <label class="btn btn-primary">
                 <input type="radio" name="paymentMethod" data-id="4" autocomplete="off">
                 <img src="imgs/master.png">
            </label>
        </div>
    </div>
</div>
</code>```

Here's what I get:

I tried to remove "btn-group" class, and I get:

And I can't align them to fit full width, as I want two radio buttons per line, and each line has full width with 50% for each radio button.

I tried to give each one "col-6", and here's what I get:

Any suggestion?

答:
actually we need to use only col class. by nesting we determine how many columns will be there.

Try this

.btn-primary {
  width: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
<div id="payment-table" class="row">
  <div class="col">
    <div class="" data-toggle="buttons">
      <div class="row">

        <div class="col">
          <label class="btn btn-primary active col">
                <input type="radio" name="paymentMethod" data-id="1" checked autocomplete="off">
                <img src="imgs/cash.png">
            </label>
        </div>
        <div class="col">
          <label class="btn btn-primary col">
                <input type="radio" name="paymentMethod" data-id="2" autocomplete="off">
                <img src="imgs/visa.png">
            </label>
        </div>
      </div>
    </div>
    <div class="row">

      <div class="col">
        <label class="btn btn-primary col">
                <input type="radio" name="paymentMethod" data-id="3" autocomplete="off">
                <img src="imgs/split.png" id="split">
            </label>
      </div>
      <div class="col">
        <label class="btn btn-primary col">
                 <input type="radio" name="paymentMethod" data-id="4" autocomplete="off">
                 <img src="imgs/master.png">
            </label>
      </div>
    </div>
  </div>
</div></code>```

Hope this helps!

Body:
I am trying to divide 4 radio buttons into two lines using bootstrap 4 alpha6, but I can't:

                <input type="radio" name="paymentMethod" data-id="1" checked autocomplete="off">

                <input type="radio" name="paymentMethod" data-id="2" autocomplete="off">

                <input type="radio" name="paymentMethod" data-id="3" autocomplete="off">

                 <input type="radio" name="paymentMethod" data-id="4" autocomplete="off">

Here's what I get:

I tried to remove "btn-group" class, and I get:

And I can't align them to fit full width, as I want two radio buttons per line, and each line has full width with 50% for each radio button.

I tried to give each one "col-6", and here's what I get:

Any suggestion?

Body:
actually we need to use only col class. by nesting we determine how many columns will be there.

Try this

.btn-primary {
  width: 100%;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
<div id="payment-table" class="row">
  <div class="col">
    <div class="" data-toggle="buttons">
      <div class="row">

        <div class="col">
          <label class="btn btn-primary active col">
                <input type="radio" name="paymentMethod" data-id="1" checked autocomplete="off">
                <img src="imgs/cash.png">
            </label>
        </div>
        <div class="col">
          <label class="btn btn-primary col">
                <input type="radio" name="paymentMethod" data-id="2" autocomplete="off">
                <img src="imgs/visa.png">
            </label>
        </div>
      </div>
    </div>
    <div class="row">

      <div class="col">
        <label class="btn btn-primary col">
                <input type="radio" name="paymentMethod" data-id="3" autocomplete="off">
                <img src="imgs/split.png" id="split">
            </label>
      </div>
      <div class="col">
        <label class="btn btn-primary col">
                 <input type="radio" name="paymentMethod" data-id="4" autocomplete="off">
                 <img src="imgs/master.png">
            </label>
      </div>
    </div>
  </div>
</div>

Hope this helps!


问:
What's the difference between function and function() in C#?
For example,
    Thread t = new Thread(function);
Why not
    Thread t = new Thread(function());
Thank you.

答:
This line

```<code>Thread t = new Thread(function);
</code>```

is a short version of this line:

```<code>Thread t = new Thread(new ThreadStart(function));
</code>```

It constructs a delegate ThreadStart from a method name using Method Group Syntax introduced in C# 2.

On the other hand, this line

```<code>Thread t = new Thread(function());
</code>```

creates a thread using a delegate returned by the function method. Of course function must return ThreadStart delegate in order for the above to compile.

Body:
This line

Thread t = new Thread(function);

is a short version of this line:

Thread t = new Thread(new ThreadStart(function));

It constructs a delegate ThreadStart from a method name using Method Group Syntax introduced in C# 2.

On the other hand, this line

Thread t = new Thread(function());

creates a thread using a delegate returned by the function method. Of course function must return ThreadStart delegate in order for the above to compile.


问:
Why won't kubernetes v1.5 recognize service.spec.loadBalancerIp?
I'm running kubernetes v1.5 (api reference here). The field service.spec.loadBalancerIp should exist but I keep getting the following error when I attempt to set it.

error: error validating ".../service.yaml": error validating data: found invalid field loadBalancerIp for v1.ServiceSpec; if you choose to ignore these errors, turn validation off with --validate=false

service.yaml:

```<code>kind: Service
apiVersion: v1
metadata:
  name: some-service
spec:
  type: LoadBalancer
  loadBalancerIp: xx.xx.xx.xx
  selector:
    deployment: some-deployment
  ports:
    - protocol: TCP
      port: 80
</code>```

kubectl version output:

```<code>Client Version: version.Info{Major:"1", Minor:"5", GitVersion:"v1.5.4", GitCommit:"7243c69eb523aa4377bce883e7c0dd76b84709a1", GitTreeState:"clean", BuildDate:"2017-03-07T23:53:09Z", GoVersion:"go1.7.4", Compiler:"gc", Platform:"darwin/amd64"}
Server Version: version.Info{Major:"1", Minor:"5", GitVersion:"v1.5.4", GitCommit:"7243c69eb523aa4377bce883e7c0dd76b84709a1", GitTreeState:"clean", BuildDate:"2017-03-07T23:34:32Z", GoVersion:"go1.7.4", Compiler:"gc", Platform:"linux/amd64"}
</code>```

I'm running my cluster on gke.

Any thoughts?

答: You have a typo in your spec. It should be loadBalancerIP, not loadBalancerIp. Note the uppercase P

Body:
I'm running kubernetes v1.5 (api reference here). The field service.spec.loadBalancerIp should exist but I keep getting the following error when I attempt to set it.

error: error validating ".../service.yaml": error validating data: found invalid field loadBalancerIp for v1.ServiceSpec; if you choose to ignore these errors, turn validation off with --validate=false

service.yaml:

kind: Service
apiVersion: v1
metadata:
  name: some-service
spec:
  type: LoadBalancer
  loadBalancerIp: xx.xx.xx.xx
  selector:
    deployment: some-deployment
  ports:
    - protocol: TCP
      port: 80

kubectl version output:

Client Version: version.Info{Major:"1", Minor:"5", GitVersion:"v1.5.4", GitCommit:"7243c69eb523aa4377bce883e7c0dd76b84709a1", GitTreeState:"clean", BuildDate:"2017-03-07T23:53:09Z", GoVersion:"go1.7.4", Compiler:"gc", Platform:"darwin/amd64"}
Server Version: version.Info{Major:"1", Minor:"5", GitVersion:"v1.5.4", GitCommit:"7243c69eb523aa4377bce883e7c0dd76b84709a1", GitTreeState:"clean", BuildDate:"2017-03-07T23:34:32Z", GoVersion:"go1.7.4", Compiler:"gc", Platform:"linux/amd64"}

I'm running my cluster on gke.

Any thoughts?


问:
'Field required a bean of type that could not be found.' error spring restful API using mongodb
So I've been learning Spring in the couples of week, been following this tutorial

Building a RESTful Web Service

All was well until I tried to integrate it to mongodb. So I follow this tutorial.

Accessing Data with MongoDB

But my practice is partially still using the first one. So my project directory structure is like this.

```<code>src/
├── main/
│   └── java/
|       ├── model/
|       |   └── User.java
|       ├── rest/
|       |   ├── Application.java
|       |   ├── IndexController.java
|       |   └── UsersController.java
|       └── service/
|           └── UserService.java
└── resources/
    └── application.properties
</code>```

This is my model/User.java file

package main.java.model;

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

@Document(collection="user")
public class User {

    private int age;
    private String country;
    @Id
    private String id;
    private String name;

    public User() {
        super();
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }
}
```

<p>This is my <strong>rest/UsersController.java</strong> file</p>

<pre class="lang-java prettyprint-override"><code>package main.java.rest;

import java.util.List;
import main.java.service.UserService;
import main.java.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping(value = "/users")
public class UsersController {

    @Autowired
    UserService userService;

    @RequestMapping(method = RequestMethod.GET)
    public List<User> getAllUsers() {
        return userService.findAll();
    }
}
</code>```

This is my service/UserService.java file

package main.java.service;

import java.util.List;
import main.java.model.User;
import org.springframework.data.mongodb.repository.MongoRepository;

public interface UserService extends MongoRepository<User, String> {
    public List<User> findAll();
}
```

I could compile them (I'm using gradle for compilation because I'm following the tutorial), but when I run the jar file it was throwing this error.

APPLICATION FAILED TO START

Description:

Field userService in main.java.rest.UsersController required a bean of
  type 'main.java.service.UserService' that could not be found.

Action:

Consider defining a bean of type 'main.java.service.UserService' in
  your configuration.

Not sure what is wrong I start googling around and found that I need to include Beans.xml file and register the userService in it. I did that but it's not working. I'm really new to this so I really have no clue on what's going on.

答:
Solved it. So by default, all packages that falls under @SpringBootApplication declaration will be scanned.

Assuming my main class ExampleApplication that has @SpringBootApplication declaration is declared inside com.example.something, then all components that falls under com.example.something is scanned while com.example.applicant will not be scanned.

So, there are two ways to do it based on this question. Use

```<code>@SpringBootApplication(scanBasePackages={
"com.example.something", "com.example.application"})
</code>```

That way, the application will scan all the specified components, but I think what if the scale were getting bigger ?

So I use the second approach, by restructuring my packages and it worked ! Now my packages structure became like this.

```<code>src/
├── main/
│   └── java/
|       ├── com.example/
|       |   └── Application.java
|       ├── com.example.model/
|       |   └── User.java
|       ├── com.example.controller/
|       |   ├── IndexController.java
|       |   └── UsersController.java
|       └── com.example.service/
|           └── UserService.java
└── resources/
    └── application.properties
</code>```

Body:
So I've been learning Spring in the couples of week, been following this tutorial

Building a RESTful Web Service

All was well until I tried to integrate it to mongodb. So I follow this tutorial.

Accessing Data with MongoDB

But my practice is partially still using the first one. So my project directory structure is like this.

src/
├── main/
│   └── java/
|       ├── model/
|       |   └── User.java
|       ├── rest/
|       |   ├── Application.java
|       |   ├── IndexController.java
|       |   └── UsersController.java
|       └── service/
|           └── UserService.java
└── resources/
    └── application.properties

This is my model/User.java file

package main.java.model;

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

@Document(collection="user")
public class User {

    private int age;
    private String country;
    @Id
    private String id;
    private String name;

    public User() {
        super();
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }
}

This is my rest/UsersController.java file

package main.java.rest;

import java.util.List;
import main.java.service.UserService;
import main.java.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping(value = "/users")
public class UsersController {

    @Autowired
    UserService userService;

    @RequestMapping(method = RequestMethod.GET)
    public List<User> getAllUsers() {
        return userService.findAll();
    }
}

This is my service/UserService.java file

package main.java.service;

import java.util.List;
import main.java.model.User;
import org.springframework.data.mongodb.repository.MongoRepository;

public interface UserService extends MongoRepository<User, String> {
    public List<User> findAll();
}

I could compile them (I'm using gradle for compilation because I'm following the tutorial), but when I run the jar file it was throwing this error.

APPLICATION FAILED TO START

Description:

Field userService in main.java.rest.UsersController required a bean of
  type 'main.java.service.UserService' that could not be found.

Action:

Consider defining a bean of type 'main.java.service.UserService' in
  your configuration.

Not sure what is wrong I start googling around and found that I need to include Beans.xml file and register the userService in it. I did that but it's not working. I'm really new to this so I really have no clue on what's going on.

Body:
Solved it. So by default, all packages that falls under @SpringBootApplication declaration will be scanned.

Assuming my main class ExampleApplication that has @SpringBootApplication declaration is declared inside com.example.something, then all components that falls under com.example.something is scanned while com.example.applicant will not be scanned.

So, there are two ways to do it based on this question. Use

@SpringBootApplication(scanBasePackages={
"com.example.something", "com.example.application"})

That way, the application will scan all the specified components, but I think what if the scale were getting bigger ?

So I use the second approach, by restructuring my packages and it worked ! Now my packages structure became like this.

src/
├── main/
│   └── java/
|       ├── com.example/
|       |   └── Application.java
|       ├── com.example.model/
|       |   └── User.java
|       ├── com.example.controller/
|       |   ├── IndexController.java
|       |   └── UsersController.java
|       └── com.example.service/
|           └── UserService.java
└── resources/
    └── application.properties


问:
sql query needs input from another table
I have a database where i want the data from two tables, they look something like this:

```<code>categories:    entries:
+----+------+  +----+-------------+-------+-------------+
| id | name |  | ID | category_id | title | description |
+----+------+  +----+-------------+-------+-------------+
|  1 |  foo |  |  1 |      1      |  bar  | Loreum ip.. |
+----+------+  +----+-------------+-------+-------------+
</code>```

I want to get info from entries, and my input will just be category name and entry title. It does obviously work if i use two statements. something like:

```<code>SELECT `id` FROM `categories` WHERE `name` = 'foo' LIMIT 1;
SELECT `ID`, `category_id`, `title`, `description` FROM `entries` WHERE `title` = 'bar' AND `category_id` = $cat_id LIMIT 1;
</code>```

Where $cat_id is the output from the first entry. But i want to combine these to into one statement, and i don't find join useful here? So my question is basically how can i combine these into one query?

答:
May be the only way is to use subquery. though I don't way it is a good way.</p>

```<code>    SELECT `ID`, `category_id`, `title`, `description` FROM `entries` WHERE `title` = 'bar'
AND `category_id` = (SELECT `id` FROM `categories` WHERE `name` = 'foo' LIMIT 1) LIMIT 1;
</code>```

Body:
I have a database where i want the data from two tables, they look something like this:

categories:    entries:
+----+------+  +----+-------------+-------+-------------+
| id | name |  | ID | category_id | title | description |
+----+------+  +----+-------------+-------+-------------+
|  1 |  foo |  |  1 |      1      |  bar  | Loreum ip.. |
+----+------+  +----+-------------+-------+-------------+

I want to get info from entries, and my input will just be category name and entry title. It does obviously work if i use two statements. something like:

SELECT `id` FROM `categories` WHERE `name` = 'foo' LIMIT 1;
SELECT `ID`, `category_id`, `title`, `description` FROM `entries` WHERE `title` = 'bar' AND `category_id` = $cat_id LIMIT 1;

Where $cat_id is the output from the first entry. But i want to combine these to into one statement, and i don't find join useful here? So my question is basically how can i combine these into one query?

Body:
May be the only way is to use subquery. though I don't way it is a good way.

    SELECT `ID`, `category_id`, `title`, `description` FROM `entries` WHERE `title` = 'bar'
AND `category_id` = (SELECT `id` FROM `categories` WHERE `name` = 'foo' LIMIT 1) LIMIT 1;


问:
Python/NumPy first occurrence of subarray
In Python or NumPy, what is the best way to find out the first occurrence of a subarray?

For example, I have

```<code>a = [1, 2, 3, 4, 5, 6]
b = [2, 3, 4]
</code>```

What is the fastest way (run-time-wise) to find out where b occurs in a? I understand for strings this is extremely easy, but what about for a list or numpy ndarray?

Thanks a lot!

[EDITED] I prefer the numpy solution, since from my experience numpy vectorization is much faster than Python list comprehension. Meanwhile, the big array is huge, so I don't want to convert it into a string; that will be (too) long.

答:
Here is a rather straight-forward option:

```<code>def first_subarray(full_array, sub_array):
    n = len(full_array)
    k = len(sub_array)
    matches = np.argwhere([np.all(full_array[start_ix:start_ix+k] == sub_array)
                   for start_ix in range(0, n-k+1)])
    return matches[0]
</code>```

Then using the original a, b vectors we get:

```<code>a = [1, 2, 3, 4, 5, 6]
b = [2, 3, 4]
first_subarray(a, b)
Out[44]:
array([1], dtype=int64)
</code>```

Body:
In Python or NumPy, what is the best way to find out the first occurrence of a subarray?

For example, I have

a = [1, 2, 3, 4, 5, 6]
b = [2, 3, 4]

What is the fastest way (run-time-wise) to find out where b occurs in a? I understand for strings this is extremely easy, but what about for a list or numpy ndarray?

Thanks a lot!

[EDITED] I prefer the numpy solution, since from my experience numpy vectorization is much faster than Python list comprehension. Meanwhile, the big array is huge, so I don't want to convert it into a string; that will be (too) long.

Body:
Here is a rather straight-forward option:

def first_subarray(full_array, sub_array):
    n = len(full_array)
    k = len(sub_array)
    matches = np.argwhere([np.all(full_array[start_ix:start_ix+k] == sub_array)
                   for start_ix in range(0, n-k+1)])
    return matches[0]

Then using the original a, b vectors we get:

a = [1, 2, 3, 4, 5, 6]
b = [2, 3, 4]
first_subarray(a, b)
Out[44]:
array([1], dtype=int64)


问:
What does VS 2008's "Convert to Website" mean?
I have upgraded a MS Visual Studio Application from VS 2003 to VS 2008 (Targeting .NET 2.0). As part of the conversion process the wizard said I needed to take the additional step of Converting my Project to a Website by Right-Clicking and blah blah blah...

I didn't follow directions and the web application seems to be working fine.

My question is, should I be concerned about pushing this to a production system? What exactly is going on here?

答:
Convert to Website moves all of your control declarations from the main page class to a secondary file (yourpage.aspx.designer.cs).

Why would I want to do this? It's bad enough that there is a .js .css .vb .aspx file for each page. Do I really need to split up the .vb into two more files just so I can hide the declarations ? page.designer.aspx.vb.h anyone?

LastEditorDisplayName: hop


问:
Learn C# on mac?
Is mono the only route , any specific visual studio like editors that you recommend?</p>

答:
Well, you could also try Silverlight...

Pro:

It is an official Microsoft implementation, so it is more likely to work

Its support for recent stuff like C# 3.0 is much better

Con:

It is browser-only, Silverlight apps do not run standalone

You won't get the whole .NET Class Library, only a subset, so it is somewhat limited

You won't get Visual Studio on a Mac

For IDE, I suggest <s>Eclipse Tools for Microsoft Silverlight</s> (apparently it is Windows-only at the moment) you should use MonoDevelop or SharpDevelop or something like that.

Title: Learn C# on mac?

OwnerDisplayName: DrJokepu


问:
Font-size <12px doesn't have effect in Google Chrome
Elements with css font-size <12px doesn't have effect in Google Chrome - remains font-size 12px.

What should I do?

My Google Chrome browser uses default settings. My version is 4.0.249.89.
I am using Windows XP.

You can paste the following code to your Google Chrome to test it:

```<code><html>
<body>
<p style="font-size:6px;">test 6px</p>
<p style="font-size:7px;">test 7px</p>
<p style="font-size:8px;">test 8px</p>
<p style="font-size:9px;">test 9px</p>
<p style="font-size:10px;">test 10px</p>
<p style="font-size:11px;">test 11px</p>
<p style="font-size:12px;">test 12px</p>
<p style="font-size:13px;">test 13px</p>
<p style="font-size:14px;">test 14px</p>
<p style="font-size:15px;">test 15px</p>
<p style="font-size:16px;">test 16px</p>
</body>
</html>
</code>```

Results from different browser:

答:
disable the auto adjustment by following style.</p>

```<code>* {
    -webkit-text-size-adjust: none;
}
</code>```

Body:
Elements with css font-size <12px doesn't have effect in Google Chrome - remains font-size 12px.

What should I do?

My Google Chrome browser uses default settings. My version is 4.0.249.89.
I am using Windows XP.

You can paste the following code to your Google Chrome to test it:

test 6px

test 7px

test 8px

test 9px

test 10px

test 11px

test 12px

test 13px

test 14px

test 15px

test 16px

Results from different browser:

Body:
disable the auto adjustment by following style.

* {
    -webkit-text-size-adjust: none;
}


问:
EXC_BAD_ACCESS signal received
When deploying the application to the device, the program will quit after a few cycles with the following error:

```<code>Program received signal: "EXC_BAD_ACCESS".
</code>```

The program runs without any issue on the iPhone simulator, it will also debug and run as long as I step through the instructions one at a time. As soon as I let it run again, I will hit the EXC_BAD_ACCESS signal.

In this particular case, it happened to be an error in the accelerometer code. It would not execute within the simulator, which is why it did not throw any errors. However, it would execute once deployed to the device.

Most of the answers to this question deal with the general EXC_BAD_ACCESS error, so I will leave this open as a catch-all for the dreaded Bad Access error.

EXC_BAD_ACCESS is typically thrown as the result of an illegal memory access. You can find more information in the answers below.

Have you encountered the EXC_BAD_ACCESS signal before, and how did you deal with it?

答:
Before you do anything, you should try:

Product -> Clean

And run again. It worked for me. Otherwise, I would have wasted hours.

OwnerDisplayName: Hector Ramos

Title: EXC_BAD_ACCESS signal received

Body:
When deploying the application to the device, the program will quit after a few cycles with the following error:

Program received signal: "EXC_BAD_ACCESS".

The program runs without any issue on the iPhone simulator, it will also debug and run as long as I step through the instructions one at a time. As soon as I let it run again, I will hit the EXC_BAD_ACCESS signal.

In this particular case, it happened to be an error in the accelerometer code. It would not execute within the simulator, which is why it did not throw any errors. However, it would execute once deployed to the device.

Most of the answers to this question deal with the general EXC_BAD_ACCESS error, so I will leave this open as a catch-all for the dreaded Bad Access error.

EXC_BAD_ACCESS is typically thrown as the result of an illegal memory access. You can find more information in the answers below.

Have you encountered the EXC_BAD_ACCESS signal before, and how did you deal with it?

LastEditorDisplayName: Ned Batchelder


问:
Not seeing latest version when updating Node.js via installer (MSI) Windows 7
I'm trying to update node on my Windows 7 box but I'm not seeing the latest version after I re-install/update node.

I'm just going out to http://nodejs.org/download/ and getting the latest Windows installer, v0.10.28.  I then just run that installer where it defaults to installing everything on my local hard drive, including npm, which is cool because I wanted to upgrade that as well.

Install runs/finishes with no apparent problem, but when I do a:

```<code>node --version
</code>```

I'm still seeing my "old" version, v0.10.15, not the latest I supposedly just installed, v0.10.28. My npm version still reports my "old" version as well.

I've tried rebooting as well.

How the heck does one update node/npm?

答:
Answer given by Johan Dettmar about using n will work here as well.

For Windows : open command prompt as administrator

For Linux/Mac : sudo -s on terminal

npm cache clean -f (force) clear you npm cache

npm install -g n install "n" (this might take a while)

n stable upgrade to lastest version

Body:
I'm trying to update node on my Windows 7 box but I'm not seeing the latest version after I re-install/update node.

I'm just going out to http://nodejs.org/download/ and getting the latest Windows installer, v0.10.28.  I then just run that installer where it defaults to installing everything on my local hard drive, including npm, which is cool because I wanted to upgrade that as well.

Install runs/finishes with no apparent problem, but when I do a:

node --version

I'm still seeing my "old" version, v0.10.15, not the latest I supposedly just installed, v0.10.28. My npm version still reports my "old" version as well.

I've tried rebooting as well.

How the heck does one update node/npm?


答:
Well, first of all you should rename your variables, so that they start with lower-case letters (e.g. cell instead of Cell) to avoid confusion.

So cell is an instance of class XSSFCell which inherits from Cell.

The static fields e.g. CELL_TYPE_STRING are declared in the class Cell
: so you should use Cell.CELL_TYPE_STRING instead of cell.CELL_TYPE_STRING

Title: I am getting an error message saying that the static field "CELL_TYPE_***" should be accessed in a static way

Body:
I am getting an error message when I hover over the 'CELL_TYPE_****' methods in the method getCellData(), saying that 'the static field "CELL_TYPE_***" should be accessed in a static way' and a strike line over them.

        package excelSelenium;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

public class seleniumIntg {
 XSSFWorkbook workbook = null;
 XSSFSheet sheet = null;
 XSSFRow Row = null;
 XSSFCell Cell = null;
 WebDriver driver = null;

 @Test(dataProvider = "getData")
 public void doLogin(String username, String password)
 {
  System.setProperty("webdriver.chrome.driver","C://testing/chromedriver_win32/chromedriver.exe" );
  driver = new ChromeDriver();

  driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
  driver.get("https://login.yahoo.com/config/login?.src=fpctx&.intl=in&.lang=en-IN&.done=https://in.yahoo.com/%3fp=us");
  driver.findElement(By.xpath("//input[@id='login-username']")).sendKeys(username);
  driver.findElement(By.xpath("//div[@class='mbr-login-submit']/button")).click();
  driver.findElement(By.xpath("//input[@id='login-passwd']")).sendKeys(password);

 }
 @DataProvider
 public Object[][] getData() throws IOException
 {
  FileInputStream fis = new FileInputStream("C://Users/Gaurav/Documents/testid.xlsx");
  workbook = new XSSFWorkbook(fis);
  sheet = workbook.getSheet("sheet1");
  int rowCount = sheet.getFirstRowNum()+sheet.getLastRowNum()+1;
  int colCount = sheet.getRow(0).getLastCellNum();
  System.out.println("Row count is:" +rowCount+ "Col count is:" +colCount);
  Object[][] data = new Object[rowCount-1][colCount];
  for(int rNum = 2; rNum<=rowCount; rNum++)
   for(int cNum = 0; cNum<colCount; cNum++)
   {
    System.out.println(getCellData("sheet1",cNum,rNum));
    data[rNum-2][cNum]=getCellData("sheet1",cNum,rNum);

   }
  return data;

 }

 public String getCellData(String sheetName, int colNum, int rowNum)
 {
  try{
  if(rowNum<=0)
   return "";
  int index = workbook.getSheetIndex(sheetName);
  if(index == -1)
   return "";
  sheet =workbook.getSheetAt(index);
  Row = sheet.getRow(rowNum-1);
  if(Row==null)
   return "";
  Cell = Row.getCell(colNum);
  if(Cell==null)
   return "";
  else if(Cell.getCellType()==Cell.CELL_TYPE_STRING)
   return Cell.getStringCellValue();

  else if(Cell.getCellType()==Cell.CELL_TYPE_NUMERIC||Cell.getCellType()==Cell.CELL_TYPE_FORMULA)
   {String CellText = String.valueOf(Cell.getNumericCellValue());
  return CellText;}
  else if(Cell.getCellType()==Cell.CELL_TYPE_BLANK)
   return "";
  else return String.valueOf(Cell.getBooleanCellValue());
 }
  catch(Exception e)
  {
   e.printStackTrace();
   return "row"+rowNum+"col"+colNum+"Does not exist";
  }

 }

  // TODO Auto-generated method stub

}


问:
Share credentials between native app and web site
An application I'm working on allows users to log into an OAuth-enabled backend. The application is therefore privy only to the authentication tokens and user metadata, not to the user's credentials.

Within the application, users can hit links that open up links in a browser. These resources are also protected by OAuth, and the token obtained during login to the native app is also relevant to the web.

I would like the user's credentials to flow from the native app to the web browser in the standard OAuth manner (by including it as an Authorization header).

It seems that Android facilitates this through its shared credentials feature, but I cannot find an equivalent for iOS. I did find the shared web credentials feature, but that seems to require knowledge of the user's credentials.

How can I flow OAuth tokens from my native app through to web browsers that it opens?

答:
Associated Domains and Shared Web Credentials don't seem to be a good approach here.

You have two options:

Passing the OAuth Access Token as URL-QueryString-Param to the
WebBrowser. https://x.y.z/?access_token=abc You'll have to manipulate the embedded URLs and assure that your backend understands this.
Very common and easy approach. Many websites like Facebook and
Google are passing Access Tokens in the URL.

If you're using In-App-Browsers (UIWebView, WKWebView), you can intercept the URL-Request and add the Authorization Header on your own. See this for UIWebView and this for WKWebView (which is little bit harder than UIWebView)


问:
Java unable to read signed negative bytes written to standard out
I have 2 classes, the first is fed a binary string of 1s and 0s to standard in, and splits the string into sub strings of length 8 to convert to bytes, to write to standard out like so:

```<code>byte b = (byte)Integer.parseInt(byteString, 2);
System.out.write(b);
System.out.flush();
</code>```

The second is piped the output of the first, and ultimately will turn the bytes back into the long binary string, but currently I have it just doing this:

```<code>int next;
    while((next = System.in.read())!=-1){
    System.out.print(next); System.out.print(" ");
    System.out.flush();
}
</code>```

If I replace System.out.write(b); with System.out.print(b); System.out.print(" "); in the first class with some small sample input, the output is -80 -84 83 11 98 -116 53 -119 49 27 10 -80 -72 104 -123 0

If I pipe this output to the second class it outputs 63 63 83 11 98 63 53 63 49 27 13 10 63 63 104 63 0 13 10

Two things seem to be happening that I can't figure out why, System.in.read() is returning 63, which is ASCII for ? when reading bytes that would be signed negative, and a carriage return + new line has been added to the end. I am stumped for solutions, insight is greatly appreciated.

Note: I was running this in Windows 10 powershell, but on normal command line and in a linux terminal the behaviour was as expected, so problem is only in powershell!

答:
```<code>int next;
while((next = System.in.read())!=-1){
    System.out.print(next); System.out.print(" ");
    System.out.flush();
}
</code>```

Bytes are signed in Java, and so is the result of InputStream.read(). Try this:

```<code>int next;
DataInputStream in = new DataInputStream(System.in);
for (;;)
{
    try
    {
        next = in.readUnsignedByte();
        System.out.print(next); System.out.print(" ");
        System.out.flush();
    }
    catch (EOFException exc)
    {
        break;
    }
}
</code>```

Body:
I have 2 classes, the first is fed a binary string of 1s and 0s to standard in, and splits the string into sub strings of length 8 to convert to bytes, to write to standard out like so:

byte b = (byte)Integer.parseInt(byteString, 2);
System.out.write(b);
System.out.flush();

The second is piped the output of the first, and ultimately will turn the bytes back into the long binary string, but currently I have it just doing this:

int next;
    while((next = System.in.read())!=-1){
    System.out.print(next); System.out.print(" ");
    System.out.flush();
}

If I replace System.out.write(b); with System.out.print(b); System.out.print(" "); in the first class with some small sample input, the output is -80 -84 83 11 98 -116 53 -119 49 27 10 -80 -72 104 -123 0

If I pipe this output to the second class it outputs 63 63 83 11 98 63 53 63 49 27 13 10 63 63 104 63 0 13 10

Two things seem to be happening that I can't figure out why, System.in.read() is returning 63, which is ASCII for ? when reading bytes that would be signed negative, and a carriage return + new line has been added to the end. I am stumped for solutions, insight is greatly appreciated.

Note: I was running this in Windows 10 powershell, but on normal command line and in a linux terminal the behaviour was as expected, so problem is only in powershell!

Body:
int next;
while((next = System.in.read())!=-1){
    System.out.print(next); System.out.print(" ");
    System.out.flush();
}

Bytes are signed in Java, and so is the result of InputStream.read(). Try this:

int next;
DataInputStream in = new DataInputStream(System.in);
for (;;)
{
    try
    {
        next = in.readUnsignedByte();
        System.out.print(next); System.out.print(" ");
        System.out.flush();
    }
    catch (EOFException exc)
    {
        break;
    }
}


问:
Apply a method to a list of objects in parallel using multi-processing
I have created a class with a number of methods. One of the methods is very time consuming, my_process, and I'd like to do that method in parallel. I came across Python Multiprocessing - apply class method to a list of objects but I'm not sure how to apply it to my problem, and what effect it will have on the other methods of my class.

```<code>class MyClass():
    def __init__(self, input):
        self.input = input
        self.result = int

    def my_process(self, multiply_by, add_to):
        self.result = self.input * multiply_by
        self._my_sub_process(add_to)
        return self.result

    def _my_sub_process(self, add_to):
        self.result += add_to

list_of_numbers = range(0, 5)
list_of_objects = [MyClass(i) for i in list_of_numbers]
list_of_results = [obj.my_process(100, 1) for obj in list_of_objects] # multi-process this for-loop

print list_of_numbers
print list_of_results

[0, 1, 2, 3, 4]
[1, 101, 201, 301, 401]
</code>```

答:
If you don't absolutely need to stick with Multiprocessing module then,
it can easily achieved using concurrents.futures library

here's the example code:

```<code>from concurrent.futures.thread import ThreadPoolExecutor, wait

MAX_WORKERS = 20

class MyClass():
    def __init__(self, input):
        self.input = input
        self.result = int

    def my_process(self, multiply_by, add_to):
        self.result = self.input * multiply_by
        self._my_sub_process(add_to)
        return self.result

    def _my_sub_process(self, add_to):
        self.result += add_to

list_of_numbers = range(0, 5)
list_of_objects = [MyClass(i) for i in list_of_numbers]

With ThreadPoolExecutor(MAX_WORKERS) as executor:
    for obj in list_of_objects:
        executor.submit(obj.my_process, 100, 1).add_done_callback(on_finish)

def on_finish(future):
    result = future.result() # do stuff with your result
</code>```

here executor returns future for every task it submits. keep in mind that if you use add_done_callback() finished task from thread returns to the main thread (which would block your main thread) if you really want true parallelism then you should wait for future objects separately. here's the code snippet for that.

```<code>futures = []
with ThreadPoolExecutor(MAX_WORKERS) as executor:
    for objin list_of_objects:
        futures.append(executor.submit(obj.my_process, 100, 1))
wait(futures)

for succeded, failed in futures:
    # work with your result here
    if succeded:
       print (succeeeded.result())
    if failed:
        print (failed.result())
</code>```

hope this helps.

Body:
I have created a class with a number of methods. One of the methods is very time consuming, my_process, and I'd like to do that method in parallel. I came across Python Multiprocessing - apply class method to a list of objects but I'm not sure how to apply it to my problem, and what effect it will have on the other methods of my class.

class MyClass():
    def __init__(self, input):
        self.input = input
        self.result = int

    def my_process(self, multiply_by, add_to):
        self.result = self.input * multiply_by
        self._my_sub_process(add_to)
        return self.result

    def _my_sub_process(self, add_to):
        self.result += add_to

list_of_numbers = range(0, 5)
list_of_objects = [MyClass(i) for i in list_of_numbers]
list_of_results = [obj.my_process(100, 1) for obj in list_of_objects] # multi-process this for-loop

print list_of_numbers
print list_of_results

[0, 1, 2, 3, 4]
[1, 101, 201, 301, 401]

Body:
If you don't absolutely need to stick with Multiprocessing module then,
it can easily achieved using concurrents.futures library

here's the example code:

from concurrent.futures.thread import ThreadPoolExecutor, wait

MAX_WORKERS = 20

class MyClass():
    def __init__(self, input):
        self.input = input
        self.result = int

    def my_process(self, multiply_by, add_to):
        self.result = self.input * multiply_by
        self._my_sub_process(add_to)
        return self.result

    def _my_sub_process(self, add_to):
        self.result += add_to

list_of_numbers = range(0, 5)
list_of_objects = [MyClass(i) for i in list_of_numbers]

With ThreadPoolExecutor(MAX_WORKERS) as executor:
    for obj in list_of_objects:
        executor.submit(obj.my_process, 100, 1).add_done_callback(on_finish)

def on_finish(future):
    result = future.result() # do stuff with your result

here executor returns future for every task it submits. keep in mind that if you use add_done_callback() finished task from thread returns to the main thread (which would block your main thread) if you really want true parallelism then you should wait for future objects separately. here's the code snippet for that.

futures = []
with ThreadPoolExecutor(MAX_WORKERS) as executor:
    for objin list_of_objects:
        futures.append(executor.submit(obj.my_process, 100, 1))
wait(futures)

for succeded, failed in futures:
    # work with your result here
    if succeded:
       print (succeeeded.result())
    if failed:
        print (failed.result())

hope this helps.