问:
Cloud.orbit.exception.UncheckedException: Don't know how to handle state
What is kotlin equivalent of this java class?

```<code>public class StatefulActor extends AbstractActor<StatefulActor.State> implements Some
{
    public static class State
    {
        String lastMessage;
    }
}
</code>```

I tried:

```<code>class HelloActor: AbstractActor<HelloActor.State>(), Hello
{
    inner class State {
        var lastMessage: String? = null
    }
</code>```

but results in Cloud.orbit.exception.UncheckedException: Don't know how to handle state

答:
What is kotlin equivalent of this java class?

Your Kotlin and Java code differs in two ways, the relationship of the State to StatefulActor and the ability of State to allow subclassing.

For State what you want is a Nested class not an Inner class in Kotlin terms. The former corresponds to static modifier in Java whereas the latter is like an inner class without the static modifier.

So for equivalence with the Java code you gave, you should drop the inner keyword.

Cloud.orbit.exception.UncheckedException: Don't know how to handle state

As for your Orbit problem you can try the following. This will also explain why subclassing is an issue:

// compile and run with cloud.orbit:orbit-runtime:1.2.0

import cloud.orbit.actors.runtime.AbstractActor
import cloud.orbit.actors.Actor
import cloud.orbit.actors.Stage
import cloud.orbit.concurrent.Task

class HelloActor: AbstractActor<HelloActor.ActorState>(), Hello
{
    override fun sayHello(greeting: String): Task<String> {
        val lastMessage = state().lastMessage
        state().lastMessage = greeting

        return Task.fromValue(lastMessage)
    }

    class ActorState {
        var lastMessage: String? = null
    }
}

interface Hello : Actor {
    fun sayHello(greeting: String): Task<String>
}

fun main(args : Array<String>) {
    val stage = Stage.Builder().clusterName("orbit-helloworld-cluster").build()
    stage.start().join()
    stage.bind()

    val helloActor = Actor.getReference(Hello::class.java, "0");

    var response = helloActor
            .sayHello("Welcome to orbit 1").join()

    println(response) // should print null

    response = helloActor
            .sayHello("Welcome to orbit 2").join()

    println(response) // should print "Welcome to orbit 1"

    stage.stop().join()
}
```

<p>Notice that the Actor's nested class is called <code>ActorState</code> and not <code>State</code> as in your question. When I named the Actor's state class <code>State</code> I got a similar error:</p>

```cloud.orbit.exception.UncheckedException: Don't know how to handle state: HelloActor$State...
Caused by: cloud.orbit.exception.UncheckedException: cloud.orbit.exception.UncheckedException: Don't know how to handle state: HelloActor$State
Caused by: cloud.orbit.exception.UncheckedException: Don't know how to handle state: HelloActor$State
Caused by: cloud.orbit.exception.UncheckedException: java.lang.ClassNotFoundException: HelloActor$ActorState
```

<p>But when I used the nested class name <code>HelloActor.ActorState</code> instead it works.</p>

<p>This is because by default all classes in Kotlin are closed (i.e. <code>final</code> in Java terms).</p>

<blockquote>
  <p>By default, all classes in Kotlin are final, which corresponds to Effective Java, Item 17: Design and document for inheritance or else prohibit it.</p>
</blockquote>

<p>While in orbit 1.2.0 the code (if you do not use the special name <code>ActorState</code>) tries to subclass your State class and then instantiate it. This will not work if you go with the closed Kotlin default extensibility.</p>

<p>If you wish to use your own name for the Actor's state class you must declare it as <code>open</code>. e.g.</p>

<pre class="lang-kotlin prettyprint-override"><code>class HelloActor: AbstractActor<HelloActor.State>(), Hello
{
    override fun sayHello(greeting: String): Task<String> {
        val lastMessage = state().lastMessage
        state().lastMessage = greeting

        return Task.fromValue(lastMessage)
    }

    open class State {
        var lastMessage: String? = null
    }
}
</code>```

Body:
What is kotlin equivalent of this java class?

public class StatefulActor extends AbstractActor<StatefulActor.State> implements Some
{
    public static class State
    {
        String lastMessage;
    }
}

I tried:

class HelloActor: AbstractActor<HelloActor.State>(), Hello
{
    inner class State {
        var lastMessage: String? = null
    }

but results in Cloud.orbit.exception.UncheckedException: Don't know how to handle state

Body:
What is kotlin equivalent of this java class?

Your Kotlin and Java code differs in two ways, the relationship of the State to StatefulActor and the ability of State to allow subclassing.

For State what you want is a Nested class not an Inner class in Kotlin terms. The former corresponds to static modifier in Java whereas the latter is like an inner class without the static modifier.

So for equivalence with the Java code you gave, you should drop the inner keyword.

Cloud.orbit.exception.UncheckedException: Don't know how to handle state

As for your Orbit problem you can try the following. This will also explain why subclassing is an issue:

// compile and run with cloud.orbit:orbit-runtime:1.2.0

import cloud.orbit.actors.runtime.AbstractActor
import cloud.orbit.actors.Actor
import cloud.orbit.actors.Stage
import cloud.orbit.concurrent.Task

class HelloActor: AbstractActor<HelloActor.ActorState>(), Hello
{
    override fun sayHello(greeting: String): Task<String> {
        val lastMessage = state().lastMessage
        state().lastMessage = greeting

        return Task.fromValue(lastMessage)
    }

    class ActorState {
        var lastMessage: String? = null
    }
}

interface Hello : Actor {
    fun sayHello(greeting: String): Task<String>
}

fun main(args : Array<String>) {
    val stage = Stage.Builder().clusterName("orbit-helloworld-cluster").build()
    stage.start().join()
    stage.bind()

    val helloActor = Actor.getReference(Hello::class.java, "0");

    var response = helloActor
            .sayHello("Welcome to orbit 1").join()

    println(response) // should print null

    response = helloActor
            .sayHello("Welcome to orbit 2").join()

    println(response) // should print "Welcome to orbit 1"

    stage.stop().join()
}

Notice that the Actor's nested class is called ActorState and not State as in your question. When I named the Actor's state class State I got a similar error:

cloud.orbit.exception.UncheckedException: Don't know how to handle state: HelloActor$State...
Caused by: cloud.orbit.exception.UncheckedException: cloud.orbit.exception.UncheckedException: Don't know how to handle state: HelloActor$State
Caused by: cloud.orbit.exception.UncheckedException: Don't know how to handle state: HelloActor$State
Caused by: cloud.orbit.exception.UncheckedException: java.lang.ClassNotFoundException: HelloActor$ActorState

But when I used the nested class name HelloActor.ActorState instead it works.

This is because by default all classes in Kotlin are closed (i.e. final in Java terms).

By default, all classes in Kotlin are final, which corresponds to Effective Java, Item 17: Design and document for inheritance or else prohibit it.

While in orbit 1.2.0 the code (if you do not use the special name ActorState) tries to subclass your State class and then instantiate it. This will not work if you go with the closed Kotlin default extensibility.

If you wish to use your own name for the Actor's state class you must declare it as open. e.g.

class HelloActor: AbstractActor<HelloActor.State>(), Hello
{
    override fun sayHello(greeting: String): Task<String> {
        val lastMessage = state().lastMessage
        state().lastMessage = greeting

        return Task.fromValue(lastMessage)
    }

