问:
Can I specify a path in an attribute to map a property in my class to a child property in my JSON?
There is some code (which I can't change) that uses Newtonsoft.Json's DeserializeObject<T>(strJSONData) to take data from a web request and convert it to a class object (I can change the class). By decorating my class properties with [DataMember(Name = "raw_property_name")] I can map the raw JSON data to the correct property in my class.  Is there a way I can map the child property of a JSON complex object to a simple property?  Here's an example:

```<code>{
    "picture":
    {
        "id": 123456,
        "data":
        {
            "type": "jpg",
            "url": "http://www.someplace.com/mypicture.jpg"
        }
    }
}
</code>```

I don't care about any of the rest of the picture object except for URL, and so don't want to setup a complex object in my C# class.  I really just want something like:

```<code>[DataMember(Name = "picture.data.url")]
public string ProfilePicture { get; set; }
</code>```

Is this possible?

答:
Istead of doing

```<code>lastLevel [nesting [i]] = new JValue(prop.GetValue (value));
</code>```

You have to do

```<code>lastLevel[nesting[i]] = JValue.FromObject(jValue);
</code>```

Otherwise we have a

Could not determine JSON object type for type ...

exception

A complete piece of code would be this:

```<code>object jValue = prop.GetValue(value);
if (prop.PropertyType.IsArray)
{
    if(jValue != null)
        //https://stackoverflow.com/a/20769644/249895
        lastLevel[nesting[i]] = JArray.FromObject(jValue);
}
else
{
    if (prop.PropertyType.IsClass && prop.PropertyType != typeof(System.String))
    {
        if (jValue != null)
            lastLevel[nesting[i]] = JValue.FromObject(jValue);
    }
    else
    {
        lastLevel[nesting[i]] = new JValue(jValue);
    }
}
</code>```

Body:
There is some code (which I can't change) that uses Newtonsoft.Json's DeserializeObject<T>(strJSONData) to take data from a web request and convert it to a class object (I can change the class). By decorating my class properties with [DataMember(Name = "raw_property_name")] I can map the raw JSON data to the correct property in my class.  Is there a way I can map the child property of a JSON complex object to a simple property?  Here's an example:

{
    "picture":
    {
        "id": 123456,
        "data":
        {
            "type": "jpg",
            "url": "http://www.someplace.com/mypicture.jpg"
        }
    }
}

I don't care about any of the rest of the picture object except for URL, and so don't want to setup a complex object in my C# class.  I really just want something like:

[DataMember(Name = "picture.data.url")]
public string ProfilePicture { get; set; }

Is this possible?

Body:
Istead of doing

lastLevel [nesting [i]] = new JValue(prop.GetValue (value));

You have to do

lastLevel[nesting[i]] = JValue.FromObject(jValue);

Otherwise we have a

Could not determine JSON object type for type ...

exception

A complete piece of code would be this:

object jValue = prop.GetValue(value);
if (prop.PropertyType.IsArray)
{
    if(jValue != null)
        //https://stackoverflow.com/a/20769644/249895
        lastLevel[nesting[i]] = JArray.FromObject(jValue);
}
else
{
    if (prop.PropertyType.IsClass && prop.PropertyType != typeof(System.String))
    {
        if (jValue != null)
            lastLevel[nesting[i]] = JValue.FromObject(jValue);
    }
    else
    {
        lastLevel[nesting[i]] = new JValue(jValue);
    }
}


来源: stackexchange

问:
How to make sure initial replication is completed for a new node (Apache Ignite)?
Here is a use case:

I have version 1 of a web app deployed.

It uses couple Ignite-powered distributed (configured for replication) Maps, Sets and other data structures.

I'm going to deploy v2 of this application and once data is replicated I'm going to shutdown v1 of this app and re-route users (using nginx) to new instance (v2).

I can see that Ignite on v1 and v2 can discover each other and automatically perform replication of data structures.

My intention: I don't want to shutdown 1st instance (v1) before all data is replicated to 2nd instance (v2).

Question is: how do I know if initial replication is completed? Is there any event that is fired in such cases, or maybe some other way to accomplish this task?

答:
If you configure you caches to use synchronous rebalancing [1], second node will not complete start process before rebalancing is completed. This way you will guarantee that all the data is replicated to the second node (of course, assuming that you're using fully replicated caches).

[1] https://apacheignite.readme.io/docs/rebalancing#section-rebalance-modes

ContentLicense: CC BY-SA 3.0


问:
NHibernate <timestamp> mapping for Oracle database causes StaleStateException
We have an NHibernate app that we are migrating from SQL Server to Oracle. Our optimistic concurrency is implemented via a <timestamp name="Version"> mapping element.

The data type of the corresponding Version column in Oracle is DATE. After we save an object, the in-memory C# object is left with a timestamp value in milliseconds (e.g. 12:34:56.789) while the value in the database is precise only to the second (e.g. 12:34:56). Thus, if we attempt to save the object a 2nd time, we get a StaleStateException because the two values do not match.

I attempted to fix this by altering the data type of the Version column to TIMESTAMP(3). Unfortunately, the C# object and the DB value are still off by one millisecond (e.g. 12:34:56.789 vs 12:34:56.788), so the 2nd attempt to save the object still causes a StaleStateException.

What can I do to create a working <timestamp> mapping to an Oracle column of type DATE or TIMESTAMP so that the same object can be saved multiple times?

Thanks.

-- Brian

答: TIMESTAMP(7) has the correct precision to match the .NET DateTime class and fixed the problem.</p>

ContentLicense: CC BY-SA 2.5


问:
How to render list of instances without losing state/recreating component?
Experimenting with making my own React router with some animations. Hit a brick wall.

I'm rendering a stack of screens.

The stack can be popped or pushed.

My problem is that when the stack changes the state is lost and the constructor is called again destroying the previous state (making the stack useless) .
How would I do this?

Create the screen (After this we push to the stack which is on the state)

```<code>/**
 * Create a new React.Element as a screen and pass props.
 */
createNewScreen = (screenName: string, props: ?any = {}): any => {

    // Props is not an object.
    if (typeof props !== 'object') {
        Logger.error(`Passed props to screen name ${screenName} wasn't an object or undefined. Will error next screens.`);
        return;
    }

    let propsUnlocked = JSON.parse(JSON.stringify(props));

    // Add unique screen it.
    const uniqueScreenKey = this.generateRandomUniqueID();
    propsUnlocked.key = uniqueScreenKey;
    propsUnlocked.screenId = uniqueScreenKey;
    propsUnlocked.navKing = this;
    propsUnlocked.screenName = screenName;

    // Find the original screen to copy from.
    // This just copies the 'type'
    // $FlowFixMe
    return React.createElement(this.findScreenNameComponent(screenName).type, propsUnlocked);
}
</code>```

Render the screens

```<code>render() {
    return ( <View
            {...this.props}
            onLayout={(event) => this.onLayout(event)}
            pointerEvents={this.state.isAnimating ? 'none' : undefined}
            >
        { this.renderStackOfScreens() }
    </View>);
};

renderStackOfScreens() {
    // Render screens.
    return this.state.stackOfScreens
    .map((eachScreen, index) => {

        // Render second last screen IF animating. Basically because we have a screen animating over the top.
        if (index === this.state.stackOfScreens.length - 2 && this.state.isAnimating) {
            return (
                <Animated.View
                    key={eachScreen.props.screenId + '_parent'}
                    style={{ position: 'absolute', top: 0, left: 0, right: 0, bottom: 0 }}>
                    { eachScreen }
                </Animated.View>
            );
        }

        // Render last screen which is animated.
        if (index === this.state.stackOfScreens.length - 1) {
            return (
                <Animated.View
                    key={eachScreen.props.screenId + '_parent'}
                    style={this.getOffset(this.state.animatedScreenOffset)}>
                    { eachScreen }
                </Animated.View>
            );
        }
    })
    // Remove the undefined values.
    .filter((eachScreen) => !!eachScreen);
}
</code>```

Can see the full example here
https://pastebin.com/BbazipKt

Screen types are passed in as unique children.

答:
Once a component is unmounted, its state is gone forever. You might think "well I have a variable reference to the component so even though it's unmounted it still keeps its state, right?" Nope, React doesn't work that way. Unmounting a component is tantamount to destroying it. Even if you remount the "same" component again, as far as React is concerned it's a brand new component, with a brand new constructor call, mounting lifecycle, etc. So you need to abandon your approach of keeping the React components themselves in arrays as the history stack.

Frustrating, I know. Believe me, I've run into the same problem.

The solution is to pull out your View/Screen states from the components themselves and lift them into a parent. In essence, you're keeping the states in an array in the parent, and then passing them as props into the Views/Screens themselves. This might seem like a counter-intuitive, "non-Reactful" way of doing things, but it actually is in line with how React is intended to be used. State should generally be "lifted up" to the level of the closest common ancestor that all components will need access to it from. In this case, you need access to your state at a level above the Views/Screens themselves, so you need to lift it up.

Here's some pseudocode to illustrate.

Right now, your app seems to be structured sorta like this:

```<code>// App state
state: {
  // stackOfScreens is React components.
  // This won't work if you're trying to persist state!
  stackOfScreens: [
    <Screen />,
    <Screen />,
    <Screen />
  ]
}

// App render function
render() {
  return <div>
    {
      this.state.stackOfScreens.map((ea, i) => {
        return <View key={i} >{ea}</View>
      }
    }
  </div>
}
</code>```

Instead it should be like this:

```<code>// App state
state: {
  // stackOfScreens is an array of JS objects.
  // They hold your state in a place that is persistent,
  // so you can modify it and render the resulting
  // React components arbitrarily
  stackOfScreens: [
    {
      name: "screen#1",
      foo: "Some sort of 'screen' state",
      bar: "More state,
      baz: "etc."
    },
    {
      name: "screen#2",
      foo: "Some sort of 'screen' state",
      bar: "More state,
      baz: "etc."
    },
    {
      name: "screen#3",
      foo: "Some sort of 'screen' state",
      bar: "More state,
      baz: "etc."
    },
  ]
}

// App render function
render() {
  return <div>
    {
      this.state.stackOfScreens.map((ea, i) => {
        return <View key={i} >
          <Screen stateData={ea} callback={this.screenCallback} />
        </View>
      }
    }
  </div>
}
</code>```

Notice the addition of a callback prop on the Screen components that you're rendering. Thats so that you can trigger changes to the rendered Screen "state" (which is actually tracked in the parent) from within the Screen.

Body:
Experimenting with making my own React router with some animations. Hit a brick wall.

I'm rendering a stack of screens.

The stack can be popped or pushed.

My problem is that when the stack changes the state is lost and the constructor is called again destroying the previous state (making the stack useless) .
How would I do this?

Create the screen (After this we push to the stack which is on the state)

/**
 * Create a new React.Element as a screen and pass props.
 */
createNewScreen = (screenName: string, props: ?any = {}): any => {

    // Props is not an object.
    if (typeof props !== 'object') {
        Logger.error(`Passed props to screen name ${screenName} wasn't an object or undefined. Will error next screens.`);
        return;
    }

    let propsUnlocked = JSON.parse(JSON.stringify(props));

    // Add unique screen it.
    const uniqueScreenKey = this.generateRandomUniqueID();
    propsUnlocked.key = uniqueScreenKey;
    propsUnlocked.screenId = uniqueScreenKey;
    propsUnlocked.navKing = this;
    propsUnlocked.screenName = screenName;

    // Find the original screen to copy from.
    // This just copies the 'type'
    // $FlowFixMe
    return React.createElement(this.findScreenNameComponent(screenName).type, propsUnlocked);
}

Render the screens

render() {
    return ( <View
            {...this.props}
            onLayout={(event) => this.onLayout(event)}
            pointerEvents={this.state.isAnimating ? 'none' : undefined}
            >
        { this.renderStackOfScreens() }
    </View>);
};

renderStackOfScreens() {
    // Render screens.
    return this.state.stackOfScreens
    .map((eachScreen, index) => {

        // Render second last screen IF animating. Basically because we have a screen animating over the top.
        if (index === this.state.stackOfScreens.length - 2 && this.state.isAnimating) {
            return (
                <Animated.View
                    key={eachScreen.props.screenId + '_parent'}
                    style={{ position: 'absolute', top: 0, left: 0, right: 0, bottom: 0 }}>
                    { eachScreen }
                </Animated.View>
            );
        }

        // Render last screen which is animated.
        if (index === this.state.stackOfScreens.length - 1) {
            return (
                <Animated.View
                    key={eachScreen.props.screenId + '_parent'}
                    style={this.getOffset(this.state.animatedScreenOffset)}>
                    { eachScreen }
                </Animated.View>
            );
        }
    })
    // Remove the undefined values.
    .filter((eachScreen) => !!eachScreen);
}

Can see the full example here
https://pastebin.com/BbazipKt

Screen types are passed in as unique children.

Body:
Once a component is unmounted, its state is gone forever. You might think "well I have a variable reference to the component so even though it's unmounted it still keeps its state, right?" Nope, React doesn't work that way. Unmounting a component is tantamount to destroying it. Even if you remount the "same" component again, as far as React is concerned it's a brand new component, with a brand new constructor call, mounting lifecycle, etc. So you need to abandon your approach of keeping the React components themselves in arrays as the history stack.

Frustrating, I know. Believe me, I've run into the same problem.

The solution is to pull out your View/Screen states from the components themselves and lift them into a parent. In essence, you're keeping the states in an array in the parent, and then passing them as props into the Views/Screens themselves. This might seem like a counter-intuitive, "non-Reactful" way of doing things, but it actually is in line with how React is intended to be used. State should generally be "lifted up" to the level of the closest common ancestor that all components will need access to it from. In this case, you need access to your state at a level above the Views/Screens themselves, so you need to lift it up.

Here's some pseudocode to illustrate.

Right now, your app seems to be structured sorta like this:

// App state
state: {
  // stackOfScreens is React components.
  // This won't work if you're trying to persist state!
  stackOfScreens: [
    <Screen />,
    <Screen />,
    <Screen />
  ]
}

// App render function
render() {
  return <div>
    {
      this.state.stackOfScreens.map((ea, i) => {
        return <View key={i} >{ea}</View>
      }
    }
  </div>
}

Instead it should be like this:

// App state
state: {
  // stackOfScreens is an array of JS objects.
  // They hold your state in a place that is persistent,
  // so you can modify it and render the resulting
  // React components arbitrarily
  stackOfScreens: [
    {
      name: "screen#1",
      foo: "Some sort of 'screen' state",
      bar: "More state,
      baz: "etc."
    },
    {
      name: "screen#2",
      foo: "Some sort of 'screen' state",
      bar: "More state,
      baz: "etc."
    },
    {
      name: "screen#3",
      foo: "Some sort of 'screen' state",
      bar: "More state,
      baz: "etc."
    },
  ]
}

// App render function
render() {
  return <div>
    {
      this.state.stackOfScreens.map((ea, i) => {
        return <View key={i} >
          <Screen stateData={ea} callback={this.screenCallback} />
        </View>
      }
    }
  </div>
}

Notice the addition of a callback prop on the Screen components that you're rendering. Thats so that you can trigger changes to the rendered Screen "state" (which is actually tracked in the parent) from within the Screen.


问:
Why does a File need to be mutable to call Read::read_to_string?
Here's a line from the 2nd edition Rust tutorial:

```<code>let mut f = File::open(filename).expect("file not found");
</code>```

I'm of the assumption that the file descriptor is a wrapper around a number that basically doesn't change and is read-only.

The compiler complains that the file cannot be borrowed mutably, and I'm assuming it's because the method read_to_string takes the instance as the self argument as mutable, but the question is "why"?  What is ever going to change about the file descriptor?  Is it keeping track of the cursor location or something?

error[E0596]: cannot borrow immutable local variable `fdesc` as mutable
  --> main.rs:13:5
   |
11 |     let fdesc = File::open(fname).expect("file not found");
   |         ----- consider changing this to `mut fdesc`
12 |     let mut fdata = String::new();
13 |     fdesc.read_to_string(&mut fdata)
   |     ^^^^^ cannot borrow mutably
```

<p>The whole source:</p>

```fn main() {
    let args: Vec<String> = env::args().collect();
    let query = &args[1];
    let fname = &args[2];
    println!("Searching for '{}' in file '{}'...", query, fname);

    let fdesc = File::open(fname).expect("file not found"); //not mut
    let mut fdata = String::new();
    fdesc.read_to_string(&mut fdata)
        .expect("something went wrong reading the file");

    println!("Found: \n{}", fdata);
}
```

答:
I'm assuming it's because the method read_to_string takes the instance as the self argument as mutable

Yes, that's correct:

```<code>fn read_to_string(&mut self, buf: &mut String) -> Result<usize>
</code>```

The trait method Read::read_to_string takes the receiver as a mutable reference because in general, that's what is needed to implement "reading" from something. You are going to change a buffer or an offset or something.

Yes, an actual File may simply contain an underlying file descriptor (e.g. on Linux or macOS) or a handle (e.g. Windows). In these cases, the operating system deals with synchronizing the access across threads. That's not even guaranteed though — it depends on the platform. Something like Redox might actually have a mutable reference in its implementation of File.

If the Read trait didn't accept a &mut self, then types like BufReader would have to use things like internal mutability, reducing the usefulness of Rust's references.

See also:

Why is it possible to implement Read on an immutable reference to File?

Body:
Here's a line from the 2nd edition Rust tutorial:

let mut f = File::open(filename).expect("file not found");

I'm of the assumption that the file descriptor is a wrapper around a number that basically doesn't change and is read-only.

The compiler complains that the file cannot be borrowed mutably, and I'm assuming it's because the method read_to_string takes the instance as the self argument as mutable, but the question is "why"?  What is ever going to change about the file descriptor?  Is it keeping track of the cursor location or something?

error[E0596]: cannot borrow immutable local variable `fdesc` as mutable
  --> main.rs:13:5
   |
11 |     let fdesc = File::open(fname).expect("file not found");
   |         ----- consider changing this to `mut fdesc`
12 |     let mut fdata = String::new();
13 |     fdesc.read_to_string(&mut fdata)
   |     ^^^^^ cannot borrow mutably

The whole source:

fn main() {
    let args: Vec<String> = env::args().collect();
    let query = &args[1];
    let fname = &args[2];
    println!("Searching for '{}' in file '{}'...", query, fname);

    let fdesc = File::open(fname).expect("file not found"); //not mut
    let mut fdata = String::new();
    fdesc.read_to_string(&mut fdata)
        .expect("something went wrong reading the file");

    println!("Found: \n{}", fdata);
}

Body:
I'm assuming it's because the method read_to_string takes the instance as the self argument as mutable

Yes, that's correct:

fn read_to_string(&mut self, buf: &mut String) -> Result<usize>

The trait method Read::read_to_string takes the receiver as a mutable reference because in general, that's what is needed to implement "reading" from something. You are going to change a buffer or an offset or something.

Yes, an actual File may simply contain an underlying file descriptor (e.g. on Linux or macOS) or a handle (e.g. Windows). In these cases, the operating system deals with synchronizing the access across threads. That's not even guaranteed though — it depends on the platform. Something like Redox might actually have a mutable reference in its implementation of File.

If the Read trait didn't accept a &mut self, then types like BufReader would have to use things like internal mutability, reducing the usefulness of Rust's references.

See also:

Why is it possible to implement Read on an immutable reference to File?


问:
Counting rows with a condition
i work with a table "ships" like this:

```<code>shipid
container1
container2
</code>```

shipid and container1 are always filled, container2 is optional.

This is my query for now:

```<code>SELECT COUNT(container1) FROM table
</code>```

How can i achieve that this query counts the amount of the container2's too?!

It must be a joined query made of those both queries:

```<code>SELECT COUNT(container1) FROM table
SELECT COUNT(container2) FROM table WHERE container2!=''
</code>```

Thanks for any hints!

答:
You can use SUM

```<code>SELECT
     SUM(container1) AS c1
    ,SUM(CASE WHEN container2 IS NOT NULL THEN 1 ELSE 0 END) AS c2
FROM ships
</code>```

Title: Counting rows with a condition

Body:
i work with a table "ships" like this:

shipid
container1
container2

shipid and container1 are always filled, container2 is optional.

This is my query for now:

SELECT COUNT(container1) FROM table

How can i achieve that this query counts the amount of the container2's too?!

It must be a joined query made of those both queries:

SELECT COUNT(container1) FROM table
SELECT COUNT(container2) FROM table WHERE container2!=''

Thanks for any hints!

Body:
You can use SUM

SELECT
     SUM(container1) AS c1
    ,SUM(CASE WHEN container2 IS NOT NULL THEN 1 ELSE 0 END) AS c2
FROM ships


问:
User lost ability to connect from remote app server
Server version: 5.5.54-0ubuntu0.14.04.1 (Ubuntu)

I had an issue where a user lost the ability to connect to the mysql server from a remote application server.

user is created as 'user'@'%'

user has all privileges on the db in question

user connects remotely from a cron job and runs a daily report, connectivity just seems to have disappeared

failed: Access denied for user 'user'@'host' (using password: YES)

After confirming I could connect locally and remotely from a different server - on a whim, I issued flush privileges; this immediately resolved the problem.

I am trying to understand why - what event would have caused the lost connectivity? Really just trying to be able to explain it.

答:
This problem has been resolved - ended up being a network issue that was contributing to intermittent connectivity issues - flush privileges, while appearing to resolve the problem actually was not part of the issue at all.

Thanks to everybody that took a look.


问:
Inheritance problem. How to create multiple instances of a base class?
I have a base class (PrintProviderBase). It holds some states (PrinterUnavailable, NoPaper, ...).

Then I inherit from this class : ColorPrintProvider, BlackAndWhitePrintProvider ...

I was assumed that if the base class has a property like this:

```<code>private PrintStateEnum State { get; set; }
</code>```

Then each child class (different print providers) have it's own state (though nothing is static). It seems one instance of the base class is shared among them while I meant to have a copy of the base class in each child class so the common functionality and state can be encapsulate into base class.

Now if a print provider goes into NoPaper state, other ones stop printing due to incorrect state. How can I change this behavior ?

答: Each instance of ColorPrintProvider and BlackAndWhitePrintProvider will have their own (and distinct) instance of the State value, although none of them will be able to access it unless you make it public or protected (or provide other properties or methods which expose it). In general the value would only be shared across instances if it were static.</p>

Body:
I have a base class (PrintProviderBase). It holds some states (PrinterUnavailable, NoPaper, ...).

Then I inherit from this class : ColorPrintProvider, BlackAndWhitePrintProvider ...

I was assumed that if the base class has a property like this:

private PrintStateEnum State { get; set; }

Then each child class (different print providers) have it's own state (though nothing is static). It seems one instance of the base class is shared among them while I meant to have a copy of the base class in each child class so the common functionality and state can be encapsulate into base class.

Now if a print provider goes into NoPaper state, other ones stop printing due to incorrect state. How can I change this behavior ?


问:
How to install a specific version of swiftlint?
I am trying to fix this error:

```<code>Error: swiftlint does not have a version "0.11.1" in the Cellar.
</code>```

by running this:

```<code>brew install swiftlint-0.11.1
</code>```

however this doesn't work, then I tried "brew search swiftlint", but nothing showed up.

Can anyone point to me the correct way to install swiftlint with a specific version?

答:
This involves a lot of steps, but anyway:

Find the Brew Formula for Swiftlint. It's here.

Now you'll need an older commit of Swift Lint, so you would normally click on the History tab and get to an older commit. However, GitHub might tell you that you need to clone the repo (git@github.com:Homebrew/homebrew-core.git) and then use git log master -- Formula/swiftlint.rb to find your older commit. I'll spare you the details of that.

Now you need a raw URL for an older commit. So the raw URL for the latest commit is https://raw.githubusercontent.com/Homebrew/homebrew-core/master/Formula/swiftlint.rb, but you would use https://github.com/Homebrew/homebrew-core/blob/COMMIT/Formula/swiftlint.rb

Now you can do a brew install directly using this older Swift Lint. In my case, I needed 0.15, so I used:

```<code>brew install https://raw.githubusercontent.com/Homebrew/homebrew-core/864095ea97b6d7dc88c772c7f9f36521cf81a77e/Formula/swiftlint.rb
</code>```

Body:
I am trying to fix this error:

Error: swiftlint does not have a version "0.11.1" in the Cellar.

by running this:

brew install swiftlint-0.11.1

however this doesn't work, then I tried "brew search swiftlint", but nothing showed up.

Can anyone point to me the correct way to install swiftlint with a specific version?

Body:
This involves a lot of steps, but anyway:

Find the Brew Formula for Swiftlint. It's here.

Now you'll need an older commit of Swift Lint, so you would normally click on the History tab and get to an older commit. However, GitHub might tell you that you need to clone the repo (git@github.com:Homebrew/homebrew-core.git) and then use git log master -- Formula/swiftlint.rb to find your older commit. I'll spare you the details of that.

Now you need a raw URL for an older commit. So the raw URL for the latest commit is https://raw.githubusercontent.com/Homebrew/homebrew-core/master/Formula/swiftlint.rb, but you would use https://github.com/Homebrew/homebrew-core/blob/COMMIT/Formula/swiftlint.rb

Now you can do a brew install directly using this older Swift Lint. In my case, I needed 0.15, so I used:

brew install https://raw.githubusercontent.com/Homebrew/homebrew-core/864095ea97b6d7dc88c772c7f9f36521cf81a77e/Formula/swiftlint.rb


问:
Search field and button
I have a search field and a button beside. It works totally fine and everything. But on mobile when you type in something and click on the phones keyboard "search" it goes to 404 error. But when i type in something and click on the "search button" it works. I just want to also to be able to click "search" on the phones keyboard without it going to 404.

This is my search field and button:

```<code><div id="search" class="search" style="margin-left: 20px;">
<input class="form-control" type="text" placeholder="Hvad leder du efter?.." name="search" value="<?php if(isset($search)) echo $search; ?>" />
<button type="submit" class="button-search"></button>
</code>```

I just dont understand why the "search button" works and not the "search" on phone keyboard

答:
hope this may help  by
adding form tag with action  attribute targeting  the current url or search page

```<code>function get_current_url()
{
        $ssl = false;
        $hostname = 'example.org';
        return ($ssl ? 'https' : 'http') . '://' . $hostname . $_SERVER['REQUEST_URI'];

}

$q = isset($_GET['q']) ? $_GET['q'] : false;
if($q !== false) {
     echo 'searching for :' . htmlspecialchars($q);
}

?>

<div id="search" class="search" style="margin-left: 20px;">
<form method='GET' action='<?= $get_current_url; ?>' >
<input class="form-control" type="text" placeholder="Search.." name="q" value="<?php if(isset($_GET['q'])) echo htmlspecialchars($_GET['q']); ?>" />
<input type="submit" value='Search' class="button-search"></button>
</form>
</div>
</code>```

Title: Search field and button

Body:
I have a search field and a button beside. It works totally fine and everything. But on mobile when you type in something and click on the phones keyboard "search" it goes to 404 error. But when i type in something and click on the "search button" it works. I just want to also to be able to click "search" on the phones keyboard without it going to 404.

This is my search field and button:

<input class="form-control" type="text" placeholder="Hvad leder du efter?.." name="search" value="<?php if(isset($search)) echo $search; ?>" />
<button type="submit" class="button-search"></button>

I just dont understand why the "search button" works and not the "search" on phone keyboard

Body:
hope this may help  by
adding form tag with action  attribute targeting  the current url or search page

function get_current_url()
{
        $ssl = false;
        $hostname = 'example.org';
        return ($ssl ? 'https' : 'http') . '://' . $hostname . $_SERVER['REQUEST_URI'];

}

$q = isset($_GET['q']) ? $_GET['q'] : false;
if($q !== false) {
     echo 'searching for :' . htmlspecialchars($q);
}

?>

<div id="search" class="search" style="margin-left: 20px;">
<form method='GET' action='<?= $get_current_url; ?>' >
<input class="form-control" type="text" placeholder="Search.." name="q" value="<?php if(isset($_GET['q'])) echo htmlspecialchars($_GET['q']); ?>" />
<input type="submit" value='Search' class="button-search"></button>
</form>
</div>


问:
How to make IntelliJ to propose "Create class" instead of "Add Maven dependency .."
I would like to know How to make IntelliJ to propose "Create class" instead to have "Add Maven Dependency ..." when I write a new class name.

See the print screen.

答: Type also field/variable name.

Body: Type also field/variable name.


问:
Compute the square root of 3 in C++
How can I compute the square root of 3 in C++ using the following relation?

Here is what I tried:

```<code>#include <iostream>
#include <cmath>

int main(void)
{
    double prevRes(1);
    double res(1 + 1./2);
    short i(2);

    while (abs(prevRes - res) > 1.e-14)
    {
        prevRes = res;

        res = i + 1 / res;

        i = 3 - i;
    }

    std::cout << res << std::endl;

    return 0;
}
</code>```

The program runs forever.

答:
It's a shame that this question wasn't asked with more effort and detail so that it was taken seriously.  I've always been confused by the appearance and concept of continued fractions, but it's been nice taking the time to think about them and implement one.

This particular one can be done iteratively.  As @wally states, the continued fraction shown in the question does not converge to sqrt(3), but to ~1.36603.  The two top-most coefficients should be 1.  Notice that sqrt(3) ~= 1 + (1/1.36603), and that all the coefficients in the continued fraction alternate.

So, if a loop works from the bottom up until the alternating continued fraction converges then one more calculation after the loop will give us the correct answer.  At each iteration the reciprocal of the current value is added to either 1 or 2.  The initial value can be anything.

```<code>#include <iostream>
#include <cmath>
#include <limits>

// Calculate square root of 3 with a continued fraction
int main(void) {
  int iterations = 0;
  double epsilon = 1.0e-12; //error bounds
  double prev = 0.0;
  double curr = 1.0; //initial estimate
  double error = curr - prev;

  // Don't show more precision than we have
  std::cout.precision(std::numeric_limits<double>::digits10);

  // Iterate the continued fraction [1;1,2,1,2...]
  // from the bottom up until it converges with errors
  // less than epsilon.
  while (std::abs(error) > epsilon) {
    prev = curr;
    // Unroll the loop with the repeating pattern here
    curr = 2 + (1/curr);
    curr = 1 + (1/curr);

    iterations++;
    error = curr - prev;
    std::cout << "error at iteration " << iterations
              << " was " << error << std::endl;
  }

  // The actual continued fraction we want to evaluate
  // is [1;1,1,2,1,2,...].
  // The two top-level coefficients are 1, so do
  // another half iteration here.
  curr = 1 + (1/curr);

  std::cout << "sqrt(3) = " << curr << " after "
            << iterations << " iterations" << std::endl;

  return 0;
}
</code>```

This strategy should work for any continued fraction with that ends in a repeating pattern of coefficients.

As for why the original code does not complete, I'll leave that to the author to figure out.  Print statements or a pocket calculator will help.

Title: Compute the square root of 3 in C++

Body:
How can I compute the square root of 3 in C++ using the following relation?

Here is what I tried:

#include <iostream>
#include <cmath>

int main(void)
{
    double prevRes(1);
    double res(1 + 1./2);
    short i(2);

    while (abs(prevRes - res) > 1.e-14)
    {
        prevRes = res;

        res = i + 1 / res;

        i = 3 - i;
    }

    std::cout << res << std::endl;

    return 0;
}

The program runs forever.

Body:
It's a shame that this question wasn't asked with more effort and detail so that it was taken seriously.  I've always been confused by the appearance and concept of continued fractions, but it's been nice taking the time to think about them and implement one.

This particular one can be done iteratively.  As @wally states, the continued fraction shown in the question does not converge to sqrt(3), but to ~1.36603.  The two top-most coefficients should be 1.  Notice that sqrt(3) ~= 1 + (1/1.36603), and that all the coefficients in the continued fraction alternate.

So, if a loop works from the bottom up until the alternating continued fraction converges then one more calculation after the loop will give us the correct answer.  At each iteration the reciprocal of the current value is added to either 1 or 2.  The initial value can be anything.

#include <iostream>
#include <cmath>
#include <limits>

// Calculate square root of 3 with a continued fraction
int main(void) {
  int iterations = 0;
  double epsilon = 1.0e-12; //error bounds
  double prev = 0.0;
  double curr = 1.0; //initial estimate
  double error = curr - prev;

  // Don't show more precision than we have
  std::cout.precision(std::numeric_limits<double>::digits10);

  // Iterate the continued fraction [1;1,2,1,2...]
  // from the bottom up until it converges with errors
  // less than epsilon.
  while (std::abs(error) > epsilon) {
    prev = curr;
    // Unroll the loop with the repeating pattern here
    curr = 2 + (1/curr);
    curr = 1 + (1/curr);

    iterations++;
    error = curr - prev;
    std::cout << "error at iteration " << iterations
              << " was " << error << std::endl;
  }

  // The actual continued fraction we want to evaluate
  // is [1;1,1,2,1,2,...].
  // The two top-level coefficients are 1, so do
  // another half iteration here.
  curr = 1 + (1/curr);

  std::cout << "sqrt(3) = " << curr << " after "
            << iterations << " iterations" << std::endl;

  return 0;
}

This strategy should work for any continued fraction with that ends in a repeating pattern of coefficients.

As for why the original code does not complete, I'll leave that to the author to figure out.  Print statements or a pocket calculator will help.


问:
Use While Loop With setTimeout
I have making a text-based space rpg game. In the battle system, the player and AI take turns firing at each other. I can't figure out how to make the system loop with a while loop without making the browser crash via infinite loop. Here is my code:

```<code>function battle(enemy) {
var battleOver = false;
console.log(enemy.name + " appears!");
//problem loop here.
while(battleOver === false){
console.log("This enemy has " + enemy.health + " health.");
for (var i = 0; i < userWeapons.length; i++) {
    var ibumped = i + 1;
    console.log("Press " + ibumped + " to fire the " + userWeapons[i].name + ".");
}
var weaponChosen;
setTimeout(function() {
    var weaponChoice = prompt("Which weapon do you choose?");
    switch (weaponChoice) {
        case 1:
            weaponChosen = userWeapons[0];
            console.log(userWeapons[0].name + " chosen.");
            break;
        case 2:
            weaponChosen = userWeapons[1];
            console.log(userWeapons[1].name + " chosen.");
            break;
        default:
            weaponChosen = userWeapons[0];
            console.log(userWeapons[0].name + " chosen.");

    };
}, 1000);
setTimeout(function() {
    if (enemy.shields > 0 && weaponChosen.ignoreShield === false) {
        enemy.shields = enemy.shields - weaponChosen.damage;
        weaponChosen.fire(enemy);
        if (enemy.shields < 0) {
            enemy.health = enemy.health + enemy.shields;
            console.log("Enemy shields destroyed and enemy took " + -1 * enemy.shields + " damage!")
        } else {
            console.log("Enemy shields have been reduced to " + enemy.shields + ".");
        }
    } else {
        enemy.health = enemy.health - weaponChosen.damage;
        weaponChosen.fire(enemy);
        console.log("Enemy takes " + weaponChosen.damage + " damage!");
    }
    if (enemy.health <= 0 && battleOver === false) {
        console.log("Enemy destroyed!");
        battleOver = true;
    }
}, 3000);
setTimeout(function() {
    if (enemy.health > 0 && battleOver === false) {
        if (enemy.weapons != null) {
            console.log(enemy.weapons.name + " fired at you.");
            health = health - enemy.weapons.damage;
            console.log("You have " + health + " health left.");
            if (health <= 0) {
                console.log("Game over... You were destroyed");
                battleOver = true;
            }
        } else {
            console.log("The enemy did nothing...");
        }
    };
}, 5000);
}
}
</code>```

All help is appreciated!

答:
I would take that loop out and use a recursive call on the end of the interactions.<br>
Let's say: </p>

```<code>function battle(enemy) {
   //All your code here
   if (HeroAlive) {
     battle(enemy);
   }
}
</code>```

Title: Use While Loop With setTimeout

Body:
I have making a text-based space rpg game. In the battle system, the player and AI take turns firing at each other. I can't figure out how to make the system loop with a while loop without making the browser crash via infinite loop. Here is my code:

function battle(enemy) {
var battleOver = false;
console.log(enemy.name + " appears!");
//problem loop here.
while(battleOver === false){
console.log("This enemy has " + enemy.health + " health.");
for (var i = 0; i < userWeapons.length; i++) {
    var ibumped = i + 1;
    console.log("Press " + ibumped + " to fire the " + userWeapons[i].name + ".");
}
var weaponChosen;
setTimeout(function() {
    var weaponChoice = prompt("Which weapon do you choose?");
    switch (weaponChoice) {
        case 1:
            weaponChosen = userWeapons[0];
            console.log(userWeapons[0].name + " chosen.");
            break;
        case 2:
            weaponChosen = userWeapons[1];
            console.log(userWeapons[1].name + " chosen.");
            break;
        default:
            weaponChosen = userWeapons[0];
            console.log(userWeapons[0].name + " chosen.");

    };
}, 1000);
setTimeout(function() {
    if (enemy.shields > 0 && weaponChosen.ignoreShield === false) {
        enemy.shields = enemy.shields - weaponChosen.damage;
        weaponChosen.fire(enemy);
        if (enemy.shields < 0) {
            enemy.health = enemy.health + enemy.shields;
            console.log("Enemy shields destroyed and enemy took " + -1 * enemy.shields + " damage!")
        } else {
            console.log("Enemy shields have been reduced to " + enemy.shields + ".");
        }
    } else {
        enemy.health = enemy.health - weaponChosen.damage;
        weaponChosen.fire(enemy);
        console.log("Enemy takes " + weaponChosen.damage + " damage!");
    }
    if (enemy.health <= 0 && battleOver === false) {
        console.log("Enemy destroyed!");
        battleOver = true;
    }
}, 3000);
setTimeout(function() {
    if (enemy.health > 0 && battleOver === false) {
        if (enemy.weapons != null) {
            console.log(enemy.weapons.name + " fired at you.");
            health = health - enemy.weapons.damage;
            console.log("You have " + health + " health left.");
            if (health <= 0) {
                console.log("Game over... You were destroyed");
                battleOver = true;
            }
        } else {
            console.log("The enemy did nothing...");
        }
    };
}, 5000);
}
}

All help is appreciated!

Body:
I would take that loop out and use a recursive call on the end of the interactions.

Let's say:

function battle(enemy) {
   //All your code here
   if (HeroAlive) {
     battle(enemy);
   }
}


问:
Populating a FlowLayoutPanel with a large number of controls and painting thumbnails on demand
I'm trying to make an ImageListBox kind of control that will display a large numbers of thumbnails, like the one that Picasa uses.

This is my design:

I have a FlowLayoutPanel that is populated with a lot of UserControl objects, for example 4,000.
Each UserControl is assigned a delegate for the Paint event.
When the Paint event is called, it checks a memory cache for the thumbnail and if the image is not in cache, it retrieves it from the disk.

I have two problems that I'm trying to solve:

It seems that WinForms will trigger a Paint event even if the UserControl is not in view. Only 10 or so controls are in fact in view, the rest are not (the FlowLayoutPanel.AutoScroll is set to true). As a result, it tries to retrieve thumbnails for all the images and that takes a long time.

Adding the UserControl objects to the FlowLayoutPanel takes a somewhat long time, about 2-3 seconds. I can live with it but I'm wondering if there is a better way to do it than:

```<code>UserControl[] boxes = new UserControl[N];
// populate array
panel.SuspendLayout();
panel.Controls.AddRange(boxes);
panel.ResumeLayout();
</code>```

答:
To improve the speed of populating the FlowLayoutPanel with your user controls, disable layout updating while you add the controls.

Immediately before your loop, call SuspendLayout() and then at the end call ResumeLayout(). Make sure to use a try-finally to guarantee the ResumeLayout() runs even if an exception occurs.

OwnerDisplayName: everwicked

Body:
I'm trying to make an ImageListBox kind of control that will display a large numbers of thumbnails, like the one that Picasa uses.

This is my design:

I have a FlowLayoutPanel that is populated with a lot of UserControl objects, for example 4,000.
Each UserControl is assigned a delegate for the Paint event.
When the Paint event is called, it checks a memory cache for the thumbnail and if the image is not in cache, it retrieves it from the disk.

I have two problems that I'm trying to solve:

It seems that WinForms will trigger a Paint event even if the UserControl is not in view. Only 10 or so controls are in fact in view, the rest are not (the FlowLayoutPanel.AutoScroll is set to true). As a result, it tries to retrieve thumbnails for all the images and that takes a long time.

Adding the UserControl objects to the FlowLayoutPanel takes a somewhat long time, about 2-3 seconds. I can live with it but I'm wondering if there is a better way to do it than:

UserControl[] boxes = new UserControl[N];
// populate array
panel.SuspendLayout();
panel.Controls.AddRange(boxes);
panel.ResumeLayout();

OwnerDisplayName: Bevan


问:
Design a language L such that neither L nor its complement has an infinite regular subset?
I'm having a class on automata theory, and right now we are learning the pumping lemma. There is an exercise question asking us to "Design a language L such that neither L nor its complement has an infinite regular subset?" But I don't understand the question. What is an infinite regular subset? How should I find a language that can meet this requirement?

Can anyone shed some light on this question?

Thanks!

答:
More precisely, you need to find a language L so that there is no subset of L that is a infinite regular language and there is no subset of the complement of L that is an infinite regular language.

Here's an incorrect example: L = the union of a^n and a^n b^n.  Since a^n is a regular language and it is a subset of L, this wouldn't work for the answer.

For finding a L that meets the requirements, I've found that these kind of questions are more like puzzles.  You try some things out, check if they work or not, and try to think about why they don't solve the problem.  Eventually you get your mind around the situation and come up with a solution.


问:
How do i make my reusable react component saves when the user clicks button?
My component this.props.save(); when componentWillUnmount? however if i leave the page to an external link in a different tab it does not trigger componentWillUnmount

my component

export default class AutoSave extends React.Component {

  constructor(props) {
    super(props);
    this.setIntervalId = null;
  }

  componentDidMount() {
    if (!window.onbeforeunload) {
      window.onbeforeunload = () => {
        this.props.save();
      };
    }

    this.setIntervalId = setInterval(() => this.props.save(), this.props.intervalInMs);
  }

  componentWillUnmount() {
    this.props.save();
    clearInterval(this.setIntervalId);
  }

  render() {

    return Last saved at {now()};
  }
}```
</div>
</div>
</p>

<p>My link looks like this </p>

```<Link href="http://www.google.com"  target="_blank">
      Google Link
    </Link>
```

How can I make component save when user clicks link? It's a react/redux app.

答:
Opening a new tab will not trigger componentWillUnmount() nor onbeforeunload. In both cases because your app is still open in the original tab. React does not unmount components immediately before you close or navigate away from the page, so componentWillUnmount() would do nothing even if the page were to close. onbeforeunload only triggers when you navigate away from the page in the same tab, or close the tab/window.

If you want to reliably call this.props.save() every time the user clicks your button, then simply add an onClick handler to the button.

```<code>render() {
  return <span onClick={this.props.save} className="saving">Last saved at {now()}</span>;
}
</code>```

Body:
My component this.props.save(); when componentWillUnmount? however if i leave the page to an external link in a different tab it does not trigger componentWillUnmount

my component

export default class AutoSave extends React.Component {

  constructor(props) {
    super(props);
    this.setIntervalId = null;
  }

  componentDidMount() {
    if (!window.onbeforeunload) {
      window.onbeforeunload = () => {
        this.props.save();
      };
    }

    this.setIntervalId = setInterval(() => this.props.save(), this.props.intervalInMs);
  }

  componentWillUnmount() {
    this.props.save();
    clearInterval(this.setIntervalId);
  }

  render() {

    return Last saved at {now()};
  }
}

My link looks like this

<Link href="http://www.google.com"  target="_blank">
      Google Link
    </Link>

How can I make component save when user clicks link? It's a react/redux app.

Body:
Opening a new tab will not trigger componentWillUnmount() nor onbeforeunload. In both cases because your app is still open in the original tab. React does not unmount components immediately before you close or navigate away from the page, so componentWillUnmount() would do nothing even if the page were to close. onbeforeunload only triggers when you navigate away from the page in the same tab, or close the tab/window.

If you want to reliably call this.props.save() every time the user clicks your button, then simply add an onClick handler to the button.

render() {
  return <span onClick={this.props.save} className="saving">Last saved at {now()}</span>;
}


问:
Angular(5) - Login button not changing to Logout on successful login
I'm using Auth0's API to handle user management. Everything is working as intended - On Login() it properly stores local. On Logout() it properly removes them.

However, the actual Login button is not becoming Logout automatically on success - It is when I hard-refresh the page, but not directly. I believe this is an issue with my binding?

Header component

```<code>  authenticated: boolean; // Wasn't sure how else to filter in front-end

  constructor(private authService: AuthService) { }

  ngOnInit() {
    this.authenticated = this.authService.isAuthenticated()
  }

  login() {
    this.authService.login();
  }

  logout() {
    this.authService.logout();
  }

}
</code>```

HTML For Header

```<code>  <li class="nav-item">
    <a class="nav-link waves-light" *ngIf="!authenticated" mdbRippleRadius (click)="login()"><i class="fa fa-user"></i> <span class="clearfix d-none d-sm-inline-block">Log In</span></a>
    <a class="nav-link waves-light" *ngIf="authenticated" mdbRippleRadius (click)="logout()"><i class="fa fa-user"></i> <span class="clearfix d-none d-sm-inline-block">Log Out</span></a>
  </li>
</code>```

The docs said to use auth.isAuthenticated() which would call the function from the service

```<code>  public isAuthenticated(): boolean {
    // Check whether the current time is past the
    // access token's expiry time
    const expiresAt = JSON.parse(localStorage.getItem('expires_at'));
    return new Date().getTime() < expiresAt;
  }
</code>```

I was thinking perhaps I should append this.authenticated = this.authService.isAuthenticated() to the end of each login()/logout() function in the header component, but I'm feeling like I'm going the wrong direction with this.

Welcome any input.

Update

Modifying logout() to call this.authenticated = this.authService.isAuthenticated() did resolve the issue for it, but Login is still not becoming Log Out until I refresh the page.

答:
From what I can see you’re only updating your variable on init. That’s why you only see the changes when you refresh. If you do

```<code>login() {
this.authService.login();
this.authenticated = this.authService.isAuthenticated()
  }
</code>```

Inside the login method it should work.

Body:
I'm using Auth0's API to handle user management. Everything is working as intended - On Login() it properly stores local. On Logout() it properly removes them.

However, the actual Login button is not becoming Logout automatically on success - It is when I hard-refresh the page, but not directly. I believe this is an issue with my binding?

Header component

  authenticated: boolean; // Wasn't sure how else to filter in front-end

  constructor(private authService: AuthService) { }

  ngOnInit() {
    this.authenticated = this.authService.isAuthenticated()
  }

  login() {
    this.authService.login();
  }

  logout() {
    this.authService.logout();
  }

}

HTML For Header

     Log In
     Log Out

The docs said to use auth.isAuthenticated() which would call the function from the service

  public isAuthenticated(): boolean {
    // Check whether the current time is past the
    // access token's expiry time
    const expiresAt = JSON.parse(localStorage.getItem('expires_at'));
    return new Date().getTime() < expiresAt;
  }

I was thinking perhaps I should append this.authenticated = this.authService.isAuthenticated() to the end of each login()/logout() function in the header component, but I'm feeling like I'm going the wrong direction with this.

Welcome any input.

Update

Modifying logout() to call this.authenticated = this.authService.isAuthenticated() did resolve the issue for it, but Login is still not becoming Log Out until I refresh the page.

Body:
From what I can see you’re only updating your variable on init. That’s why you only see the changes when you refresh. If you do

login() {
this.authService.login();
this.authenticated = this.authService.isAuthenticated()
  }

Inside the login method it should work.


问:
matplotlib histogram with line
```<code>import matplotlib.image as mpimg
from scipy.spatial import distance
import matplotlib.patches as mpatches
import pylab
import matplotlib.mlab as mlab
import scipy.stats as ss

fig = plt.figure(num=None, figsize=(9, 7), facecolor='w', edgecolor='k')
ax = fig.add_subplot(111)
plt.hist(h, bins=30, normed=True)    #h is the data
</code>```

right now my plot looks like this:

I want to add a trend line to reflect the histogram. To reflect the peak of each bin.  So tried what fuglede suggested, using seaborn, I got something that is really weird.

I dont know why suddenly with the seaborn imported, my plot has those weird grey grids going on. I'm using Sypder btw.
Second, I want to have a smooth like, not like the one I have right now just going up and down.

答:
It sounds like you might be looking for something like a kernel density estimate. An off-the-shelf KDE calculator/plotter with a simple API is available in Seaborn.

```<code>import numpy as np
import seaborn as sns

data = np.random.normal(0, 1, 100)
sns.distplot(data)
</code>```

Title: matplotlib histogram with line

Body:
import matplotlib.image as mpimg
from scipy.spatial import distance
import matplotlib.patches as mpatches
import pylab
import matplotlib.mlab as mlab
import scipy.stats as ss

fig = plt.figure(num=None, figsize=(9, 7), facecolor='w', edgecolor='k')
ax = fig.add_subplot(111)
plt.hist(h, bins=30, normed=True)    #h is the data

right now my plot looks like this:

I want to add a trend line to reflect the histogram. To reflect the peak of each bin.  So tried what fuglede suggested, using seaborn, I got something that is really weird.

I dont know why suddenly with the seaborn imported, my plot has those weird grey grids going on. I'm using Sypder btw.
Second, I want to have a smooth like, not like the one I have right now just going up and down.

Body:
It sounds like you might be looking for something like a kernel density estimate. An off-the-shelf KDE calculator/plotter with a simple API is available in Seaborn.

import numpy as np
import seaborn as sns

data = np.random.normal(0, 1, 100)
sns.distplot(data)


问:
RIPEMD-160 vs SHA-256
Can anyone shed some light into SHA-256 and RIPEMD-160, which algorithm is normally faster and what are the performance and space comparisons, if any?
By space comparisons I don't mean 160 bits and 256 bits, but what are the collisions frequency, difference in space requirements in production env. and time to calculate both.
Is RIPEMD-160 a requirement for European countries?
Any additional information, that would be helpful in deciding.</p>

答:
RIPMD-160 can be used to any message size while SHA is limited to 2^64-1.
and RIPMD-160 takes 160 steps during the process whereas SHA takes only 80.
as I think RIPMD-160 is better.

Title: RIPEMD-160 vs SHA-256


问:
set base URL dynamicaly in Laravel 5
I have two versions of a site one running at on example.com
and other at example.com/version2.

In web.php I have

```<code>    Route::group(['middleware'=>['webconfig'],'prefix'=>'version2'], function(){
        //Routes for version2 site
    });
// Routes for main site
</code>```

In webconfig middleware I set database connection for version2 site. Which is working fine but I am also setting base URL for version2 site. which not working url() method returns example.com
Here is my webconfig middleware

```<code>public function handle($request, Closure $next)
{
    \Config::set('database.default', 'mysql_us');
    \Config::set('app.url', url('version2'));
    return $next($request);
}
</code>```

So how can I set base url dynamicaly.

答: In your .env file specify APP_URL=http://example.com/version2</p>

ContentLicense: CC BY-SA 4.0

Title: set base URL dynamicaly in Laravel 5

Body:
I have two versions of a site one running at on example.com
and other at example.com/version2.

In web.php I have

    Route::group(['middleware'=>['webconfig'],'prefix'=>'version2'], function(){
        //Routes for version2 site
    });
// Routes for main site

In webconfig middleware I set database connection for version2 site. Which is working fine but I am also setting base URL for version2 site. which not working url() method returns example.com
Here is my webconfig middleware

public function handle($request, Closure $next)
{
    \Config::set('database.default', 'mysql_us');
    \Config::set('app.url', url('version2'));
    return $next($request);
}

So how can I set base url dynamicaly.


问:
dplyr differences between pairs in nested groups
I'd like to use dplyr to calculate differences in value between people nested in pair by session.

```<code>dat <- data.frame(person=c(rep(1, 10),
                           rep(2, 10),
                           rep(3, 10),
                           rep(4, 10),
                           rep(5, 10),
                           rep(6, 10),
                           rep(7, 10),
                           rep(8, 10)),
                  pair=c(rep(1, 20),
                         rep(2, 20),
                         rep(3, 20),
                         rep(4, 20)),
                  condition=c(rep("NEW", 10),
                              rep("OLD", 10),
                              rep("NEW", 10),
                              rep("OLD", 10),
                              rep("NEW", 10),
                              rep("OLD", 10),
                              rep("NEW", 10),
                              rep("OLD", 10)),
                  session=rep(seq(from=1, to=10, by=1), 8),
                  value=c(0, 2, 4, 8, 16, 16, 18, 20, 20, 20,
                          0, 1, 1, 2, 4, 5, 8, 12, 15, 15,
                          0, 2, 8, 10, 15, 16, 18, 20, 20, 20,
                          0, 4, 4, 6, 6, 8, 10, 12, 12, 18,
                          0, 6, 8, 10, 16, 16, 18, 20, 20, 20,
                          0, 2, 2, 3, 4, 8, 8, 8, 10, 12,
                          0, 10, 12, 16, 18, 18, 18, 20, 20, 20,
                          0, 2, 2, 8, 10, 10, 11, 12, 15, 20)
                  )
</code>```

For instance, person 1 and 2 make a pair (pair==1):

person==1 & session==2: 2

person==2 & session==2: 1

Difference (NEW-OLD) is 2-1=1.

Here's what I have tried so far. I think I need to group_by() first and then summarise(), but I have not cracked this nut.

```<code>dat %>%
    mutate(session = factor(session)) %>%
    group_by(condition, pair, session) %>%
    summarise(pairDiff = value-first(value))
</code>```

Desired output:

答:
You can spread condition to headers and then do the subtraction NEW - OLD:

```<code>library(dplyr); library(tidyr)

dat %>%
    select(-person) %>%
    spread(condition, value) %>%
    mutate(diff = NEW - OLD) %>%
    select(session, pair, diff)

# A tibble: 40 x 3
#   session  pair  diff
#     <dbl> <dbl> <dbl>
# 1       1     1     0
# 2       2     1     1
# 3       3     1     3
# 4       4     1     6
# 5       5     1    12
# 6       6     1    11
# 7       7     1    10
# 8       8     1     8
# 9       9     1     5
#10      10     1     5
# ... with 30 more rows
</code>```

Body:
I'd like to use dplyr to calculate differences in value between people nested in pair by session.

dat <- data.frame(person=c(rep(1, 10),
                           rep(2, 10),
                           rep(3, 10),
                           rep(4, 10),
                           rep(5, 10),
                           rep(6, 10),
                           rep(7, 10),
                           rep(8, 10)),
                  pair=c(rep(1, 20),
                         rep(2, 20),
                         rep(3, 20),
                         rep(4, 20)),
                  condition=c(rep("NEW", 10),
                              rep("OLD", 10),
                              rep("NEW", 10),
                              rep("OLD", 10),
                              rep("NEW", 10),
                              rep("OLD", 10),
                              rep("NEW", 10),
                              rep("OLD", 10)),
                  session=rep(seq(from=1, to=10, by=1), 8),
                  value=c(0, 2, 4, 8, 16, 16, 18, 20, 20, 20,
                          0, 1, 1, 2, 4, 5, 8, 12, 15, 15,
                          0, 2, 8, 10, 15, 16, 18, 20, 20, 20,
                          0, 4, 4, 6, 6, 8, 10, 12, 12, 18,
                          0, 6, 8, 10, 16, 16, 18, 20, 20, 20,
                          0, 2, 2, 3, 4, 8, 8, 8, 10, 12,
                          0, 10, 12, 16, 18, 18, 18, 20, 20, 20,
                          0, 2, 2, 8, 10, 10, 11, 12, 15, 20)
                  )

For instance, person 1 and 2 make a pair (pair==1):

person==1 & session==2: 2

person==2 & session==2: 1

Difference (NEW-OLD) is 2-1=1.

Here's what I have tried so far. I think I need to group_by() first and then summarise(), but I have not cracked this nut.

dat %>%
    mutate(session = factor(session)) %>%
    group_by(condition, pair, session) %>%
    summarise(pairDiff = value-first(value))

Desired output:

Body:
You can spread condition to headers and then do the subtraction NEW - OLD:

library(dplyr); library(tidyr)

dat %>%
    select(-person) %>%
    spread(condition, value) %>%
    mutate(diff = NEW - OLD) %>%
    select(session, pair, diff)

# A tibble: 40 x 3
#   session  pair  diff
#     <dbl> <dbl> <dbl>
# 1       1     1     0
# 2       2     1     1
# 3       3     1     3
# 4       4     1     6
# 5       5     1    12
# 6       6     1    11
# 7       7     1    10
# 8       8     1     8
# 9       9     1     5
#10      10     1     5
# ... with 30 more rows


问:
Sql query searching for the first three letters
My Sql query is not correct. I want to create a query that searches for companies whose first three characters are equal to the given parameter

```<code>@NamedNativeQuery(
    name="Company.retrieveNameCompanyForFirstThreeChar",
    query =" SELECT SUBSTRING(company_name, 1, 3) AS keyword from companies
    WHERE = :KEYWORD",
    resultClass = Company.class
)
</code>```

My error:

org.springframework.dao.InvalidDataAccessResourceUsageException:
  could not extract ResultSet; SQL [n/a]; nested exception is
  org.hibernate.exception.SQLGrammarException: could not extract
  ResultSet

答:
Try this:

```<code>SELECT company_name
FROM companies
WHERE SUBSTRING(company_name FROM 1 FOR 3) = :KEYWORD;
</code>```

You may want to add a TRIM() function around "company_name" in case of blank spaces.

Body:
My Sql query is not correct. I want to create a query that searches for companies whose first three characters are equal to the given parameter

@NamedNativeQuery(
    name="Company.retrieveNameCompanyForFirstThreeChar",
    query =" SELECT SUBSTRING(company_name, 1, 3) AS keyword from companies
    WHERE = :KEYWORD",
    resultClass = Company.class
)

My error:

org.springframework.dao.InvalidDataAccessResourceUsageException:
  could not extract ResultSet; SQL [n/a]; nested exception is
  org.hibernate.exception.SQLGrammarException: could not extract
  ResultSet

Body:
Try this:

SELECT company_name
FROM companies
WHERE SUBSTRING(company_name FROM 1 FOR 3) = :KEYWORD;

You may want to add a TRIM() function around "company_name" in case of blank spaces.


问:
Inheritance of private inner class
I want to implement Serializable into a class, but I am not allowed to modify it. My idea was to make another class which inherits from the other class. But the original class is built like this:

```<code>public class ClassName {

    private class InnerClass{
        private InnerClass(){
            //do stuff
        }
    }

    public ClassName(){
        //do stuff
    }
}
</code>```

So following does not work because InnerClass is private thus not visible:

```<code>import java.io.Serializable;

public class ClassTwo extends ClassName implements Serializable{

    private class InnerClass extends ClassName.InnerClass implements Serializable {
        private InnerClass(){
            super();
        }
    }

    public ClassTwo(){
        super();
    }
}
</code>```

Is there a way to implement Serializable into ClassName without changing the original class?

答:
If you have read/write access to all the slots you care to serialize, you can create an adapter class.

```<code>public class MyClassAdapter implements Serializable {
    private MyClass instance;
    ...
}
</code>```

Then just wrap the instance in this adapter class before serializing, and extract it after deserializing.

If you don't have read/write access to the slots, there's probably a good reason for that, and serializing data you don't own is a bad idea.

Title: Inheritance of private inner class

Body:
I want to implement Serializable into a class, but I am not allowed to modify it. My idea was to make another class which inherits from the other class. But the original class is built like this:

public class ClassName {

    private class InnerClass{
        private InnerClass(){
            //do stuff
        }
    }

    public ClassName(){
        //do stuff
    }
}

So following does not work because InnerClass is private thus not visible:

import java.io.Serializable;

public class ClassTwo extends ClassName implements Serializable{

    private class InnerClass extends ClassName.InnerClass implements Serializable {
        private InnerClass(){
            super();
        }
    }

    public ClassTwo(){
        super();
    }
}

Is there a way to implement Serializable into ClassName without changing the original class?

Body:
If you have read/write access to all the slots you care to serialize, you can create an adapter class.

public class MyClassAdapter implements Serializable {
    private MyClass instance;
    ...
}

Then just wrap the instance in this adapter class before serializing, and extract it after deserializing.

If you don't have read/write access to the slots, there's probably a good reason for that, and serializing data you don't own is a bad idea.


问:
RxJs: request list from server, consume values, re-request when we're almost out of values
I'm fetching a list of items from a REST api. The user interacts with each one via a click, and when there are only, say, a couple left unused, I'd like to repeat the request to get more items. I'm trying to do this using a proper RxJs (5) stream-oriented approach.

So, something like:

```<code>var userClick$ = Observable.fromEvent(button.nativeElement, 'click');

var needToExtend$ = new BehaviorSubject(1);

var list$ = needToExtend$
            .flatMap( () => this.http.get("http://myserver/get-list") )
            .flatMap( x => x['list'] );

var itemsUsed$ = userClick$.zip(list$, (click, item) => item);
itemsUsed$.subscribe( item => use(item) );
</code>```

and then, to trigger a re-load when necessary:

```<code>list$.subscribe(
    if (list$.isEmpty()) {
        needToExtend$.next(1);
    }
)
</code>```

This last bit is wrong, and manually re-triggering doesn't seem very "stream-oriented" even if it did work as intended. Any ideas?

This is similar to Rxjs - Consume API output and re-query when cache is empty but I can't make assumptions about the length of the list returned by the API, and I'd like to re-request before the list is completely consumed. And the solution there feels a bit too clever. There must be a more readable way, right?

答:
I'm not clear on how you are tracking getting the next set of items so I will assume it is some form of paging for my answer. I also assume that you don't know the total number of items.

console.clear();
const pageSize = 5;
const pageBuffer = 2;
const data = [...Array(17).keys()]

function getData(page) {
  const begin = pageSize * page
  const end = begin + pageSize;
 return Rx.Observable.of(data.slice(begin, end));
}

const clicks = Rx.Observable.interval(400);

clicks
  .scan(count => ++count, 0)
  .do(() => console.log('click'))
  .map(count => {
    const page = Math.floor(count / pageSize) + 1;
    const total = page * pageSize;
    return { total, page, count }
  })
  .filter(x => x.total - pageBuffer === x.count)
  .startWith({ page: 0 })
  .switchMap(x => getData(x.page))
  .takeWhile(x => x.length > 0)
  .subscribe(
    x => { console.log('next: ', x); },
    x => { console.log('error: ', x); },
    () => { console.log('completed'); }
  );```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.5.3/Rx.min.js"></script></code>```

Here is an explaination:

Rx.Observable.interval(#): simulates the client click events

.scan(...): accumulates the click events

.map(...): calculates the page index and potential total item count (actual count could be less but it doesn't matter for our purposes

.filter(...): only allow to pass through to get a new page of data if it has just hit the page buffer.

.startWith(...): get the first page without waiting for clicks. The +1 on the page calculation in the .scan accounts for this.

.switchMap(...): get the next page of data.

.takeWhile(...): keep the stream open till we get an empty list.

So it will get an initial page and then go get a new page whenever the number of clicks comes within the designated buffer. Once all items have been retrieved (known by empty list) it will complete.

One thing I didn't figure out how to do is to complete the list when the page length is less than the page size. Not sure if it matters to you.

Body:
I'm fetching a list of items from a REST api. The user interacts with each one via a click, and when there are only, say, a couple left unused, I'd like to repeat the request to get more items. I'm trying to do this using a proper RxJs (5) stream-oriented approach.

So, something like:

var userClick$ = Observable.fromEvent(button.nativeElement, 'click');

var needToExtend$ = new BehaviorSubject(1);

var list$ = needToExtend$
            .flatMap( () => this.http.get("http://myserver/get-list") )
            .flatMap( x => x['list'] );

var itemsUsed$ = userClick$.zip(list$, (click, item) => item);
itemsUsed$.subscribe( item => use(item) );

and then, to trigger a re-load when necessary:

list$.subscribe(
    if (list$.isEmpty()) {
        needToExtend$.next(1);
    }
)

This last bit is wrong, and manually re-triggering doesn't seem very "stream-oriented" even if it did work as intended. Any ideas?

This is similar to Rxjs - Consume API output and re-query when cache is empty but I can't make assumptions about the length of the list returned by the API, and I'd like to re-request before the list is completely consumed. And the solution there feels a bit too clever. There must be a more readable way, right?

Body:
I'm not clear on how you are tracking getting the next set of items so I will assume it is some form of paging for my answer. I also assume that you don't know the total number of items.

console.clear();
const pageSize = 5;
const pageBuffer = 2;
const data = [...Array(17).keys()]

function getData(page) {
  const begin = pageSize * page
  const end = begin + pageSize;
 return Rx.Observable.of(data.slice(begin, end));
}

const clicks = Rx.Observable.interval(400);

clicks
  .scan(count => ++count, 0)
  .do(() => console.log('click'))
  .map(count => {
    const page = Math.floor(count / pageSize) + 1;
    const total = page * pageSize;
    return { total, page, count }
  })
  .filter(x => x.total - pageBuffer === x.count)
  .startWith({ page: 0 })
  .switchMap(x => getData(x.page))
  .takeWhile(x => x.length > 0)
  .subscribe(
    x => { console.log('next: ', x); },
    x => { console.log('error: ', x); },
    () => { console.log('completed'); }
  );

<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.5.3/Rx.min.js"></script>

Here is an explaination:

Rx.Observable.interval(#): simulates the client click events

.scan(...): accumulates the click events

.map(...): calculates the page index and potential total item count (actual count could be less but it doesn't matter for our purposes

.filter(...): only allow to pass through to get a new page of data if it has just hit the page buffer.

.startWith(...): get the first page without waiting for clicks. The +1 on the page calculation in the .scan accounts for this.

.switchMap(...): get the next page of data.

.takeWhile(...): keep the stream open till we get an empty list.

So it will get an initial page and then go get a new page whenever the number of clicks comes within the designated buffer. Once all items have been retrieved (known by empty list) it will complete.

One thing I didn't figure out how to do is to complete the list when the page length is less than the page size. Not sure if it matters to you.


问:
Understanding the PhaseListener.getPhaseId
HI,

I need clarification on implementing the PhaseListener class. The following is the two different overriding implementation for the PhaseListener.getPhaseId

```<code>@Override
public PhaseId getPhaseId() {
    return PhaseId.ANY_PHASE;
}
</code>```

and

```<code>@Override
public PhaseId getPhaseId() {
    return PhaseId.RESTORE_VIEW;
}
</code>```

What could be the significant difference in those two implementations?. What will be the impact?

答: As stated in the PhaseListener#getPhaseId() javadoc, this indicates for which PhaseId the current PhaseListener implementation should execute the implemented beforePhase() and afterPhase() methods. In the first example, they will be executed on any phase and in the second example, they will be executed in the RESTORE_VIEW phase only (which is the firstmost phase of the JSF lifecycle).

Body:
HI,

I need clarification on implementing the PhaseListener class. The following is the two different overriding implementation for the PhaseListener.getPhaseId

@Override
public PhaseId getPhaseId() {
    return PhaseId.ANY_PHASE;
}

and

@Override
public PhaseId getPhaseId() {
    return PhaseId.RESTORE_VIEW;
}

What could be the significant difference in those two implementations?. What will be the impact?


问:
How to use nodejs RESTful api to query from multiple collections?
nodejs noobie here,

I have created nodejs RESTful api for fetching data from three different collections. Here is the article which helped me nodejs api in 10 minutes

After creating APIs, I am able to hit the APIs through postman and get data there. Now I wish to move on to next step of querying records from multiple collections

Server.js

```<code>    var express = require('express'),
  app = express(),

  port = process.env.PORT ||3000,
  mongoose = require('mongoose'),
  menu = require('./app/api/bestseller_books/models/bestsellerBooksModel'),
    admin = require('./app/api/admin/models/adminModel'),
    test = require('./app/api/test/models/testModel'),
  bodyParser = require('body-parser');
  var Schema = mongoose.Schema;
  var cors = require('cors');

// mongoose instance connection url connection
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost:27017/takebook', { useMongoClient: true });
/*mongoose.model('menu', new Schema({ title: String, id: Number }));*/

var menu = mongoose.model('bestseller_books');
var test = mongoose.model('test');
var admin = mongoose.model('admin');
var routes = require('./app/api/bestseller_books/routes/bestsellerBooksRoutes');
var routes2 = require('./app/api/admin/routes/adminRoutes');
var routes3 = require('./app/api/test/routes/testRoutes');

menu.find({}, function(err, data) { console.log(err, data.length); });

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cors());

routes(app); //register the route
/*routes2(app);
routes3(app);*/

app.listen(port);
app.use(function(req, res) {
  res.status(404).send({url: req.originalUrl + ' not found'})
});

console.log('RESTful API server started on: ' + port);
</code>```

bestsellerbooks controller

```<code>'use strict';

var mongoose = require('mongoose'),
  menu = mongoose.model('bestseller_books');

exports.list_all_menus = function(req, res) {
  menu.find({}, function(err, menu) {
    if (err)
      res.send(err);
    res.json(menu);
    console.log(res);
  });
};

exports.create_a_menu = function(req, res) {
  var new_menu = new menu(req.body);
  new_menu.save(function(err, menu) {
    if (err)
      res.send(err);
    res.json(menu);
  });
};

exports.read_a_menu = function(req, res) {
  menu.findById(req.params.menuId, function(err, menu) {
    if (err)
      res.send(err);
    res.json(menu);
  });
};

exports.update_a_menu = function(req, res) {
  menu.findOneAndUpdate({_id: req.params.menuId}, req.body, {new: true}, function(err, menu) {
    if (err)
      res.send(err);
    res.json(menu);
  });
};

exports.delete_a_menu = function(req, res) {
  menu.remove({
    _id: req.params.menuId
  }, function(err, menu) {
    if (err)
      res.send(err);
    res.json({ message: 'bestseller_books successfully deleted' });
  });
};
</code>```

My questions are :

Do I have to create new set of models, controllers and routes for
each API?

Looking at the server.js, is this the best practice of
setting up API routes?

What is the use of create_a_menu methods
mentioned in API controllers, if I have to hit API in this format:

```<code>app.controller('booklister', ['$http', function($http) {
var self = this;
$http.get('http://localhost:3000/bestseller_books')
.then(function(response)
{
      /*$('.fa-refresh').hide();*/
      self.items = response.data;
    }, function(errResponse) {
      /*$('.fa-refresh').show();*/
      console.error('Service Error while fetching books' + errResponse);
    });
</code>```

答:
Just create more from everything.
New model, new schema, new Bl layer, new route that take care for that new collection.

For  example:

In yore dotsModel.js:

```<code>var mongoose = require('mongoose');
var Schema = mongoose.Schema;

    var DotsSchema = new Schema({

    x: {
        type: Number
    },
    y: {
        type: Number
    }
});

module.exports = mongoose.model('Dots', DotsSchema);
</code>```

In youre dotsController.js:

```<code>var mongoose = require('mongoose'),
    Dots = mongoose.model('Dots')

exports.get_all_dots = function (req, res) {
    Dots.find({}, function (err, task) {
        if (err)
            res.send(err);
        res.json(task);
    });
};
</code>```

And in your dotsRoutes.js:

```<code>module.exports = function(app) {
    var todoList = require('../controllers/ dotsController.js:');

app.route('/dots')
    .get(todoList.get_all_dots);
</code>```

Note:

The article you read is short and he touch really briefly on each topic, it's highly recommended to take another course, much longer, and take the time to learn each part of your application, and what node capable of.

Body:
nodejs noobie here,

I have created nodejs RESTful api for fetching data from three different collections. Here is the article which helped me nodejs api in 10 minutes

After creating APIs, I am able to hit the APIs through postman and get data there. Now I wish to move on to next step of querying records from multiple collections

Server.js

    var express = require('express'),
  app = express(),

  port = process.env.PORT ||3000,
  mongoose = require('mongoose'),
  menu = require('./app/api/bestseller_books/models/bestsellerBooksModel'),
    admin = require('./app/api/admin/models/adminModel'),
    test = require('./app/api/test/models/testModel'),
  bodyParser = require('body-parser');
  var Schema = mongoose.Schema;
  var cors = require('cors');

// mongoose instance connection url connection
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost:27017/takebook', { useMongoClient: true });
/*mongoose.model('menu', new Schema({ title: String, id: Number }));*/

var menu = mongoose.model('bestseller_books');
var test = mongoose.model('test');
var admin = mongoose.model('admin');
var routes = require('./app/api/bestseller_books/routes/bestsellerBooksRoutes');
var routes2 = require('./app/api/admin/routes/adminRoutes');
var routes3 = require('./app/api/test/routes/testRoutes');

menu.find({}, function(err, data) { console.log(err, data.length); });

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cors());

routes(app); //register the route
/*routes2(app);
routes3(app);*/

app.listen(port);
app.use(function(req, res) {
  res.status(404).send({url: req.originalUrl + ' not found'})
});

console.log('RESTful API server started on: ' + port);

bestsellerbooks controller

'use strict';

var mongoose = require('mongoose'),
  menu = mongoose.model('bestseller_books');

exports.list_all_menus = function(req, res) {
  menu.find({}, function(err, menu) {
    if (err)
      res.send(err);
    res.json(menu);
    console.log(res);
  });
};

exports.create_a_menu = function(req, res) {
  var new_menu = new menu(req.body);
  new_menu.save(function(err, menu) {
    if (err)
      res.send(err);
    res.json(menu);
  });
};

exports.read_a_menu = function(req, res) {
  menu.findById(req.params.menuId, function(err, menu) {
    if (err)
      res.send(err);
    res.json(menu);
  });
};

exports.update_a_menu = function(req, res) {
  menu.findOneAndUpdate({_id: req.params.menuId}, req.body, {new: true}, function(err, menu) {
    if (err)
      res.send(err);
    res.json(menu);
  });
};

exports.delete_a_menu = function(req, res) {
  menu.remove({
    _id: req.params.menuId
  }, function(err, menu) {
    if (err)
      res.send(err);
    res.json({ message: 'bestseller_books successfully deleted' });
  });
};

My questions are :

Do I have to create new set of models, controllers and routes for
each API?

Looking at the server.js, is this the best practice of
setting up API routes?

What is the use of create_a_menu methods
mentioned in API controllers, if I have to hit API in this format:

app.controller('booklister', ['$http', function($http) {
var self = this;
$http.get('http://localhost:3000/bestseller_books')
.then(function(response)
{
      /*$('.fa-refresh').hide();*/
      self.items = response.data;
    }, function(errResponse) {
      /*$('.fa-refresh').show();*/
      console.error('Service Error while fetching books' + errResponse);
    });

Body:
Just create more from everything.
New model, new schema, new Bl layer, new route that take care for that new collection.

For  example:

In yore dotsModel.js:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

    var DotsSchema = new Schema({

    x: {
        type: Number
    },
    y: {
        type: Number
    }
});

module.exports = mongoose.model('Dots', DotsSchema);

In youre dotsController.js:

var mongoose = require('mongoose'),
    Dots = mongoose.model('Dots')

exports.get_all_dots = function (req, res) {
    Dots.find({}, function (err, task) {
        if (err)
            res.send(err);
        res.json(task);
    });
};

And in your dotsRoutes.js:

module.exports = function(app) {
    var todoList = require('../controllers/ dotsController.js:');

app.route('/dots')
    .get(todoList.get_all_dots);

Note:

The article you read is short and he touch really briefly on each topic, it's highly recommended to take another course, much longer, and take the time to learn each part of your application, and what node capable of.


问:
Creating a new column with an if function in R
I am currently dealing with data on NFL Teams. Basically what I am trying to do here is create a new column titled Conference. I am trying to create an if function that generates the conference based off the Team in the Team column. My data set is called NFL_DATA and the column i am interested in is Team so I am using NFL_DATA$Team. Basically I am trying to say if NFL_DATA$TEAM == 'Philadelphia Eagles' or 'Dallas Cowboys' or 'New York Giants' or 'Washington Redskins' Then it will equal NFC East. Then in the conference column NFC East will appear for any of these teams. I am trying to do this for all 8 conferences. Any help would be greatly appreciated!!

So Far this is what I have and Im sure this is off:

```<code>Conference <- function(NFL_DATA$Team) {
  if (NFL_DATA$Team == 'Phiadelphia Eagles' | 'Dallas Cowboys' | 'New York Giants' | 'Washington Redskins') y <- "NFC EAST"
}
</code>```

答:
Dplyr's case_when is handy for long ifelse statments:

```<code>library(dplyr)
NFL_Data <-
  NFL_Data %>% mutate("Conference" = case_when(
    Team %in% c(
      'Phiadelphia Eagles' ,
      'Dallas Cowboys' ,
      'New York Giants' ,
      'Washington Redskins'
    ) ~ 'NFC EAST',
    Team %in% c(
      'New England Patriots' ,
      'Buffalo Bills' ,
      'New York Jets' ,
      'Miami Dolphins'
    ) ~ 'AFC EAST',
    TRUE ~ "NFC WEST"
  )
</code>```

You can keep adding Team %in% c("List_of_Teams") ~ "Conference_Name" lines before the TRUE ~ "NFC WEST" for the remaining NFL conferences.

Body:
I am currently dealing with data on NFL Teams. Basically what I am trying to do here is create a new column titled Conference. I am trying to create an if function that generates the conference based off the Team in the Team column. My data set is called NFL_DATA and the column i am interested in is Team so I am using NFL_DATA$Team. Basically I am trying to say if NFL_DATA$TEAM == 'Philadelphia Eagles' or 'Dallas Cowboys' or 'New York Giants' or 'Washington Redskins' Then it will equal NFC East. Then in the conference column NFC East will appear for any of these teams. I am trying to do this for all 8 conferences. Any help would be greatly appreciated!!

So Far this is what I have and Im sure this is off:

Conference <- function(NFL_DATA$Team) {
  if (NFL_DATA$Team == 'Phiadelphia Eagles' | 'Dallas Cowboys' | 'New York Giants' | 'Washington Redskins') y <- "NFC EAST"
}

Body:
Dplyr's case_when is handy for long ifelse statments:

library(dplyr)
NFL_Data <-
  NFL_Data %>% mutate("Conference" = case_when(
    Team %in% c(
      'Phiadelphia Eagles' ,
      'Dallas Cowboys' ,
      'New York Giants' ,
      'Washington Redskins'
    ) ~ 'NFC EAST',
    Team %in% c(
      'New England Patriots' ,
      'Buffalo Bills' ,
      'New York Jets' ,
      'Miami Dolphins'
    ) ~ 'AFC EAST',
    TRUE ~ "NFC WEST"
  )

You can keep adding Team %in% c("List_of_Teams") ~ "Conference_Name" lines before the TRUE ~ "NFC WEST" for the remaining NFL conferences.


问:
Git / SourceTree - remote invalid username or password
I've just reinstalled SourceTree on my new computer and I'm having trouble when trying to push my commits.

If I use the built-in Push button from SourceTree, it brings up a dialog where I enter my username and password but then I get an error: remote invalid username or password.

The strangest thing is that if I bring the Git console by clicking on the Console button in SourceTree, type git push then enter the exact same credentials, it works...

I'm assuming SourceTree might be overriding some Git config somehow but I can't find a solution.

I tried deleting all credentials saved by SourceTree, I disallowed SourceTree to modify my Git config in the Tools > General menu but it didn't change anything...

Thanks for your help!

答:
One possible answer to this problem is to update your local version of git or update your embedded version of git. Newer versions of sourcetree do not play nice with older versions of git.

https://community.atlassian.com/t5/Bitbucket-questions/SourceTree-2-1-10-0-Authentication-Issues/qaq-p/623202


问:
Creating a jump menu to jump to different categories without splitting up MySQL query
I have a simple MySQL table that stores four fields -  CATEGORY, TITLE, DESCRIPTION, IMAGE   as well as a unique ID for each row.

I use ORDER BY CATEGORY to display all of them on the page through one query.

```<code>SELECT
RESOLUTIONS.CATEGORY,
RESOLUTIONS.ID,
RESOLUTIONS.TITLE,
RESOLUTIONS.DESCRIPTION,
RESOLUTIONS.IMAGE
FROM
RESOLUTIONS
ORDER BY
RESOLUTIONS.CATEGORY
</code>```

I want to create a jump menu that will jump to the first row of each category on the page. Is this possible using php?  I know how to create a jump menu that jumps to an ID anchor of a div, but how can I make a unique identifier (that I can jump to) inside the repeat region?

Here is the repeat code I have now...

```<code><?php
while(!$DETAILS->atEnd()) {
?>
 <div class="row g-my-10 g-color-black">
    <?php if($DETAILS->getColumnVal("IMAGE")!= "") { ?>
    <div class="col-md-9">
        <h2><?php echo($DETAILS->getColumnVal("TITLE")); ?></h2>
        <?php echo($DETAILS->getColumnVal("DESCRIPTION")); ?>
    </div>
    <div class="col-md-3"><img src="images/<?php echo($DETAILS->getColumnVal("IMAGE")); ?>" class="img-fluid"></div>
    <? } else { ?>
    <div class="col-md-12">
        <h2><?php echo($DETAILS->getColumnVal("TITLE")); ?></h2>
        <?php echo($DETAILS->getColumnVal("DESCRIPTION")); ?>
    </div>
    <?php } ?>
  </div>

 <?php

    $DETAILS->moveNext();
}
$DETAILS->moveFirst(); //return RS to first record
?>
</code>```

答:
In each iteration check if the category is different than the one before and create an anchor.

```<code><?php
// set any initial value that does not match an empty category (if you have them)
$lastCategory = false;

while(!$DETAILS->atEnd()) {

 <div class="row g-my-10 g-color-black">
<?php
    // this category is different than the last: create anchor
    if ($lastCategory !== $DETAILS->getColumnVal("CATEGORY")) {
        echo '<a name="category-' . $DETAILS->getColumnVal("CATEGORY") . '"></a>';
        // set the compare-value to the current category
        $lastCategory = $DETAILS->getColumnVal("CATEGORY");
    }
?>
    <?php if($DETAILS->getColumnVal("IMAGE")!= "") { ?>
    <div class="col-md-9">
        <h2><?php echo($DETAILS->getColumnVal("TITLE")); ?></h2>
        <?php echo($DETAILS->getColumnVal("DESCRIPTION")); ?>
    </div>
    <div class="col-md-3"><img src="images/<?php echo($DETAILS->getColumnVal("IMAGE")); ?>" class="img-fluid"></div>
    <? } else { ?>
    <div class="col-md-12">
        <h2><?php echo($DETAILS->getColumnVal("TITLE")); ?></h2>
        <?php echo($DETAILS->getColumnVal("DESCRIPTION")); ?>
    </div>
    <?php } ?>
  </div>

 <?php

    $DETAILS->moveNext();
}
$DETAILS->moveFirst(); //return RS to first record
?>
</code>```

Note: You might have to put the anchor within the column or even the
, depending on your grid system (is that bootstrap?). You maybe also want to refactor the generation of the title/description column, so you don't repeat yourself. Something like

```<code><?php
    if ($DETAILS->getColumnVal("IMAGE")!= "") {
        $cols = '9';
    } else {
        $cols = '12';
    }
?>
<div class="col-md-<?php echo $cols ?>">
    <h2><?php echo($DETAILS->getColumnVal("TITLE")); ?></h2>
    <?php echo($DETAILS->getColumnVal("DESCRIPTION")); ?>
</div>
<?php
    if ($DETAILS->getColumnVal("IMAGE")!= "") {
?>
<div class="col-md-3"><img src="images/<?php echo($DETAILS->getColumnVal("IMAGE")); ?>" class="img-fluid"></div>
<?php
    }
?>
</code>```

Also note that according to PSR-1 you should use either <?php or the echo shortcut <?= but not just <?

And I know it's a matter of personal choice and also depends on what your file mainly contains (HTML or PHP), but I personally prefer echoing HTML code snippets instead of opening and closing PHP tags, because I find it easier to read (there is also a very marginal performance advantage)

Body:
I have a simple MySQL table that stores four fields -  CATEGORY, TITLE, DESCRIPTION, IMAGE   as well as a unique ID for each row.

I use ORDER BY CATEGORY to display all of them on the page through one query.

SELECT
RESOLUTIONS.CATEGORY,
RESOLUTIONS.ID,
RESOLUTIONS.TITLE,
RESOLUTIONS.DESCRIPTION,
RESOLUTIONS.IMAGE
FROM
RESOLUTIONS
ORDER BY
RESOLUTIONS.CATEGORY

I want to create a jump menu that will jump to the first row of each category on the page. Is this possible using php?  I know how to create a jump menu that jumps to an ID anchor of a div, but how can I make a unique identifier (that I can jump to) inside the repeat region?

Here is the repeat code I have now...

<?php
while(!$DETAILS->atEnd()) {
?>

    <?php if($DETAILS->getColumnVal("IMAGE")!= "") { ?>

<?php echo($DETAILS->getColumnVal("TITLE")); ?>

        <?php echo($DETAILS->getColumnVal("DESCRIPTION")); ?>

<img src="images/<?php echo($DETAILS->getColumnVal("IMAGE")); ?>" class="img-fluid">

    <? } else { ?>

<?php echo($DETAILS->getColumnVal("TITLE")); ?>

        <?php echo($DETAILS->getColumnVal("DESCRIPTION")); ?>

    <?php } ?>

 <?php

    $DETAILS->moveNext();
}
$DETAILS->moveFirst(); //return RS to first record
?>

Body:
In each iteration check if the category is different than the one before and create an anchor.

<?php
// set any initial value that does not match an empty category (if you have them)
$lastCategory = false;

while(!$DETAILS->atEnd()) {

 <div class="row g-my-10 g-color-black">
<?php
    // this category is different than the last: create anchor
    if ($lastCategory !== $DETAILS->getColumnVal("CATEGORY")) {
        echo '<a name="category-' . $DETAILS->getColumnVal("CATEGORY") . '"></a>';
        // set the compare-value to the current category
        $lastCategory = $DETAILS->getColumnVal("CATEGORY");
    }
?>
    <?php if($DETAILS->getColumnVal("IMAGE")!= "") { ?>
    <div class="col-md-9">
        <h2><?php echo($DETAILS->getColumnVal("TITLE")); ?></h2>
        <?php echo($DETAILS->getColumnVal("DESCRIPTION")); ?>
    </div>
    <div class="col-md-3"><img src="images/<?php echo($DETAILS->getColumnVal("IMAGE")); ?>" class="img-fluid"></div>
    <? } else { ?>
    <div class="col-md-12">
        <h2><?php echo($DETAILS->getColumnVal("TITLE")); ?></h2>
        <?php echo($DETAILS->getColumnVal("DESCRIPTION")); ?>
    </div>
    <?php } ?>
  </div>

 <?php

    $DETAILS->moveNext();
}
$DETAILS->moveFirst(); //return RS to first record
?>

Note: You might have to put the anchor within the column or even the <h2>, depending on your grid system (is that bootstrap?). You maybe also want to refactor the generation of the title/description column, so you don't repeat yourself. Something like

<?php
    if ($DETAILS->getColumnVal("IMAGE")!= "") {
        $cols = '9';
    } else {
        $cols = '12';
    }
?>
<div class="col-md-<?php echo $cols ?>">
    <h2><?php echo($DETAILS->getColumnVal("TITLE")); ?></h2>
    <?php echo($DETAILS->getColumnVal("DESCRIPTION")); ?>
</div>
<?php
    if ($DETAILS->getColumnVal("IMAGE")!= "") {
?>
<div class="col-md-3"><img src="images/<?php echo($DETAILS->getColumnVal("IMAGE")); ?>" class="img-fluid"></div>
<?php
    }
?>

Also note that according to PSR-1 you should use either <?php or the echo shortcut <?= but not just <?

And I know it's a matter of personal choice and also depends on what your file mainly contains (HTML or PHP), but I personally prefer echoing HTML code snippets instead of opening and closing PHP tags, because I find it easier to read (there is also a very marginal performance advantage)


问:
Array indexOf() vs includes() perfomance depending on browser and needle position
Is there any advantage to Array.prototype.includes() over Array.prototype.indexOf() depending on browsers (Chrome, Firefox) and needle item position (at the begging, middle, ending of the array)?

Array.prototype.includes vs. Array.prototype.indexOf
There is no browser specific information, there is no position in the array specific information, and I don't ask about NaN value.

答:
If you wonder about performances, here is a JSperf test that tend to show that more the time pass, more includes() will be faster than indexOf.

JSperf

IMHO, i also prefer to write if (arr.includes(el)) {} since it is clearer and more maintainable than if (arr.indexOf(el) !== -1) {}