    open class State {
        var lastMessage: String? = null
    }
}


来源: stackexchange

问:
Variables in a do while loop
Below is some code asking the user to input an integer.

```<code>public int getValidInput() {
    Scanner user_input = new Scanner(System.in);

    do {
        System.out.println("Enter an integer >=1 and <=10: ");
        int number = user_input.nextInt();

    } while (number > 10 || number < 0);

    return number;
}
</code>```

The code as shown does not work although when I initialise number outside the do command i.e. set it to int number; and then in the do loop set number = user_input.nextInt(); it does. Why does it work in one case and not the other?

答:
Conditions are used to enter a body from outside that body, so the variable which decides the truth value of condition has to exist before the body.
And as the body block of do-while loop is the code to be executed, therefore the code which decides to execute it must be other than itself.</p>

ContentLicense: CC BY-SA 3.0

Title: Variables in a do while loop

Body:
Below is some code asking the user to input an integer.

public int getValidInput() {
    Scanner user_input = new Scanner(System.in);

    do {
        System.out.println("Enter an integer >=1 and <=10: ");
        int number = user_input.nextInt();

    } while (number > 10 || number < 0);

    return number;
}

The code as shown does not work although when I initialise number outside the do command i.e. set it to int number; and then in the do loop set number = user_input.nextInt(); it does. Why does it work in one case and not the other?


问:
rownum in mariaDB not working
LIMIT is working properly but ROWNUM is not working. Here is my code-
"SELECT article_ref FROM article_write ROWNUM<=3" is not working in MariaDB.
Error : You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '<= 3' at line 1</p>

答:
For pagination, the usual technique is

```<code>LIMIT 10 OFFSET 20
</code>```

(to get the 3rd page of 10 items, for example.)

However, there are problems with doing such, and they are the same problems as with ROWNUM.  See this for a discussion of a more efficient, less buggy, way of doing pagination.

Title: rownum in mariaDB not working

Body:
For pagination, the usual technique is

LIMIT 10 OFFSET 20

(to get the 3rd page of 10 items, for example.)

However, there are problems with doing such, and they are the same problems as with ROWNUM.  See this for a discussion of a more efficient, less buggy, way of doing pagination.


问:
sizing the input only on xs screens
I am adding the class input-lg but I only want it on xs screens and not on md lg screens

```<code><input class="form-control input-lg" type="text">
</code>```

is there a way to do that using bootstrap only.

I think @media queries are the only solution.

答: Styles applied for smaller screens in bootstrap apply to their bigger screen counterparts unless explicitly mentioned. Ao, if you apply something for xs only, it will apply to sm, md and lg. To achieve what you want to, you need to apply style for xs, and separate style for sm, which can carryover to md and lg screensizes.</p>

Title: sizing the input only on xs screens

Body:
I am adding the class input-lg but I only want it on xs screens and not on md lg screens

<input class="form-control input-lg" type="text">

is there a way to do that using bootstrap only.

I think @media queries are the only solution.


问:
Force app to quit in Cordova iOS or Android
This is an old topic and I have never found an answer. This thread is the latest:

Phonegap: force an app to quit instead of running in background

But it is not a solution either as what I heard was "there is no way and it is not a good experience", etc...

However, if you download OfferUp app. Try to login and logout. The app on iOS will shut itself down. How do they do that? Obviously there is a way and it is approved by App Store. I am wondering if it is still possible with Cordova app?

答:
use this plugin

```<code>cordova plugin add https://github.com/FRD49/iOS-ExitApp.git
</code>```

and simply call

```<code>navigator.app.exitApp();
</code>```

Body:
use this plugin

cordova plugin add https://github.com/FRD49/iOS-ExitApp.git

and simply call

navigator.app.exitApp();


问:
Error handling Apollo-client with redux-observable
I'm doing a mutation using Apollo-client and redux-observable and so far this is my code:

```<code>export const languageTimeZoneEpic = (action$) => {
  return action$.ofType('PING')
    .flatMap(action => client.mutate({
      mutation: languageTimeZoneIdMutation,
      variables: { id: action.id,  defaultLanguage: action.selected_language, defaultTimeZoneId: action.selected_timeZone }
    })
      .then(store.dispatch(setLocale(action.selected_language)))
  )
    .map(result => ({
      type: 'PONG',
      payload: result
    }))
    .catch(error => ({
      type: 'PONG_ERROR'
    }));
};
</code>```

My mutation works correctly but I can't seem to make my catch(error) work. In the small amount of documentation I've found on this, it suggests I put Observable of after error => but then it gives me an error saying Observable is undefined.

Thank you

UPDATE:

If the connection between the app and the server doesn't work, it just waits for the connection to come back up and then finish the epic. I would like for it to just catch and error and stop the epic.

答:
Figured out there was nothing wrong with the catch(error) in the code above. Turns out putting the server on hold did not throw an error when I tried to establish a connection. It had to be shut down for it to throw an error.

For those who are looking for a good way to implement a mutation using Apollo-client with redux-observable (because there is almost no docs on it), here's the code I used for my mutation:

```<code>import { languageMutation } from '../mutation/languageMutation';
import { changeLanguageFulfilled, changeLanguageError } from '../actions/actions';

export const languageEpic = (action$) => {
  return action$.ofType('CHANGE_LANGUAGE')
    .mergeMap(action => client.mutate({
      mutation: languageMutation,
       variables: { id: action.id,  defaultLanguage: action.selected_language, defaultTimeZoneId: action.selected_timeZone }
    }).then(result => changeLanguageFulfilled(result))
      .catch(error => changeLanguageError(error))
  );
};
</code>```

Both changeLanguageFulfilled and changeLanguageError are actions that trigger their own reducer.

Hope this helps someone.

Body:
I'm doing a mutation using Apollo-client and redux-observable and so far this is my code:

export const languageTimeZoneEpic = (action$) => {
  return action$.ofType('PING')
    .flatMap(action => client.mutate({
      mutation: languageTimeZoneIdMutation,
      variables: { id: action.id,  defaultLanguage: action.selected_language, defaultTimeZoneId: action.selected_timeZone }
    })
      .then(store.dispatch(setLocale(action.selected_language)))
  )
    .map(result => ({
      type: 'PONG',
      payload: result
    }))
    .catch(error => ({
      type: 'PONG_ERROR'
    }));
};

My mutation works correctly but I can't seem to make my catch(error) work. In the small amount of documentation I've found on this, it suggests I put Observable of after error => but then it gives me an error saying Observable is undefined.

Thank you

UPDATE:

If the connection between the app and the server doesn't work, it just waits for the connection to come back up and then finish the epic. I would like for it to just catch and error and stop the epic.

Body:
Figured out there was nothing wrong with the catch(error) in the code above. Turns out putting the server on hold did not throw an error when I tried to establish a connection. It had to be shut down for it to throw an error.

For those who are looking for a good way to implement a mutation using Apollo-client with redux-observable (because there is almost no docs on it), here's the code I used for my mutation:

import { languageMutation } from '../mutation/languageMutation';
import { changeLanguageFulfilled, changeLanguageError } from '../actions/actions';

export const languageEpic = (action$) => {
  return action$.ofType('CHANGE_LANGUAGE')
    .mergeMap(action => client.mutate({
      mutation: languageMutation,
       variables: { id: action.id,  defaultLanguage: action.selected_language, defaultTimeZoneId: action.selected_timeZone }
    }).then(result => changeLanguageFulfilled(result))
      .catch(error => changeLanguageError(error))
  );
};

Both changeLanguageFulfilled and changeLanguageError are actions that trigger their own reducer.

Hope this helps someone.


问:
Try catch statements in C
I was thinking today about the try/catch blocks existent in another languages. Googled for a while this but with no result. From what I know, there is not such a thing as try/catch in C. However, is there a way to "simulate" them?

Sure, there is assert and other tricks but nothing like try/catch, that also catch the raised exception. Thank you

答:
This is another way to do error handling in C which is more performant than using setjmp/longjmp. Unfortunately, it will not work with MSVC but if using only GCC/Clang is an option, then you might consider it. Specifically, it uses the "label as value" extension, which allows you to take the address of a label, store it in a value and and jump to it unconditionally. I'll present it using an example:

```<code>GameEngine *CreateGameEngine(GameEngineParams const *params)
{
    /* Declare an error handler variable. This will hold the address
       to jump to if an error occurs to cleanup pending resources.
       Initialize it to the err label which simply returns an
       error value (NULL in this example). The && operator resolves to
       the address of the label err */
    void *eh = &&err;

    /* Try the allocation */
    GameEngine *engine = malloc(sizeof *engine);
    if (!engine)
        goto *eh; /* this is essentially your "throw" */

    /* Now make sure that if we throw from this point on, the memory
       gets deallocated. As a convention you could name the label "undo_"
       followed by the operation to rollback. */
    eh = &&undo_malloc;

    /* Now carry on with the initialization. */
    engine->window = OpenWindow(...);
    if (!engine->window)
        goto *eh;   /* The neat trick about using approach is that you don't
                       need to remember what "undo" label to go to in code.
                       Simply go to *eh. */

    eh = &&undo_window_open;

    /* etc */

    /* Everything went well, just return the device. */
    return device;

    /* After the return, insert your cleanup code in reverse order. */
undo_window_open: CloseWindow(engine->window);
undo_malloc: free(engine);
err: return NULL;
}
</code>```

If you so wish, you could refactor common code in defines, effectively implementing your own error-handling system.

```<code>/* Put at the beginning of a function that may fail. */
#define declthrows void *_eh = &&err

/* Cleans up resources and returns error result. */
#define throw goto *_eh

/* Sets a new undo checkpoint. */
#define undo(label) _eh = &&undo_##label

/* Throws if [condition] evaluates to false. */
#define check(condition) if (!(condition)) throw

/* Throws if [condition] evaluates to false. Then sets a new undo checkpoint. */
#define checkpoint(label, condition) { check(condition); undo(label); }
</code>```

Then the example becomes

```<code>GameEngine *CreateGameEngine(GameEngineParams const *params)
{
    declthrows;

    /* Try the allocation */
    GameEngine *engine = malloc(sizeof *engine);
    checkpoint(malloc, engine);

    /* Now carry on with the initialization. */
    engine->window = OpenWindow(...);
    checkpoint(window_open, engine->window);

    /* etc */

    /* Everything went well, just return the device. */
    return device;

    /* After the return, insert your cleanup code in reverse order. */
undo_window_open: CloseWindow(engine->window);
undo_malloc: free(engine);
err: return NULL;
}
</code>```

Title: Try catch statements in C

Body:
This is another way to do error handling in C which is more performant than using setjmp/longjmp. Unfortunately, it will not work with MSVC but if using only GCC/Clang is an option, then you might consider it. Specifically, it uses the "label as value" extension, which allows you to take the address of a label, store it in a value and and jump to it unconditionally. I'll present it using an example:

GameEngine *CreateGameEngine(GameEngineParams const *params)
{
    /* Declare an error handler variable. This will hold the address
       to jump to if an error occurs to cleanup pending resources.
       Initialize it to the err label which simply returns an
       error value (NULL in this example). The && operator resolves to
       the address of the label err */
    void *eh = &&err;

    /* Try the allocation */
    GameEngine *engine = malloc(sizeof *engine);
    if (!engine)
        goto *eh; /* this is essentially your "throw" */

    /* Now make sure that if we throw from this point on, the memory
       gets deallocated. As a convention you could name the label "undo_"
       followed by the operation to rollback. */
    eh = &&undo_malloc;

    /* Now carry on with the initialization. */
    engine->window = OpenWindow(...);
    if (!engine->window)
        goto *eh;   /* The neat trick about using approach is that you don't
                       need to remember what "undo" label to go to in code.
                       Simply go to *eh. */

    eh = &&undo_window_open;

    /* etc */

    /* Everything went well, just return the device. */
    return device;

    /* After the return, insert your cleanup code in reverse order. */
undo_window_open: CloseWindow(engine->window);
undo_malloc: free(engine);
err: return NULL;
}

If you so wish, you could refactor common code in defines, effectively implementing your own error-handling system.

/* Put at the beginning of a function that may fail. */
#define declthrows void *_eh = &&err

/* Cleans up resources and returns error result. */
#define throw goto *_eh

/* Sets a new undo checkpoint. */
#define undo(label) _eh = &&undo_##label

/* Throws if [condition] evaluates to false. */
#define check(condition) if (!(condition)) throw

/* Throws if [condition] evaluates to false. Then sets a new undo checkpoint. */
#define checkpoint(label, condition) { check(condition); undo(label); }

Then the example becomes

GameEngine *CreateGameEngine(GameEngineParams const *params)
{
    declthrows;

    /* Try the allocation */
    GameEngine *engine = malloc(sizeof *engine);
    checkpoint(malloc, engine);

    /* Now carry on with the initialization. */
    engine->window = OpenWindow(...);
    checkpoint(window_open, engine->window);

    /* etc */

    /* Everything went well, just return the device. */
    return device;

    /* After the return, insert your cleanup code in reverse order. */
undo_window_open: CloseWindow(engine->window);
undo_malloc: free(engine);
err: return NULL;
}


问:
How to return an element from the function that return a list in r?
I built my own function like this:

```<code>library(VineCopula)

Matrix <- c(5, 2, 3, 1, 4,
            0, 2, 3, 4, 1,
            0, 0, 3, 4, 1,
            0, 0, 0, 4, 1,
            0, 0, 0, 0, 1)
Matrix <- matrix(Matrix, 5, 5)
family <-par <- par2 <-  list()
for(i in 1:3){
# define R-vine pair-copula family matrix
family[[i]] <- c(0, 1, 3, 4, 4,
            0, 0, 3, 4, 1,
            0, 0, 0, 4, 1,
            0, 0, 0, 0, 3,
            0, 0, 0, 0, 0)
family[[i]] <- matrix(family[[i]], 5, 5)
# define R-vine pair-copula parameter matrix
par[[i]] <- c(0, 0.2, 0.9, 1.5, 3.9,
         0, 0, 1.1, 1.6, 0.9,
         0, 0, 0, 1.9, 0.5,
         0, 0, 0, 0, 4.8,
         0, 0, 0, 0, 0)
par[[i]] <- matrix(par[[i]], 5, 5)
# define second R-vine pair-copula parameter matrix
par2[[i]] <- matrix(0, 5, 5)
}
my_func <- function(Matrix, family, par, par2){
     x <- list()
     for(i in 1:3){
          x[[i]] <- RVineMatrix(Matrix = Matrix,family=family[[i]],par=par[[i]],par2 = par2[[i]])
     }
     x
}
</code>```

This will return me a list. How can I then extract specific element from my function. For example, how I can get my_func$Matrix or my_func$par[1]
Note: family <– par <– par2 <– list(). I also tried return(x[i]$family[i]) and return NULL.

To run the function:

```<code>y <- my_func(Matrix = Matrix,family = family,par = par,par2 = par2)

> y$Matrix
NULL
</code>```

答:
You'll need to assign the outcome of that function to something. For example:

```<code>y <- my_func(Matrix = ... , family = ..., par = ..., par2 = ...)
</code>```

where ... above are the values of your arguments. Based on your my_func definition, the end result is an unnamed list so to access its elements you use:

```<code>y[[1]]
y[[2]]
y[[3]]
</code>```

or just y to access all elements.

Body:
I built my own function like this:

library(VineCopula)

Matrix <- c(5, 2, 3, 1, 4,
            0, 2, 3, 4, 1,
            0, 0, 3, 4, 1,
            0, 0, 0, 4, 1,
            0, 0, 0, 0, 1)
Matrix <- matrix(Matrix, 5, 5)
family <-par <- par2 <-  list()
for(i in 1:3){
# define R-vine pair-copula family matrix
family[[i]] <- c(0, 1, 3, 4, 4,
            0, 0, 3, 4, 1,
            0, 0, 0, 4, 1,
            0, 0, 0, 0, 3,
            0, 0, 0, 0, 0)
family[[i]] <- matrix(family[[i]], 5, 5)
# define R-vine pair-copula parameter matrix
par[[i]] <- c(0, 0.2, 0.9, 1.5, 3.9,
         0, 0, 1.1, 1.6, 0.9,
         0, 0, 0, 1.9, 0.5,
         0, 0, 0, 0, 4.8,
         0, 0, 0, 0, 0)
par[[i]] <- matrix(par[[i]], 5, 5)
# define second R-vine pair-copula parameter matrix
par2[[i]] <- matrix(0, 5, 5)
}
my_func <- function(Matrix, family, par, par2){
     x <- list()
     for(i in 1:3){
          x[[i]] <- RVineMatrix(Matrix = Matrix,family=family[[i]],par=par[[i]],par2 = par2[[i]])
     }
     x
}

This will return me a list. How can I then extract specific element from my function. For example, how I can get my_func$Matrix or my_func$par[1]
Note: family <– par <– par2 <– list(). I also tried return(x[i]$family[i]) and return NULL.

To run the function:

y <- my_func(Matrix = Matrix,family = family,par = par,par2 = par2)

> y$Matrix
NULL

Body:
You'll need to assign the outcome of that function to something. For example:

y <- my_func(Matrix = ... , family = ..., par = ..., par2 = ...)

where ... above are the values of your arguments. Based on your my_func definition, the end result is an unnamed list so to access its elements you use:

y[[1]]
y[[2]]
y[[3]]

or just y to access all elements.


问:
Is there a library / repository / public site that contains commonly written Java Entities / Classes / Beans / Data structures? (Preferably in Java)
We all reuse our code, but really, how many times did you find yourself re-writing something like this?

```<code>class Person{
    private String firtsName;
    private String lastName;
    private Date dob;
    ...
    private List<Address> addresses
</code>```

or this

```<code>class Address {
    private String address1;
    private String address2;
    private String city;
    private String zip;
    ...
</code>```

Wouldn't it be nice if we had a library of free, mature, well written, best practice Entity types / beans / POJOs / POCOs so we all can finally say good bye to trying to clone the world in Java / C# / (replace with your favorite language) and start writing actual code.

Is there something like that?
Do you agree it's required?

答:
There's mvnrepository.com which contains tons of Java code of different nature. The most difficult part of you asking is done there -- central, searchable repository of Java code which is used by lots of developers and is "common practice".

I don't know if there's some library with purpose similar to what you interested in. But if there isn't you can always write it and share it with the world via given link.

ContentLicense: CC BY-SA 2.5

Body:
We all reuse our code, but really, how many times did you find yourself re-writing something like this?

class Person{
    private String firtsName;
    private String lastName;
    private Date dob;
    ...
    private List<Address> addresses

or this

class Address {
    private String address1;
    private String address2;
    private String city;
    private String zip;
    ...

Wouldn't it be nice if we had a library of free, mature, well written, best practice Entity types / beans / POJOs / POCOs so we all can finally say good bye to trying to clone the world in Java / C# / (replace with your favorite language) and start writing actual code.

Is there something like that?
Do you agree it's required?


问:
AttributeError: Unknown property cmap
I have the following 2 errors:

```<code>AttributeError: Unknown property cmap
</code>```

and

```<code>Cannot find reference 'coolwarm' in 'cm.py'
</code>```

I have run:

```<code>import matplotlib.pyplot as plt
import matplotlib
import matplotlib.cm as cm
</code>```

Code I get the error with is

```<code>fig = plt.figure()
ax1 = fig.add_subplot(111)
ax2 = ax1.twiny()

ax1.plot(result['tme'], result['spread'], ".", markersize=1,
c=result['bdaterange'], cmap=cm.coolwarm)
</code>```

答:
This might be what you're trying to do (your question is a bit vague, so, I guessed).

First, some imports and random data:

```<code>import matplotlib.pyplot as plt
import matplotlib.colors as colors
import matplotlib.cm as cm
import numpy as np

xs = np.arange(10)
ys = np.arange(10,20)
# the intensity of each data point
intensities = np.random.rand(10)
</code>```

Then, we get the colormap you wanted:

```<code>coolwarm = plt.get_cmap('coolwarm')
my_norm = colors.Normalize(0, 1)
map = cm.ScalarMappable(norm=my_norm, cmap='coolwarm')
</code>```

Finally, plot each data point with its intensity as follows:

```<code>for idx in range(len(ys)):
    point_x = xs[idx]
    point_y = ys[idx]
    my_col = map.to_rgba(intensities[idx])
    plt.plot(point_x, point_y, ".", markersize=5, color=my_col)

plt.show()
</code>```

For this code you get an image like this:
random_cmap_data

Title: AttributeError: Unknown property cmap

Body:
I have the following 2 errors:

AttributeError: Unknown property cmap

and

Cannot find reference 'coolwarm' in 'cm.py'

I have run:

import matplotlib.pyplot as plt
import matplotlib
import matplotlib.cm as cm

Code I get the error with is

fig = plt.figure()
ax1 = fig.add_subplot(111)
ax2 = ax1.twiny()

ax1.plot(result['tme'], result['spread'], ".", markersize=1,
c=result['bdaterange'], cmap=cm.coolwarm)

Body:
This might be what you're trying to do (your question is a bit vague, so, I guessed).

First, some imports and random data:

import matplotlib.pyplot as plt
import matplotlib.colors as colors
import matplotlib.cm as cm
import numpy as np

xs = np.arange(10)
ys = np.arange(10,20)
# the intensity of each data point
intensities = np.random.rand(10)

Then, we get the colormap you wanted:

coolwarm = plt.get_cmap('coolwarm')
my_norm = colors.Normalize(0, 1)
map = cm.ScalarMappable(norm=my_norm, cmap='coolwarm')

Finally, plot each data point with its intensity as follows:

for idx in range(len(ys)):
    point_x = xs[idx]
    point_y = ys[idx]
    my_col = map.to_rgba(intensities[idx])
    plt.plot(point_x, point_y, ".", markersize=5, color=my_col)

plt.show()

For this code you get an image like this:
random_cmap_data


问:
Split string by spaces into an array
I want to have a user type some words, and get them converted to an array. I want to split by word. Here is an example:

"15 17 21 46" → [15, 17, 21, 46]

Stuff like split("") and scan make an array out of every single letter.

I would prefer doing it without using YAML. Also, take note in the example that it doesn't include the spaces but it uses those as breaks between values.

Is it possible to do what I did in the example above where I have a bunch of numbers with spaces and those get converted directly to integers? I feel like the spaces might interrupt it in case I do something like to_i.

This question is similar to String to Array in Ruby, but it does not have an answer.

答:
Eric Duminil's answer shows how to split the string on what the contents is not -- spaces. Perfectly valid if you know that your string contains only digits of interest and spaces.

You can also gather the elements based on what you want -- digits vs what you don't want -- the spaces between the digits.

To do that in Ruby, use a regex with .scan:

```<code>> "15 17 21 46".scan(/\d+/)
=> ["15", "17", "21", "46"]
</code>```

Or, if you have numbers embedded in strings that you do not want:

```<code>> "15 17 21 46 123abc 34".scan(/\b\d+\b/)
=> ["15", "17", "21", "46", "34"]
</code>```

Note that 123 is not included since it is part of the string 123abc as opposed to:

```<code>> "15 17 21 46 123abc 34".scan(/\d+/)
=> ["15", "17", "21", "46", "123", "34"]
</code>```

This includes 123 since the word break \b was not part of the regex.

If you just split on spaces:

```<code>> "15 17 21 46 123abc 34".split
=> ["15", "17", "21", "46", "123abc", "34"]
</code>```

What the 'right answer' is is based on your goal and your data.

Then you can convert those values to integers:

```<code>"15 17 21 46 123abc 34".scan(/\b\d+\b/).map {|s| Integer(s) }
=> [15, 17, 21, 46, 34]
</code>```

Note that I am calling Integer vs the more permissive .to_i. Integer will raise an exception for strings that are not completely converted to an integer vs to_i that will convert the first few and silently ignore anything else:

```<code>> '1.5E+06'.to_i
=> 1
> Integer('1.5E+06')
ArgumentError: invalid value for Integer(): "1.5E+06"
    from (irb):19:in `Integer'
    from (irb):19
    from /usr/local/bin/irb:11:in `<main>'
</code>```

Again, it depends on the strings and your goal to know which is 'right.'

Title: Split string by spaces into an array

Body:
Eric Duminil's answer shows how to split the string on what the contents is not -- spaces. Perfectly valid if you know that your string contains only digits of interest and spaces.

You can also gather the elements based on what you want -- digits vs what you don't want -- the spaces between the digits.

To do that in Ruby, use a regex with .scan:

> "15 17 21 46".scan(/\d+/)
=> ["15", "17", "21", "46"]

Or, if you have numbers embedded in strings that you do not want:

> "15 17 21 46 123abc 34".scan(/\b\d+\b/)
=> ["15", "17", "21", "46", "34"]

Note that 123 is not included since it is part of the string 123abc as opposed to:

> "15 17 21 46 123abc 34".scan(/\d+/)
=> ["15", "17", "21", "46", "123", "34"]

This includes 123 since the word break \b was not part of the regex.

If you just split on spaces:

> "15 17 21 46 123abc 34".split
=> ["15", "17", "21", "46", "123abc", "34"]

What the 'right answer' is is based on your goal and your data.

Then you can convert those values to integers:

"15 17 21 46 123abc 34".scan(/\b\d+\b/).map {|s| Integer(s) }
=> [15, 17, 21, 46, 34]

Note that I am calling Integer vs the more permissive .to_i. Integer will raise an exception for strings that are not completely converted to an integer vs to_i that will convert the first few and silently ignore anything else:

> '1.5E+06'.to_i
=> 1
> Integer('1.5E+06')
ArgumentError: invalid value for Integer(): "1.5E+06"
    from (irb):19:in `Integer'
    from (irb):19
    from /usr/local/bin/irb:11:in `<main>'

Again, it depends on the strings and your goal to know which is 'right.'


问:
React inherit html from super class
I am building a series of gadgets and want to have a super class where some general gadget UI is defined such as a header bar container min/max/close button and maybe a footer and only the content area of the gadgets are defined in subclasses.

Any suggestions?

thanks

答:
I found an answer myself:

For the super class:

```<code>export default class Gadget extends React.Component{
    renderHeader() {
        return (
            <div>header</div>
        )
    }
    renderMe() {
        return null;
    }
    render() {
        return (
            <div>
                {this.renderHeader()}
                {this.renderMe()}
            </div>
        )
    }

}
</code>```

For the subclass:

```<code>import Gadget from '../../../../common/Gadget'
class ENGAlertsGadget extends Gadget{
    /**
    * render
    * @return {ReactElement} markup
    */
    renderMe(){

        //...
        return (
            <div id="ENGAlerts" style={{"height":"250px", "backgroundColor":"#58D3F7", "borderRadius":"10px", "margin":"9px", "padding":"9px"}}>

            </div>
        )
    }
}
</code>```

HTML:

```<code><ENGAlertsGadget/>
</code>```

The key points are

 - HTML code is not redundant

 - You never want to expose the super class in your HTML

Title: React inherit html from super class

Body:
I found an answer myself:

For the super class:

export default class Gadget extends React.Component{
    renderHeader() {
        return (
            <div>header</div>
        )
    }
    renderMe() {
        return null;
    }
    render() {
        return (
            <div>
                {this.renderHeader()}
                {this.renderMe()}
            </div>
        )
    }

}

For the subclass:

import Gadget from '../../../../common/Gadget'
class ENGAlertsGadget extends Gadget{
    /**
    * render
    * @return {ReactElement} markup
    */
    renderMe(){

        //...
        return (
            <div id="ENGAlerts" style={{"height":"250px", "backgroundColor":"#58D3F7", "borderRadius":"10px", "margin":"9px", "padding":"9px"}}>

            </div>
        )
    }
}

HTML:

<ENGAlertsGadget/>

The key points are

 - HTML code is not redundant

 - You never want to expose the super class in your HTML


问:
ASP.NET validators validate on mouse up
I have a compare validator on a Password field compared it to a password repeat field.  If there is a validation error the error doesn't disappear until the lost focus event is fired.  The client wants this changed to be the key up event.

What is the best way of going about this?

答:
It is doable as below:

```<code><script type="text/javascript" src="http://code.jquery.com/jquery-1.4.4.js"></script>
<script type="text/javascript">
    $(function () {
        $('#TextBox1').keyup(function () {
            if (typeof (Page_ClientValidate) == 'function') {
                Page_ClientValidate();
            }
        });
    });
</script>
</code>```

Edited: Changed mouseup to keyup.

Title: ASP.NET validators validate on mouse up

Body:
It is doable as below:

<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.4.js"></script>
<script type="text/javascript">
    $(function () {
        $('#TextBox1').keyup(function () {
            if (typeof (Page_ClientValidate) == 'function') {
                Page_ClientValidate();
            }
        });
    });
</script>

Edited: Changed mouseup to keyup.


问:
What is the correct way to update wrapped-maven jar in Apache Karaf?
I have created a OSGI bundle A and a jar B, A is dependent on B.
I also successful deployed A and B on Karaf 4.1.1.
B is deployed as wrapped maven jar (bundle:install -s mvn:....).

Now B has some changes, so I have redeployed it into our Nexus server, I also want to deploy the new B into Karaf.

But I found, if I only update B in Karaf, A is still using old B, even I have restart A.
I have to uninstall and re-install B to make A use the new B.

Since B is a common library, there will be many other bundles will dependent on B.
And B is also used by our other non-OSGI applications, so I don't want make it as OSGI bundle.

Is it the correct way to update wrapped-maven Jar in Karaf?
Or any suggestion?

答:
The problem is not related with "wrapped component". After being installed with wrap protocol, a jar is considered like a normal OSGI bundle.

But, Remember that Karaf watch changes only from SNAPSHOT bundles.

So:

In your developpement environnement, bundle B may be in SNAPSHOT version. So you can watch your changes immediately (just be sure to hit bundle:watch * in your karaf command line). Bundle A detect B's changes immediately also.

In your production environnement, bundle B must be in a released version. So to deploy your new changes in B, you must install it's new version and remove the old one.

If you want to let B deployed with two different version, and force A to use the new version, you have to make some changes into bundle A by modifying the import packages like this:

```<code>...
bundle_B_package*;version="[bundle_B_new_version,bundle_B_new_version + 1)",
...
</code>```

Here we are applying semantic versioning :)

Body:
The problem is not related with "wrapped component". After being installed with wrap protocol, a jar is considered like a normal OSGI bundle.

But, Remember that Karaf watch changes only from SNAPSHOT bundles.

So:

In your developpement environnement, bundle B may be in SNAPSHOT version. So you can watch your changes immediately (just be sure to hit bundle:watch * in your karaf command line). Bundle A detect B's changes immediately also.

In your production environnement, bundle B must be in a released version. So to deploy your new changes in B, you must install it's new version and remove the old one.

If you want to let B deployed with two different version, and force A to use the new version, you have to make some changes into bundle A by modifying the import packages like this:

...
bundle_B_package*;version="[bundle_B_new_version,bundle_B_new_version + 1)",
...

Here we are applying semantic versioning :)


问:
Is there a way to nest an enum within a data class in Kotlin?
Is there a way to nest an enum within a data class in Kotlin?

```<code>data class D(val a:Any) {
    enum class E {F,G}
    ...
}
</code>```

Or to declare it inline within a function?

```<code>fun foo() {
    enum class E {F,G}
    doSomething()
}
</code>```

I can't find documentation on the rules for where enums are allowed to be declared.

答:
Yes, you can nest the enum in a data class, but not in a function:</p>

```<code>data class Outer(val a: InnerEnum) {
    enum class InnerEnum { A, B }
}

fun foo() {
    val o = Outer(Outer.InnerEnum.A)
    println(o) // --> Outer(a=A)
}
</code>```

Body:
Is there a way to nest an enum within a data class in Kotlin?

data class D(val a:Any) {
    enum class E {F,G}
    ...
}

Or to declare it inline within a function?

fun foo() {
    enum class E {F,G}
    doSomething()
}

I can't find documentation on the rules for where enums are allowed to be declared.

Body:
Yes, you can nest the enum in a data class, but not in a function:

data class Outer(val a: InnerEnum) {
    enum class InnerEnum { A, B }
}

fun foo() {
    val o = Outer(Outer.InnerEnum.A)
    println(o) // --> Outer(a=A)
}

ContentLicense: CC BY-SA 4.0


问:
Is there "FloatingToggleButton" or something like that in Android?
I want to use FloatingActionButton for "like" action, but there should be two states for this, liked and unliked. So ToggleButton is suitable for this, but is there anything that combines the feature of these two kinds of button?</p>

答:
Basically this depend on your scenario,for eg if want to show like dislike only then use toggle button only and if want to perform some action then use floating action button with all the action..
Like for particular page change background black white,increase text size etc..All depends on scenario..And always try to choose best not to fail at any stage...For anything pls ask</p>


问:
Lock a div in place after you have selected it
So I have the hover state figured out. I'd like to keep the card at it's translated stated once I click on it though. I've tried using pseudo class :focus and :active but it didn't work. Or I'm just not putting the right values in.

$('.wrapper').on('click', function() {
  $(this).addClass('active');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.wrapper:hover {
    transform: translateY(5px);
}

.wrapper:active {
    transform: translateY(5px);
    position: fixed;
}</code>```

Featured

Big Baby Swing

Does he look like hes stupid.  Did he drive well?  No.  Then is he stupid? He's a good kid that's like the devil behind a wheel. That's all you need to know about him..

              More

```

codepen to my question

答:
You missed jquery cdn and add some css following if you need to get back use toggleClass.

```<code>.wrapper.active{
    transform: translateY(5px);
}
.wrapper.active div a.button{
    width:auto;
    font-size: 0.8rem;
    background-color: #29426d;
    box-shadow: none;
}
</code>```

$('.wrapper').on('click', function() {
  $(this).addClass('active');
  // You can use here toggleClass also
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html, body {
    margin: 0;
    padding: 0;
    width: 100%;
    height: 100%;
    background: #2c3e50;
    font-family: 'Montserrat', sans-serif;
    font-size: 14px;
}

/* this centers the card in the middle of any browser */

body {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-around;
    align-items: center;
    align-content: center;
    background-color: #D7D7DD;
}

/* You can rename this .wrapperCard or what ever you may have used.  The important thing to notice is the z-index relative to the .papaer div in order for this to work.  In the HTML document .space which contains the gradient at the bottom is out side of .paper that holds the information. */

.wrapper {
    margin: 0;
    padding: 0;
    height: auto;
    width: auto;
    transition: 1s ease;
    cursor: pointer;
    z-index: 98;
}

.wrapper:hover{
    transform: translateY(5px);
}
.wrapper.active{
    transform: translateY(5px);
}
.wrapper.active div a.button{
    width:auto;
    font-size: 0.8rem;
    background-color: #29426d;
    box-shadow: none;
}

.wrapper:hover div a.button{
    width:auto;
    font-size: 0.8rem;
    background-color: #29426d;
    box-shadow: none;
}

/* This calls onto the div.paper on hover and looks for div.space, if you take a way div.space your gradient will not longer dissapear on hover. */

.wrapper:hover div.space{
    transform: translateY(-7px);
    z-index:-1;
}

/* This is the div that contains all of the informoation, to be noted.  The div is set to a specific height of 41, it basically reaches to the bottom of the MORE button.  The reason being is so I can hide the gradient which is the div space, placed all the way at the bottom with a z-index of -1.  If you take out the height in div.paper you will see why I made the card a particular size, so keep that in mind when you are transfering the gradient code onto the cards for NASCA. */

.paper{
    font-family: 'Titilium Web', sans-serif;
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    align-content: center;
    margin: 0 auto;
    padding: 0;
    max-width: 300px;
    min-width: 300px;
    background: white;
    text-align: justify;
    z-index: 99;
}

a.image{
    flex: 1;
    text-align: none;
    font-size: none;
    text-decoration: none;
    color:none;
    transition: none;
    padding:0;
    margin: 0;
    height: auto;
}

a.image:hover{
    color:none;
    border-bottom:none;
    text-align: none;
    box-shadow: none;
    transform: none;
}

.poster{
    flex: 1;
    height: auto;
}

h2{
    flex: 1;
    font-size: .55rem;
    color: #A0A6AB;
    letter-spacing: 2px;
    text-transform: uppercase;
    text-align: center;
    font-family: $sans-serif;
    font-weight: 500;
    margin-bottom: 10px;
}

h1{
    flex: 1;
    display: flex;
    justify-content: center;
    margin-top:1rem;
    font-weight:bolder;
    letter-spacing: normal;
    font-kerning: 1rem;
    transition: 0.5s ease;
    color: #29426d;
}

h1:hover{
    transform: translateX(2px);
}

p{
    flex: 1;
    padding: 1rem 1rem;
    color:#333333;
}

a.button{
    position: relative;
    display: flex;
    justify-content: center;
    cursor: pointer;
    text-transform: uppercase;
    text-decoration: none;
    font-size: 0.8rem;
    line-height: 20px;
    letter-spacing: .06rem;
    font-weight: bold;
    color: white;
    background: #e44d6e;
    margin: 0 auto;
    padding: 0.5rem 1rem;
    width: auto;
    transition: 1s ease;
}

/* To be noted, the top selector is set to -4px because the gradient is too strong initially, pulling it up some makes it less harsh. */

.space{
    flex: 1;
    position: relative;
    padding: 0;
    margin: 0;
    left: 0;
    bottom: 0;
    width:100%;
    height: 1rem;
    background: grey;
    background: -webkit-linear-gradient(#333333 -290%, transparent 100%);
    background: -o-linear-gradient(#333333 -290%, transparent 100%);
    background: -mox-linear-gradient(#333333 -290%, transparent 100%);
    background: linear-gradient(#333333 -290%, transparent 100%);
    transition: 1s ease;
    z-index: -1;
}</code>```

Featured

Big Baby Swing

Does he look like hes stupid.  Did he drive well?  No.  Then is he stupid? He's a good kid that's like the devil behind a wheel. That's all you need to know about him..

            More

```

Body:
So I have the hover state figured out. I'd like to keep the card at it's translated stated once I click on it though. I've tried using pseudo class :focus and :active but it didn't work. Or I'm just not putting the right values in.

$('.wrapper').on('click', function() {
  $(this).addClass('active');
});

.wrapper:hover {
    transform: translateY(5px);
}

.wrapper:active {
    transform: translateY(5px);
    position: fixed;
}

Featured

Big Baby Swing

Does he look like hes stupid.  Did he drive well?  No.  Then is he stupid? He's a good kid that's like the devil behind a wheel. That's all you need to know about him..

              More

codepen to my question

Body:
You missed jquery cdn and add some css following if you need to get back use toggleClass.

.wrapper.active{
    transform: translateY(5px);
}
.wrapper.active div a.button{
    width:auto;
    font-size: 0.8rem;
    background-color: #29426d;
    box-shadow: none;
}

$('.wrapper').on('click', function() {
  $(this).addClass('active');
  // You can use here toggleClass also
});

html, body {
    margin: 0;
    padding: 0;
    width: 100%;
    height: 100%;
    background: #2c3e50;
    font-family: 'Montserrat', sans-serif;
    font-size: 14px;
}

/* this centers the card in the middle of any browser */

body {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-around;
    align-items: center;
    align-content: center;
    background-color: #D7D7DD;
}

/* You can rename this .wrapperCard or what ever you may have used.  The important thing to notice is the z-index relative to the .papaer div in order for this to work.  In the HTML document .space which contains the gradient at the bottom is out side of .paper that holds the information. */

.wrapper {
    margin: 0;
    padding: 0;
    height: auto;
    width: auto;
    transition: 1s ease;
    cursor: pointer;
    z-index: 98;
}

.wrapper:hover{
    transform: translateY(5px);
}
.wrapper.active{
    transform: translateY(5px);
}
.wrapper.active div a.button{
    width:auto;
    font-size: 0.8rem;
    background-color: #29426d;
    box-shadow: none;
}

.wrapper:hover div a.button{
    width:auto;
    font-size: 0.8rem;
    background-color: #29426d;
    box-shadow: none;
}

/* This calls onto the div.paper on hover and looks for div.space, if you take a way div.space your gradient will not longer dissapear on hover. */

.wrapper:hover div.space{
    transform: translateY(-7px);
    z-index:-1;
}

/* This is the div that contains all of the informoation, to be noted.  The div is set to a specific height of 41, it basically reaches to the bottom of the MORE button.  The reason being is so I can hide the gradient which is the div space, placed all the way at the bottom with a z-index of -1.  If you take out the height in div.paper you will see why I made the card a particular size, so keep that in mind when you are transfering the gradient code onto the cards for NASCA. */

.paper{
    font-family: 'Titilium Web', sans-serif;
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    align-content: center;
    margin: 0 auto;
    padding: 0;
    max-width: 300px;
    min-width: 300px;
    background: white;
    text-align: justify;
    z-index: 99;
}

a.image{
    flex: 1;
    text-align: none;
    font-size: none;
    text-decoration: none;
    color:none;
    transition: none;
    padding:0;
    margin: 0;
    height: auto;
}

a.image:hover{
    color:none;
    border-bottom:none;
    text-align: none;
    box-shadow: none;
    transform: none;
}

.poster{
    flex: 1;
    height: auto;
}

h2{
    flex: 1;
    font-size: .55rem;
    color: #A0A6AB;
    letter-spacing: 2px;
    text-transform: uppercase;
    text-align: center;
    font-family: $sans-serif;
    font-weight: 500;
    margin-bottom: 10px;
}

h1{
    flex: 1;
    display: flex;
    justify-content: center;
    margin-top:1rem;
    font-weight:bolder;
    letter-spacing: normal;
    font-kerning: 1rem;
    transition: 0.5s ease;
    color: #29426d;
}

h1:hover{
    transform: translateX(2px);
}

p{
    flex: 1;
    padding: 1rem 1rem;
    color:#333333;
}

a.button{
    position: relative;
    display: flex;
    justify-content: center;
    cursor: pointer;
    text-transform: uppercase;
    text-decoration: none;
    font-size: 0.8rem;
    line-height: 20px;
    letter-spacing: .06rem;
    font-weight: bold;
    color: white;
    background: #e44d6e;
    margin: 0 auto;
    padding: 0.5rem 1rem;
    width: auto;
    transition: 1s ease;
}

/* To be noted, the top selector is set to -4px because the gradient is too strong initially, pulling it up some makes it less harsh. */

.space{
    flex: 1;
    position: relative;
    padding: 0;
    margin: 0;
    left: 0;
    bottom: 0;
    width:100%;
    height: 1rem;
    background: grey;
    background: -webkit-linear-gradient(#333333 -290%, transparent 100%);
    background: -o-linear-gradient(#333333 -290%, transparent 100%);
    background: -mox-linear-gradient(#333333 -290%, transparent 100%);
    background: linear-gradient(#333333 -290%, transparent 100%);
    transition: 1s ease;
    z-index: -1;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
    <div class="paper">
        <a href="#" class="image"><img src="https://www.jbhifi.com.au/FileLibrary/ProductResources/Images/216422-M-LO.jpg"></a>
        <div class="poster">
        <h2>Featured</h2>
            <h1>Big Baby Swing</h1>
            <p>Does he look like hes stupid.  Did he drive well?  No.  Then is he stupid? He's a good kid that's like the devil behind a wheel. That's all you need to know about him..</p>
            <a href="https://www.google.com/search?q=baby+driver&rlz=1C1CHBF_enUS716US718&oq=baby+driver&aqs=chrome.0.69i59j0l5.1792j0j4&sourceid=chrome&ie=UTF-8" target="_blank" class="button">More</a>
        </div>
    </div>
    <div class="space"></div>
</div>

</body>


问:
Escaping nil closure definition in Swift
In objective-C I could pass a nil completion handler to any function. Coming to Swift3 I am struggling a bit with nil closure definition. I have a function defined like this:

```<code>func doSomething ( completion : @escaping (Error?) -> ()? ) {
    let error = foo( completion : { (error) in
        completion (error)
    })
}
</code>```

Now the point is that I try to call this function with a nil parameter for completion as I do not care of the results, I just want to launch a background activity. Calling

```<code>doSomething ( completion : nil)
</code>```

leads to error "nil is not compatible with type (error) -> ()?"
This was quite ok in Obj-C. I tried to google up and down but no success. I tried to relocate question mark around closure definition but not luck.

How do I achieve this?

答:
Rewrite your function as below:</p>

```<code>func doSomething ( completion : ((_ error: NSError?) -> Swift.Void)? ) {
    let error = foo( completion : { (error) in
            completion?(urlString, error)
    })
}
</code>```

Body:
In objective-C I could pass a nil completion handler to any function. Coming to Swift3 I am struggling a bit with nil closure definition. I have a function defined like this:

func doSomething ( completion : @escaping (Error?) -> ()? ) {
    let error = foo( completion : { (error) in
        completion (error)
    })
}

Now the point is that I try to call this function with a nil parameter for completion as I do not care of the results, I just want to launch a background activity. Calling

doSomething ( completion : nil)

leads to error "nil is not compatible with type (error) -> ()?"
This was quite ok in Obj-C. I tried to google up and down but no success. I tried to relocate question mark around closure definition but not luck.

How do I achieve this?

Body:
Rewrite your function as below:

func doSomething ( completion : ((_ error: NSError?) -> Swift.Void)? ) {
    let error = foo( completion : { (error) in
            completion?(urlString, error)
    })
}


问:
Cucumber Selenium using Excel File as Data Table
I am using Cucumber-Selenium and Excel as my Data file, my question is how can I run my feature file multiple time based on the data I have on the Excel. For Example I have 10 rows of data in Excel and wanted to run it one by one, after the first row of data it will move to the next row and execute it.

Feature File:
  Scenario: Login

```<code>Given I open the browser and access this URL
When I enter the "<Username>" and "<Password>"
Then I am able to login
</code>```

Step Definition:
    public class Login {

```<code> WebDriver driver = null;
 String url;

@Given("^I open the browser and access this URL$")
public void navigateToUrl() throws Throwable{

    System.setProperty("webdriver.chrome.driver", "");
    driver = new ChromeDriver();
    url = DataTable.getDataTableValue(0, 2, 2);
    driver.get(url);
    driver.manage().window().maximize();
}

@When("^I enter the \"([^\"]*)\" and \"([^\"]*)\"$")
public void enterCredentials(String userName, String password ) throws Throwable {

    userName = DataTable.getDataTableValue(0, 1, 1);
    password = DataTable.getDataTableValue(0, 1, 2);

    driver.findElement(By.id("username")).sendKeys(userName);
    driver.findElement(By.id("password")).sendKeys(password);
}

@Then("^I am able to login$")
public void clickLoginButton() throws Throwable {
    driver.findElement(By.id("Login")).click();
}
</code>```

}

Here is my Data Table(Excel File)

|ID     | UserName  | Password

|ID1    |username1  |password1

|ID2    | username2 | password2

|ID3    | username3 | password3

|ID4    | username4 | password4

答:
If you want to iterate of the content in an Excel sheet you need to implement that in code in the step definition. There is no support for doing it in Gherkin.

Apache POI may be an option when implementing the iteration.

It is important to understand that the purpose of Behaviour-Driven Development, BDD, is communication. Gherkin is one way of communicating. The Gherkin scenarios can be read and understood by almost anyone understanding the problem.

If you have some of the truth in Gherkin and some in Excel you will end up in a situation where you don't use Cucumber and Gherkin for communication but rather as a test tool. This may be ok. But if you use Cucumber as a test tool, there are other tools that may be easier to use. JUnit is one of them.

Body:
I am using Cucumber-Selenium and Excel as my Data file, my question is how can I run my feature file multiple time based on the data I have on the Excel. For Example I have 10 rows of data in Excel and wanted to run it one by one, after the first row of data it will move to the next row and execute it.

Feature File:
  Scenario: Login

Given I open the browser and access this URL
When I enter the "<Username>" and "<Password>"
Then I am able to login

Step Definition:
    public class Login {

 WebDriver driver = null;
 String url;

@Given("^I open the browser and access this URL$")
public void navigateToUrl() throws Throwable{

    System.setProperty("webdriver.chrome.driver", "");
    driver = new ChromeDriver();
    url = DataTable.getDataTableValue(0, 2, 2);
    driver.get(url);
    driver.manage().window().maximize();
}

@When("^I enter the \"([^\"]*)\" and \"([^\"]*)\"$")
public void enterCredentials(String userName, String password ) throws Throwable {

    userName = DataTable.getDataTableValue(0, 1, 1);
    password = DataTable.getDataTableValue(0, 1, 2);

    driver.findElement(By.id("username")).sendKeys(userName);
    driver.findElement(By.id("password")).sendKeys(password);
}

@Then("^I am able to login$")
public void clickLoginButton() throws Throwable {
    driver.findElement(By.id("Login")).click();
}

}

Here is my Data Table(Excel File)

|ID     | UserName  | Password

|ID1    |username1  |password1

|ID2    | username2 | password2

|ID3    | username3 | password3

|ID4    | username4 | password4


问:
Error using additive blending in WebGL
I'm developing a game engine in JavaScript and webgl and using the forward rendering technique, one pass for each light source in the scene.

I'm using additive blending for the second pass and it works quite well except when I need to light objects with transparent textures. In this case, I get the nasty artifact you can see in the picture below. Keep in mind objects in the scene are sorted by z (from far to near) and transparent objects are rendered after the opaque ones. I'm using the blend function gl.ONE - gl.ONE but, to be honest I tried randomly almost every possible combination that could make sense.

Anyone can give me an hint of how to fix this problem?

答:
I am debugging what I think is a similar issue. What I discovered is that the underlying page is showing through on pixels that have alpha less than 1. I seem to be getting this even when blending is disabled, or whatever blending mode is set. One way to debug this is change the background color on your page and see if it changes the result.

Check when you create your WebGL context if you are specifying true for 'alpha'. If so, try changing to false. This means that the browser will treat your canvas as completely opaque.

Title: Error using additive blending in WebGL


问:
ASP.NET: Does FormsCookie go away when authentication period expires?
I'm trying to establish some authentication timeout expiration checking, and I'm noticing something a little strange. When the authentication period is still valid, the following code will give me a cookie:

```<code>HttpCookie authCookie = context.Request.Cookies[".ASPXAUTH"]; // .ASPXAUTH name defined in web.config
</code>```

But when the authentication period has expired, the cookie is no longer in the Cookies array, and my result is null. I'm trying to build a FormsAuthenticationTicket object from the cookie, to be able to check the expired property. Like this:

```<code>FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);

// check if previously authenticated session is now dead
if (authTicket != null && authTicket.Expired)
{
    // send a Response indicating that they've expired.
}
</code>```

But if the cookie goes away once the authentication period has expired, I can't even get that far. So is there something I'm doing wrong, or is that cookie not supposed to be there? And if not, how am I supposed to build a ticket to even check the Expired property?

Thanks very much.

答:
The cookie has an expiration timeout value that you can specify in the configuration file.  There isn't much warning about when the cookie expires; you could build a process that checks upon every request to see which request it expired on.

However, factor in the  element too, which may require a valid user (not anonymous), so without the cookie you may get kicked out.

Read more about it here: http://support.microsoft.com/kb/910443

Body:
I'm trying to establish some authentication timeout expiration checking, and I'm noticing something a little strange. When the authentication period is still valid, the following code will give me a cookie:

HttpCookie authCookie = context.Request.Cookies[".ASPXAUTH"]; // .ASPXAUTH name defined in web.config

But when the authentication period has expired, the cookie is no longer in the Cookies array, and my result is null. I'm trying to build a FormsAuthenticationTicket object from the cookie, to be able to check the expired property. Like this:

FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);

// check if previously authenticated session is now dead
if (authTicket != null && authTicket.Expired)
{
    // send a Response indicating that they've expired.
}

But if the cookie goes away once the authentication period has expired, I can't even get that far. So is there something I'm doing wrong, or is that cookie not supposed to be there? And if not, how am I supposed to build a ticket to even check the Expired property?

Thanks very much.


问:
How to align portfolio items in height?
I would like to align these items in height:

Since I have little clue of what's going on, I'm going to paste what I THINK it's the relevant code:

#portfolio .portfolio-item {
      margin: 0 0 15px;
      right: 0;
    }
    #portfolio .portfolio-item .portfolio-link {
      display: block;
      position: relative;
      max-width: 400px;
      margin: 0 auto;
    }
    #portfolio .portfolio-item .portfolio-caption {
      max-width: 400px;
      margin: 0 auto;
      background-color: white;
      text-align: center;
      padding: 25px;
    }
    #portfolio .portfolio-item .portfolio-caption h4 {
      text-transform: none;
      margin: 0;
    }
    #portfolio .portfolio-item .portfolio-caption p {
      font-family: "Droid Serif", "Helvetica Neue", sans-serif;
      font-style: italic;
      font-size: 16px;
      margin: 0;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section id="portfolio" class="bg-light-gray">
        <div class="container">
            <div class="row">
              <div class="col-lg-12 text-center">
                    <h2 class="section-heading">Portfolio</h2>
                    <h3 class="section-subheading text-muted">Here I show some of my work.</h3>
                </div>
            </div>
            <div class="row">
                <div class="col-md-4 col-sm-6 portfolio-item">

                        <div class="portfolio-hover">
                            <div class="portfolio-hover-content">
                                <i class="fa fa-plus fa-3x"></i>
                                <p>click for more</p>
                            </div>
                        </div>
                        <img src="img/portfolio/img.jpg" class="img-responsive" alt="">

                    <div class="portfolio-caption">
                        <h4>1st job</h4>
                        <p class="text-muted">Design</p>
                    </div>
                </div>
                <div class="col-md-4 col-sm-6 portfolio-item">

                        <div class="portfolio-hover">
                            <div class="portfolio-hover-content">
                                <i class="fa fa-plus fa-3x"></i>
                                <p>click for more</p>
                            </div>
                        </div>
                        <img src="img/portfolio/img2.jpg" class="img-responsive" alt="">

                    <div class="portfolio-caption">
                        <h4>2nd job</h4>
                        <p class="text-muted">Design</p>
                        <br>
                    </div>
                </div>
                <div class="col-md-4 col-sm-6 portfolio-item">

                        <div class="portfolio-hover">
                            <div class="portfolio-hover-content">
                                <i class="fa fa-plus fa-3x"></i>
                                <p>click for more</p>
                            </div>
                        </div>
                        <img src="img/portfolio/img3.png" class="img-responsive" alt="">

                    <div class="portfolio-caption">
                        <h4>3rd job</h4>
                        <p class="text-muted">Design</p>
                    </div>
                </div>
                <div class="col-md-4 col-sm-6 portfolio-item">

                        <div class="portfolio-hover">
                            <div class="portfolio-hover-content">
                                <i class="fa fa-plus fa-3x"></i>
                                <p>click for more</p>
                            </div>
                        </div>
                        <img src="img/portfolio/img4.jpg" class="img-responsive" alt="">

                    <div class="portfolio-caption">
                        <h4>Beach Tennis Brand</h4>
                        <p class="text-muted">Design</p>
                    </div>
                </div>
                <div class="col-md-4 col-sm-6 portfolio-item">

                        <div class="portfolio-hover">
                            <div class="portfolio-hover-content">
                                <i class="fa fa-plus fa-3x"></i>
                                <p>click to watch</p>
                            </div>
                        </div>
                        <img src="img/portfolio/img5.jpg" class="img-responsive" alt="">

                    <div class="portfolio-caption">
                        <h4>NGO "4th job"</h4>
                        <p class="text-muted">Design</p>
                    </div>
                </div>
                <div class="col-md-4 col-sm-6 portfolio-item">

                        <div class="portfolio-hover">
                            <div class="portfolio-hover-content">
                                <i class="fa fa-plus fa-3x"></i>
                                <p>click for more</p>
                            </div>
                        </div>
                        <img src="img/portfolio/img6.jpg" class="img-responsive" alt="">

                    <div class="portfolio-caption">
                        <h4>Design</h4>
                        <p class="text-muted">5th job</p>
                    </div>
                </div>
            </div>
        </div>
    </section></code>```

Any help appreciated!

答:
You can use masonry layout ( search for isotope js in google ) or You can set min-height:300px;max-height:300px; ( for example ) for every .portfolio-item

For image if You don't want to use masonry, try add one more container for img:

```<code>.image_container{
   width:100%;
   height:300px;
   overflow:hidden;
}

.image_container img{
   max-width:100%;
   height:auto;
}
</code>```

but Your image will be cropped.

Title: How to align portfolio items in height?

Body:
I would like to align these items in height:

Since I have little clue of what's going on, I'm going to paste what I THINK it's the relevant code:

#portfolio .portfolio-item {
      margin: 0 0 15px;
      right: 0;
    }
    #portfolio .portfolio-item .portfolio-link {
      display: block;
      position: relative;
      max-width: 400px;
      margin: 0 auto;
    }
    #portfolio .portfolio-item .portfolio-caption {
      max-width: 400px;
      margin: 0 auto;
      background-color: white;
      text-align: center;
      padding: 25px;
    }
    #portfolio .portfolio-item .portfolio-caption h4 {
      text-transform: none;
      margin: 0;
    }
    #portfolio .portfolio-item .portfolio-caption p {
      font-family: "Droid Serif", "Helvetica Neue", sans-serif;
      font-style: italic;
      font-size: 16px;
      margin: 0;
    }

Portfolio

Here I show some of my work.

click for more

1st job

Design

click for more

2nd job

Design

click for more

3rd job

Design

click for more

Beach Tennis Brand

Design

click to watch

NGO "4th job"

Design

click for more

Design

5th job

Any help appreciated!

Body:
You can use masonry layout ( search for isotope js in google ) or You can set min-height:300px;max-height:300px; ( for example ) for every .portfolio-item

For image if You don't want to use masonry, try add one more container for img:

.image_container{
   width:100%;
   height:300px;
   overflow:hidden;
}

.image_container img{
   max-width:100%;
   height:auto;
}

but Your image will be cropped.


问:
Access shared file in Dropbox API
I need to regularly download a file that someone shared with me on Dropbox.
I manage to list all my shared links through the HTTP API (https://www.dropbox.com/developers/documentation/http/documentation#sharing-list_shared_links) but this don't list the file I want.

I can't figure out what is the correct way to download through the API a file   that someone shared with me. Here below you can see the print screen on Dropbox where this files is, if it can help...

答: Based on your screenshot, it sounds like you need to use the /2/sharing/list_received_files and /2/sharing/list_received_files/continue endpoints instead.</p>

Title: Access shared file in Dropbox API


问:
How can I get a JSON status that my server is busy?
My JSON Code:

```<code>Response.Listener<String> responseListener = new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject jsonResponse = new JSONObject(response);
                            int success = jsonResponse.getInt("success");

                            if (success == 0) {

                            }
                            if (success == 1) {

                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                };
                nRequest nRequest = new nRequest(edtTextReg.getText().toString(), responseListener);
                RequestQueue queue = Volley.newRequestQueue(login.this);
                queue.add(nRequest);
</code>```

How can I find a way that JSON give me the status "server is busy"? Busy means for example: thousands of people use my server.

答:
Http status code for server overload is 503.

503 - Service Unavailable
A 503 status code is most often seen on extremely busy servers, and it indicates that the server was unable to complete the request due to a server overload.

so your code should be something like this:

```<code>                @Override

                public void onResponse(String response) {
                    try {
                        JSONObject jsonResponse = new JSONObject(response);

                 int status = jsonResponse.getStatusLine().getStatusCode();
                      int success = jsonResponse.getInt("success");
                        if (status == 503) {
                          //
                        }

                        if (success == 0) {

                        }
                        if (success == 1) {

                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            };
</code>```

Body:
My JSON Code:

Response.Listener<String> responseListener = new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject jsonResponse = new JSONObject(response);
                            int success = jsonResponse.getInt("success");

                            if (success == 0) {

                            }
                            if (success == 1) {

                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                };
                nRequest nRequest = new nRequest(edtTextReg.getText().toString(), responseListener);
                RequestQueue queue = Volley.newRequestQueue(login.this);
                queue.add(nRequest);

How can I find a way that JSON give me the status "server is busy"? Busy means for example: thousands of people use my server.

Body:
Http status code for server overload is 503.

503 - Service Unavailable
A 503 status code is most often seen on extremely busy servers, and it indicates that the server was unable to complete the request due to a server overload.

so your code should be something like this:

                @Override

                public void onResponse(String response) {
                    try {
                        JSONObject jsonResponse = new JSONObject(response);

                 int status = jsonResponse.getStatusLine().getStatusCode();
                      int success = jsonResponse.getInt("success");
                        if (status == 503) {
                          //
                        }

                        if (success == 0) {

                        }
                        if (success == 1) {

                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            };


问:
Could not convert string to float in generator
I am trying to do some basic operations with a nest listed of data in Python 2.7.  A simplified version of my data is presented below:

```<code>resultlistdata = [
['sell','EURUSD',-1092.0,'Sometext'],
['buy','GBPUSD',2342.0,'Moretext'],
['buy','EURUSD',2122.0,'Yetmoretext'],
['not opened','','',''],
['sell','EURJPY',-483,'Difftext'],
['sell','EURJPY',269,'Anothertext'],
etc...
]
</code>```

The list is a few thousand lines long.  I'm trying to count the number of times the third item in the list is greater than or equal to zero (so the correct result in the case above would be 3).  I am using the generator expression (or is it list comprehension?):

```<code>profittrades = sum(1 for x in resultdatalist if x[2] >= 0)
</code>```

which gives an answer equal to the number of items in the list (so 6 in the case above, which is wrong).  I have also tried:

```<code>profittrades = sum(1 for x in resultdatalist if float(x[2]) >= 0)
</code>```

which gives the error "ValueError:  Could not convert string to float".

I am almost certain the problem is caused by the line where the 'not opened' occurs, and it cannot convert the empty string to a float, I just don't know what to do about it!

Is there a way to do the counting using a 'one-liner' list comprehension approach, or do I need to make a loop?

The "resultslistdata" is compiled by me, so if there is something clever I can do when creating it that would help I can give it a try.  Im reluctant to enter a value of "0" as the profit for trades that are "never opened" because later when I do averages it will skew my results (?!).

Thank you to anyone who can help me!

答:
If all trades that were never opened (or something of that sort) are all blanks '', then you can do:

```<code>profittrades = sum(1 for x in resultdatalist if x[2] and float(x[2]) >= 0)
</code>```

This checks first that the string is not falsy i.e. blank, before attempting the float cast.

Body:
I am trying to do some basic operations with a nest listed of data in Python 2.7.  A simplified version of my data is presented below:

resultlistdata = [
['sell','EURUSD',-1092.0,'Sometext'],
['buy','GBPUSD',2342.0,'Moretext'],
['buy','EURUSD',2122.0,'Yetmoretext'],
['not opened','','',''],
['sell','EURJPY',-483,'Difftext'],
['sell','EURJPY',269,'Anothertext'],
etc...
]

The list is a few thousand lines long.  I'm trying to count the number of times the third item in the list is greater than or equal to zero (so the correct result in the case above would be 3).  I am using the generator expression (or is it list comprehension?):

profittrades = sum(1 for x in resultdatalist if x[2] >= 0)

which gives an answer equal to the number of items in the list (so 6 in the case above, which is wrong).  I have also tried:

profittrades = sum(1 for x in resultdatalist if float(x[2]) >= 0)

which gives the error "ValueError:  Could not convert string to float".

I am almost certain the problem is caused by the line where the 'not opened' occurs, and it cannot convert the empty string to a float, I just don't know what to do about it!

Is there a way to do the counting using a 'one-liner' list comprehension approach, or do I need to make a loop?

The "resultslistdata" is compiled by me, so if there is something clever I can do when creating it that would help I can give it a try.  Im reluctant to enter a value of "0" as the profit for trades that are "never opened" because later when I do averages it will skew my results (?!).

Thank you to anyone who can help me!

Body:
If all trades that were never opened (or something of that sort) are all blanks '', then you can do:

profittrades = sum(1 for x in resultdatalist if x[2] and float(x[2]) >= 0)

This checks first that the string is not falsy i.e. blank, before attempting the float cast.


问:
Pluralize string in Symfony 3
Are there any ways for pluralizing a string in Symfony 3? For example: I have "Object" and I would like to get "Objects".</p>

答:
pluralization is a very complex topic and Symfony embraces it as part if the Translation Component:

Message pluralization is a tough topic as the rules can be quite complex.

So you basically would need to activate translations for your system and translate the needed strings using the transChoice() method of the translator service or the 'transchoice' tag / filter in your twig template.

To handle this, use the transChoice() method or the transchoice tag/filter in your template.

using the translator service

```<code>// the %count% placeholder is assigned to the second argument...
$translator->transChoice(
    'There is one apple|There are %count% apples',
    10
);

// ...but you can define more placeholders if needed
$translator->transChoice(
    'Hurry up %name%! There is one apple left.|There are %count% apples left.',
    10,
    // no need to include %count% here; Symfony does that for you
    array('%name%' => $user->getName())
);
</code>```

twig tags

```<code>{% trans %}Hello %name%{% endtrans %}

{% transchoice count %}
    {0} There are no apples|{1} There is one apple|]1,Inf[ There are %count% apples
{% endtranschoice %}
</code>```

UPDATE

If you do not know the string beforehand you can use the internal Inflector Component, but be aware of the disclaimer and the fact that this would only work for strings in  English:

This component is currently marked as internal. Do not use it in your own code. Breaking changes may be introduced in the next minor version of Symfony, or the component itself might even be removed completely.

An alternative would be to create your own inflector class, e.g. something like this and  create a service from it.

Title: Pluralize string in Symfony 3

Body:
pluralization is a very complex topic and Symfony embraces it as part if the Translation Component:

Message pluralization is a tough topic as the rules can be quite complex.

So you basically would need to activate translations for your system and translate the needed strings using the transChoice() method of the translator service or the 'transchoice' tag / filter in your twig template.

To handle this, use the transChoice() method or the transchoice tag/filter in your template.

using the translator service

// the %count% placeholder is assigned to the second argument...
$translator->transChoice(
    'There is one apple|There are %count% apples',
    10
);

// ...but you can define more placeholders if needed
$translator->transChoice(
    'Hurry up %name%! There is one apple left.|There are %count% apples left.',
    10,
    // no need to include %count% here; Symfony does that for you
    array('%name%' => $user->getName())
);

twig tags

{% trans %}Hello %name%{% endtrans %}

{% transchoice count %}
    {0} There are no apples|{1} There is one apple|]1,Inf[ There are %count% apples
{% endtranschoice %}

UPDATE

If you do not know the string beforehand you can use the internal Inflector Component, but be aware of the disclaimer and the fact that this would only work for strings in  English:

This component is currently marked as internal. Do not use it in your own code. Breaking changes may be introduced in the next minor version of Symfony, or the component itself might even be removed completely.

An alternative would be to create your own inflector class, e.g. something like this and  create a service from it.


问:
Extending UIControl to Assign a Startup Value for Persistence
StackOverflow,

I am working to extend UIControl to assign a single value to itself. This is implemented so it can assign a value on startup for persistence. My goal is to do this as generally as possible so it is easily extendable. One of the main components of my approach is switching on the type of UIControl. For instance, if it is a switch I need to assign a bool and if is a text view I need to assign a string. Yet, it gives me a few errors given below:

Cast from 'UIControl' to unrelated type 'UITextView' always fails

Expression pattern of type 'Bool' cannot match values of type
  'UIControl'

I understand that this code is completely wrong but I have found no other approach. What is your suggestion to implement this method? Am I on the right track?

```<code>extension UIControl {
    func assignValue(value: Any?){
        switch(self){
        case self is UISwitch:
            (self as! UISwitch).isOn = value as! Bool
        case self is UITextView:
            (self as! UITextView).text = value as! String
        default:
            break
        }
    }
}
</code>```

Thanks,
Macro

答:
self.hello(),

The syntax errors can be fixed by matching true to the case in which the object is of type UISwitch, UITextView, etc. All UIControl elements will inherit this method. It might be better to separately extend each UIElements that is implemented so they don't all have the function.

```<code>extension UIControl {
    func assignValue(object: AnyObject, value: Any){
        switch(true){
        case object is UISwitch:
            (object as! UISwitch).isOn = value as! Bool
        case object is UITextView:
            (object as! UITextView).text = value as! String
        default:
            break
        }
    }
}
</code>```

self.thanks()

Body:
StackOverflow,

I am working to extend UIControl to assign a single value to itself. This is implemented so it can assign a value on startup for persistence. My goal is to do this as generally as possible so it is easily extendable. One of the main components of my approach is switching on the type of UIControl. For instance, if it is a switch I need to assign a bool and if is a text view I need to assign a string. Yet, it gives me a few errors given below:

Cast from 'UIControl' to unrelated type 'UITextView' always fails

Expression pattern of type 'Bool' cannot match values of type
  'UIControl'

I understand that this code is completely wrong but I have found no other approach. What is your suggestion to implement this method? Am I on the right track?

extension UIControl {
    func assignValue(value: Any?){
        switch(self){
        case self is UISwitch:
            (self as! UISwitch).isOn = value as! Bool
        case self is UITextView:
            (self as! UITextView).text = value as! String
        default:
            break
        }
    }
}

Thanks,
Macro

Body:
self.hello(),

The syntax errors can be fixed by matching true to the case in which the object is of type UISwitch, UITextView, etc. All UIControl elements will inherit this method. It might be better to separately extend each UIElements that is implemented so they don't all have the function.

extension UIControl {
    func assignValue(object: AnyObject, value: Any){
        switch(true){
        case object is UISwitch:
            (object as! UISwitch).isOn = value as! Bool
        case object is UITextView:
            (object as! UITextView).text = value as! String
        default:
            break
        }
    }
}

self.thanks()


问:
Activating SSL on index page of Presta Shop
I've got problem with SSL on webpage altrak24.com. The SSL works only at admin page at address altrak24.com/admin3218/. I've tried everything including modifications of .htaccess and setting up SSL on admin page.

Any ideas how to fix this situation?

答:
Best way to redirect everything is to make an url redirect rule in .htaccess (if you are on Apache) :</p>

```<code>RewriteEngine On
RewriteCond %{HTTP_HOST} ^domain\.com [NC]
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI}
</code>```

Body:
Best way to redirect everything is to make an url redirect rule in .htaccess (if you are on Apache) :

RewriteEngine On
RewriteCond %{HTTP_HOST} ^domain\.com [NC]
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI}


问:
CVS Web frontend
Is there any free WEB application, that can be installed and pointed to any CVS server, that would show commits as they arrive, allow to search them, and possibly present nice diffs, and visual representation of branches.</p>

Title: CVS Web frontend

Body:
http://www.gjt.org/src/cvsweb/

http://www.viewvc.org/


问:
Convert this Excel formula into VBA code
```<code>=IF((effDate)-curDate>0,0,IF(curDate-(effDate)+1>nDays,0,nSpend/4))+IF((effDate+365/4*1)-curDate>0,0,IF(curDate-(effDate+365/$4*1)+1>nDays,0,nSpend/4))+IF((effDate+365/4*2)-curDate>0,0,IF(curDate-(effDate+365/4*2)+1>nDays,0,nSpend/4))+IF((effDate+365/4*3)-curDate>0,0,IF(curDate-(effDate+365/4*3)+1>nDays,0,nSpend/4))

effDate: 1/1/2017 (as value)
curDate: 1/31/2017 (as value)
nSpend: 1600
nDays: 60
Correct answer: 400
</code>```

Above is a long formula I'm trying to covert to VBA code. The way I've been trying to do it is long and I tried breaking it up into smaller functions, but it's not giving me the right answer. My VBA skills are very beginner so I'm not sure what else to try. I keep getting the wrong answer or no answer at all.

This is what I've been trying:

```<code>If effdate - curdate > 0 Then
val1 = 0
Exit Function
End If

If curdate - effDate + 1 > nDays Then
val1 = 0
Else
val1 = nSpend / 4

End If

If (effDate + (365 / 4)) - curdate > 0 Then
val2 = 0
Exit Function
End If

If curdate - (effDate + (365 / 4)) + 1 > nDays Then
val2 = 0
Else
val2 = nSpend / 4
End If

If effDate + (365 / (4 * 2)) - curdate > 0 Then
val3 = 0
Exit Function
End If

If curdate - (effDate + (365 / (4 * 2))) + 1 > nDays Then
val3 = 0
Else
val3 = nSpend / 4
End If

If effDate + (365 / (4 * 3)) - curdate > 0 Then
val4 = 0
Exit Function
End If

If curdate - (effDate + (365 / (4 * 3))) + 1 > nDays Then
val4 = 0
Else
val4 = nSpend / 4
End If
End If

APFcst = val1 + val2 + val3 + val4

End Function
</code>```

I dimmed everything correctly, it's the actual conversion that I have problems with.
I would appreciate the help! This is also a huge learning stretch for me since I just started learning VBA coding.
Thank you!

答:
I was intrigued by this to see why it wasn't working, I've rewrote the if > else > else logic to an if or > else but it achieves the same thing. Like Doug Coats' answer says, you can use DateAdd to work with subtraction/adding dates together. I've just converted the date strings to double:

```<code>Private Sub CommandButton1_Click()
Dim x As Date: Dim y As Date
Dim effDate As Double
Dim curDate As Double
Dim nSpend As Double
Dim nDays As Double

x = "1/1/17"
y = "31/1/17"
effDate = CDbl(x)
curDate = CDbl(y)
nSpend = 1600
nDays = 60

If (effDate - curDate > 0) Or (curDate - effDate + 1 > nDays) Then
    val1 = 0
Else
    val1 = nSpend / 4
End If

If ((effDate + (365 / 4)) - curDate > 0) Or (curDate - (effDate + (365 / 4)) + 1 > nDays) Then
    val2 = 0
Else
    val2 = nSpend / 4
End If

If (effDate + (365 / (4 * 2)) - curDate > 0) Or (curDate - (effDate + (365 / (4 * 2))) + 1 > nDays) Then
    val3 = 0
Else
    val3 = nSpend / 4
End If

If (effDate + (365 / (4 * 3)) - curDate > 0) Or (curDate - (effDate + (365 / (4 * 3))) + 1 > nDays) Then
    val4 = 0
Else
    val4 = nSpend / 4
End If

MsgBox (val1 + val2 + val3 + val4)

End Sub
</code>```

Body:
=IF((effDate)-curDate>0,0,IF(curDate-(effDate)+1>nDays,0,nSpend/4))+IF((effDate+365/4*1)-curDate>0,0,IF(curDate-(effDate+365/$4*1)+1>nDays,0,nSpend/4))+IF((effDate+365/4*2)-curDate>0,0,IF(curDate-(effDate+365/4*2)+1>nDays,0,nSpend/4))+IF((effDate+365/4*3)-curDate>0,0,IF(curDate-(effDate+365/4*3)+1>nDays,0,nSpend/4))

effDate: 1/1/2017 (as value)
curDate: 1/31/2017 (as value)
nSpend: 1600
nDays: 60
Correct answer: 400

Above is a long formula I'm trying to covert to VBA code. The way I've been trying to do it is long and I tried breaking it up into smaller functions, but it's not giving me the right answer. My VBA skills are very beginner so I'm not sure what else to try. I keep getting the wrong answer or no answer at all.

This is what I've been trying:

If effdate - curdate > 0 Then
val1 = 0
Exit Function
End If

If curdate - effDate + 1 > nDays Then
val1 = 0
Else
val1 = nSpend / 4

End If

If (effDate + (365 / 4)) - curdate > 0 Then
val2 = 0
Exit Function
End If

If curdate - (effDate + (365 / 4)) + 1 > nDays Then
val2 = 0
Else
val2 = nSpend / 4
End If

If effDate + (365 / (4 * 2)) - curdate > 0 Then
val3 = 0
Exit Function
End If

If curdate - (effDate + (365 / (4 * 2))) + 1 > nDays Then
val3 = 0
Else
val3 = nSpend / 4
End If

If effDate + (365 / (4 * 3)) - curdate > 0 Then
val4 = 0
Exit Function
End If

If curdate - (effDate + (365 / (4 * 3))) + 1 > nDays Then
val4 = 0
Else
val4 = nSpend / 4
End If
End If

APFcst = val1 + val2 + val3 + val4

End Function

I dimmed everything correctly, it's the actual conversion that I have problems with.
I would appreciate the help! This is also a huge learning stretch for me since I just started learning VBA coding.
Thank you!

Body:
I was intrigued by this to see why it wasn't working, I've rewrote the if > else > else logic to an if or > else but it achieves the same thing. Like Doug Coats' answer says, you can use DateAdd to work with subtraction/adding dates together. I've just converted the date strings to double:

Private Sub CommandButton1_Click()
Dim x As Date: Dim y As Date
Dim effDate As Double
Dim curDate As Double
Dim nSpend As Double
Dim nDays As Double

x = "1/1/17"
y = "31/1/17"
effDate = CDbl(x)
curDate = CDbl(y)
nSpend = 1600
nDays = 60

If (effDate - curDate > 0) Or (curDate - effDate + 1 > nDays) Then
    val1 = 0
Else
    val1 = nSpend / 4
End If

If ((effDate + (365 / 4)) - curDate > 0) Or (curDate - (effDate + (365 / 4)) + 1 > nDays) Then
    val2 = 0
Else
    val2 = nSpend / 4
End If

If (effDate + (365 / (4 * 2)) - curDate > 0) Or (curDate - (effDate + (365 / (4 * 2))) + 1 > nDays) Then
    val3 = 0
Else
    val3 = nSpend / 4
End If

If (effDate + (365 / (4 * 3)) - curDate > 0) Or (curDate - (effDate + (365 / (4 * 3))) + 1 > nDays) Then
    val4 = 0
Else
    val4 = nSpend / 4
End If

MsgBox (val1 + val2 + val3 + val4)

End Sub