问:
"Failed to resolve IP"; "Lookup error" in bash script when joining dockerized serf agents
[Context: Host is AWS-EC2 / Ubuntu 14.04.5 with Docker version 17.05.0-ce. Containers are built from publicly available repo image cbhihe/serf-alpine-bash. Containers are located on the same EC2 instance and share the same default bridge network as well as the instance's eth0 interface.]

This question builds on an answer to a different issue.

Working with two running docker containers, each with a live serf agent in it, I want to form a two node serf cluster from an unattended bash script, executing on the host where the two containers run.

For one serf agent in container "DC2" to join another in container "DC1" with private IP 172.17.0.2,  my script looks like:

```<code>docker run -d --name DC1 --rm cbhihe/serf-alpine-bash agent -node=NODE1 -iface=eth0
docker run -d --name DC2 --rm cbhihe/serf-alpine-bash agent -node=NODE2 -iface=eth0
docker exec -d DC2 serf join 172.17.0.2
</code>```

The two first line produce the expected result, i.e. 2 running containers. The third line seem to fail:

either silently, when using the detached switch,

or with the following error in the absence of such switch.

Error joining the cluster: 1 error(s) occurred:
Failed to resolve 172.17.0.2 : lookup 172.17.0.2 : invalid domain name

Either way joining does not occur.

Doing exactly the same thing from console works flawlessly.

I looked at importing the host's environment in my script's bash shebang context. Was not successsful. Pointers are welcome. Tx

答:
From the information in your question, I think that there could be a dependency to the shell, that sets environment variables.

Try executing serf launched by bash. Something like this:

```<code>docker exec "$cont_id" bash -c 'serf join '"$join_IP"
</code>```

Body:
[Context: Host is AWS-EC2 / Ubuntu 14.04.5 with Docker version 17.05.0-ce. Containers are built from publicly available repo image cbhihe/serf-alpine-bash. Containers are located on the same EC2 instance and share the same default bridge network as well as the instance's eth0 interface.]

This question builds on an answer to a different issue.

Working with two running docker containers, each with a live serf agent in it, I want to form a two node serf cluster from an unattended bash script, executing on the host where the two containers run.

For one serf agent in container "DC2" to join another in container "DC1" with private IP 172.17.0.2,  my script looks like:

docker run -d --name DC1 --rm cbhihe/serf-alpine-bash agent -node=NODE1 -iface=eth0
docker run -d --name DC2 --rm cbhihe/serf-alpine-bash agent -node=NODE2 -iface=eth0
docker exec -d DC2 serf join 172.17.0.2

The two first line produce the expected result, i.e. 2 running containers. The third line seem to fail:

either silently, when using the detached switch,

or with the following error in the absence of such switch.

Error joining the cluster: 1 error(s) occurred:
Failed to resolve 172.17.0.2 : lookup 172.17.0.2 : invalid domain name

Either way joining does not occur.

Doing exactly the same thing from console works flawlessly.

I looked at importing the host's environment in my script's bash shebang context. Was not successsful. Pointers are welcome. Tx

Body:
From the information in your question, I think that there could be a dependency to the shell, that sets environment variables.

Try executing serf launched by bash. Something like this:

docker exec "$cont_id" bash -c 'serf join '"$join_IP"


来源: stackexchange

问:
how to debug jest unit tests on create-react-app?
I use create-react-app and I would like to debug my unit tests

as Jest documentation says, debugging is possible using this command:

```<code>node --debug-brk --inspect ./node_modules/.bin/jest -i [any other arguments here]
</code>```

unfortunately, it's not working with create-react-app.
I got this error instead:

```<code>node --debug-brk --inspect ./node_modules/.bin/jest -i
Debugger listening on port 9229.
Warning: This is an experimental feature and could change at any time.
To start debugging, open the following URL in Chrome:
    chrome-devtools://devtools/remote/serve_file/@60cd6e859b9f557d2312f5bf532f6aec5f284980/inspector.html?experiments=true&v8only=true&ws=localhost:9229/node
Debugger attached.
module.js:457
    throw err;
    ^

Error: Cannot find module '/Users/asafkatz/dev/newmaps/node_modules/.bin/jest'
    at Function.Module._resolveFilename (module.js:455:15)
    at Function.Module._load (module.js:403:25)
    at Timeout.Module.runMain [as _onTimeout] (module.js:590:10)
    at tryOnTimeout (timers.js:232:11)
    at Timer.listOnTimeout (timers.js:202:5)
Waiting for the debugger to disconnect...
</code>```

what is the proper way to debug jest unit test on create-react-app?

答:
If you're using visual studio code, you can use the following configuration. Hopefully this saves someone a few hours.

My setup:

Un-ejected create-react-app (1.3.1) project

Node version: v6.10.3

Npm version: 4.6.1

To get this working I also needed to install jest-file and jest-css using npm i --save-dev jest-file jest-css. These are used as file transformers so that jest doesn't complain about imports for files, for example svg.

launch.json

```<code>{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Test with debugger",
      "type": "node",
      "request": "launch",
      "port": 5858,
      "runtimeArgs": [
        "--debug-brk",
        "--nolazy"
      ],
      "program": "${workspaceRoot}/node_modules/jest/bin/jest.js",
      "args": [
        "--runInBand",
        "--transform={\"^.+\\\\.(js|jsx)$\": \"babel-jest\",\"^.+\\\\.css$\": \"jest-css\",\"^(?!.*\\\\.(js|jsx|css|json)$)\": \"jest-file\"}"
      ],
      "cwd": "${workspaceRoot}"
    }
  ]
}
</code>```

Explanation

--nolazy: fully compile code so that we can use breakpoints correctly

--runInBand: stop Jest from spawning tests in worker processes

--transform: stop errors when importing files such as svg. If you add this to package.json, react-scripts won't let you run npm test since it doesn't support overwriting of the transform options.

The following lines need to be added to package.json or .babelrc

```<code>"babel": {
  "sourceMaps": "inline",
  "presets": [
    "react-app"
  ]
}
</code>```

Explanation

sourceMaps: This must either be "inline" or "both". If you don't set this, when you debug your tests you'll see transpiled code instead of your source.

presets: react-app is the default preset for a create-react-app project. If you don't include this in either package.json or .babelrc you'll get errors because jest won't know how to deal with the jsx.

Result

If you're not using visual studio code, you could run the following command and connect to the debugging session using another GUI debugger: node --debug-brk ./node_modules/jest/bin/jest.js --runInBand --config=./jest-config.json. Just make sure to put the below config in a jest-config.json file:

```<code>"transform": {
  "^.+\\.(js|jsx)$": "babel-jest",
  "^.+\\.css$": "jest-css",
  "^(?!.*\\.(js|jsx|css|json)$)": "jest-file"
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I use create-react-app and I would like to debug my unit tests

as Jest documentation says, debugging is possible using this command:

node --debug-brk --inspect ./node_modules/.bin/jest -i [any other arguments here]

unfortunately, it's not working with create-react-app.
I got this error instead:

node --debug-brk --inspect ./node_modules/.bin/jest -i
Debugger listening on port 9229.
Warning: This is an experimental feature and could change at any time.
To start debugging, open the following URL in Chrome:
    chrome-devtools://devtools/remote/serve_file/@60cd6e859b9f557d2312f5bf532f6aec5f284980/inspector.html?experiments=true&v8only=true&ws=localhost:9229/node
Debugger attached.
module.js:457
    throw err;
    ^

Error: Cannot find module '/Users/asafkatz/dev/newmaps/node_modules/.bin/jest'
    at Function.Module._resolveFilename (module.js:455:15)
    at Function.Module._load (module.js:403:25)
    at Timeout.Module.runMain [as _onTimeout] (module.js:590:10)
    at tryOnTimeout (timers.js:232:11)
    at Timer.listOnTimeout (timers.js:202:5)
Waiting for the debugger to disconnect...

what is the proper way to debug jest unit test on create-react-app?

Body:
If you're using visual studio code, you can use the following configuration. Hopefully this saves someone a few hours.

My setup:

Un-ejected create-react-app (1.3.1) project

Node version: v6.10.3

Npm version: 4.6.1

To get this working I also needed to install jest-file and jest-css using npm i --save-dev jest-file jest-css. These are used as file transformers so that jest doesn't complain about imports for files, for example svg.

launch.json

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Test with debugger",
      "type": "node",
      "request": "launch",
      "port": 5858,
      "runtimeArgs": [
        "--debug-brk",
        "--nolazy"
      ],
      "program": "${workspaceRoot}/node_modules/jest/bin/jest.js",
      "args": [
        "--runInBand",
        "--transform={\"^.+\\\\.(js|jsx)$\": \"babel-jest\",\"^.+\\\\.css$\": \"jest-css\",\"^(?!.*\\\\.(js|jsx|css|json)$)\": \"jest-file\"}"
      ],
      "cwd": "${workspaceRoot}"
    }
  ]
}

Explanation

--nolazy: fully compile code so that we can use breakpoints correctly

--runInBand: stop Jest from spawning tests in worker processes

--transform: stop errors when importing files such as svg. If you add this to package.json, react-scripts won't let you run npm test since it doesn't support overwriting of the transform options.

The following lines need to be added to package.json or .babelrc

"babel": {
  "sourceMaps": "inline",
  "presets": [
    "react-app"
  ]
}

Explanation

sourceMaps: This must either be "inline" or "both". If you don't set this, when you debug your tests you'll see transpiled code instead of your source.

presets: react-app is the default preset for a create-react-app project. If you don't include this in either package.json or .babelrc you'll get errors because jest won't know how to deal with the jsx.

Result

If you're not using visual studio code, you could run the following command and connect to the debugging session using another GUI debugger: node --debug-brk ./node_modules/jest/bin/jest.js --runInBand --config=./jest-config.json. Just make sure to put the below config in a jest-config.json file:

"transform": {
  "^.+\\.(js|jsx)$": "babel-jest",
  "^.+\\.css$": "jest-css",
  "^(?!.*\\.(js|jsx|css|json)$)": "jest-file"
}


问:
Apply css from another file to an echo statement from the ajax call
I have a registration page (say reg.php) with a form and I am using ajax for validation of the form elements (say username).
Now, if the username already exists in the db, I want to display the error message in red and if it is available I want it to be in green.
It is working if I style the echo statement like this-

```<code>echo "<span style='color:brown; font-size:14px'><b>Oophs! </b>Looks like username is already in use.</span>";
</code>```

But I want to style it from an another css file. How can I do it?

答:
in the page on which error will be display, inside head tag add style tag as

```<code><style>
   .error {
        color:brown;
        font-size:14px;
   }
</style>
</code>```

and echo like this

```<code>echo "<span class='error'><b>Oophs! </b>Looks like username is already in use.</span>";
</code>```

Body:
I have a registration page (say reg.php) with a form and I am using ajax for validation of the form elements (say username).
Now, if the username already exists in the db, I want to display the error message in red and if it is available I want it to be in green.
It is working if I style the echo statement like this-

echo "Oophs! Looks like username is already in use.";

But I want to style it from an another css file. How can I do it?

Body:
in the page on which error will be display, inside head tag add style tag as

<style>
   .error {
        color:brown;
        font-size:14px;
   }
</style>

and echo like this

echo "<span class='error'><b>Oophs! </b>Looks like username is already in use.</span>";


问:
React.JS: Sequence of timed state changes
I have a simple web app with one parent component and three child components. The children are just div boxes that can change their background color from white to red based on their property active. The animateChild() function can be used to turn a specific child red and then white again after 1s.

My goal is to "play" an arbitrary sequence of child animations with a break of 1s between each animation. This should happen in the animateSequence() function.

My initial idea to accomplish that, was to use a for loop and call animateChild(childNum) in a window.setTimeout() at each iteration. However, this didn't work. I guess because setState() is asynchronous and several state changes get merged together.

What is the best way to accomplish a sequence (e.g. Child 1, Child 2, Child 3) of animations with a break time of 1s between each animation? Thank you very much

Javascript Code:

```<code>class Child extends React.Component {

  render() {
    var childStyle = "basic";
    if (this.props.active){
      childStyle += " active";
    }
    return (
        <div className={childStyle}></div>
    );
  }
}

class Parent extends React.Component {
  constructor(){
    super();
    this.state = {
      firstChildActive:false,
      secondChildActive:false,
      thirdChildActive:false,
    };
    this.animateChild = this.animateChild.bind(this);

  }

  animateChild(childNum){
    var childDict = ["firstChildActive","secondChildActive","thirdChildActive"];
    this.setState({[childDict[childNum]]: true}, function() {

        window.setTimeout(() => {
        this.setState({[childDict[childNum]]: false});

        },1000);
    });
  }

  animateSequence(){
    // animate child 2, then child 1, then child 3, then child 1, etc.
  }

  render() {
    return (
      <div className ="container">
      <Child active={this.state.firstChildActive}/>
      <Child active={this.state.secondChildActive}/>
      <Child active={this.state.thirdChildActive}/>
      </div>
    );
  }
}

ReactDOM.render(<Parent />,document.getElementById('app'));
</code>```

CSS Code:

```<code>.container{
  display:flex;
  width:100%;
  justify-content: space-between;

}

.basic{
  margin: 10px;
  width: 100px;
  height:100px;
  border: 2px solid black;
}

.active{
  background: red;
}
</code>```

Codepen: https://codepen.io/miga89/full/owgZea/

答:
I've also converted your Child Component into a Stateless Component, the solution was just use a simple setInterval.

https://codepen.io/anon/pen/LLEyVo

```<code>const Child = ({ isActive }) => {
    var childStyle = "basic";
    if ( isActive ) childStyle += " active";
    return <div className={ childStyle }></div>
}

class Parent extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      firstChildActive  : false,
      secondChildActive : false,
      thirdChildActive  : false,
    };
  }

  animateSequence(){

    const TOTAL = 3;
    const CHILD_DICT = ["firstChildActive","secondChildActive","thirdChildActive"];

    let run = 0;

    var setActive = setInterval( () => {
      this.setState({ [CHILD_DICT[run]]: true });
      run = run + 1;
      if( run === TOTAL ) {
        clearInterval(setActive);
      }
    }, 1000)

  }

  render() {
    return (
      <div className ="container">
        <button onClick={ () => this.animateSequence() }>Run Sequence</button>
      <Child isActive={this.state.firstChildActive }/>
      <Child isActive={this.state.secondChildActive } />
      <Child isActive={this.state.thirdChildActive }/>
      </div>
    );
  }
}

ReactDOM.render(<Parent />,document.getElementById('app'));
</code>```

Body:
I have a simple web app with one parent component and three child components. The children are just div boxes that can change their background color from white to red based on their property active. The animateChild() function can be used to turn a specific child red and then white again after 1s.

My goal is to "play" an arbitrary sequence of child animations with a break of 1s between each animation. This should happen in the animateSequence() function.

My initial idea to accomplish that, was to use a for loop and call animateChild(childNum) in a window.setTimeout() at each iteration. However, this didn't work. I guess because setState() is asynchronous and several state changes get merged together.

What is the best way to accomplish a sequence (e.g. Child 1, Child 2, Child 3) of animations with a break time of 1s between each animation? Thank you very much

Javascript Code:

class Child extends React.Component {

  render() {
    var childStyle = "basic";
    if (this.props.active){
      childStyle += " active";
    }
    return (

    );
  }
}

class Parent extends React.Component {
  constructor(){
    super();
    this.state = {
      firstChildActive:false,
      secondChildActive:false,
      thirdChildActive:false,
    };
    this.animateChild = this.animateChild.bind(this);

  }

  animateChild(childNum){
    var childDict = ["firstChildActive","secondChildActive","thirdChildActive"];
    this.setState({[childDict[childNum]]: true}, function() {

        window.setTimeout(() => {
        this.setState({[childDict[childNum]]: false});

        },1000);
    });
  }

  animateSequence(){
    // animate child 2, then child 1, then child 3, then child 1, etc.
  }

  render() {
    return (

      <Child active={this.state.firstChildActive}/>
      <Child active={this.state.secondChildActive}/>
      <Child active={this.state.thirdChildActive}/>

    );
  }
}

ReactDOM.render(<Parent />,document.getElementById('app'));

CSS Code:

.container{
  display:flex;
  width:100%;
  justify-content: space-between;

}

.basic{
  margin: 10px;
  width: 100px;
  height:100px;
  border: 2px solid black;
}

.active{
  background: red;
}

Codepen: https://codepen.io/miga89/full/owgZea/

Body:
I've also converted your Child Component into a Stateless Component, the solution was just use a simple setInterval.

https://codepen.io/anon/pen/LLEyVo

const Child = ({ isActive }) => {
    var childStyle = "basic";
    if ( isActive ) childStyle += " active";
    return <div className={ childStyle }></div>
}

class Parent extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      firstChildActive  : false,
      secondChildActive : false,
      thirdChildActive  : false,
    };
  }

  animateSequence(){

    const TOTAL = 3;
    const CHILD_DICT = ["firstChildActive","secondChildActive","thirdChildActive"];

    let run = 0;

    var setActive = setInterval( () => {
      this.setState({ [CHILD_DICT[run]]: true });
      run = run + 1;
      if( run === TOTAL ) {
        clearInterval(setActive);
      }
    }, 1000)

  }

  render() {
    return (
      <div className ="container">
        <button onClick={ () => this.animateSequence() }>Run Sequence</button>
      <Child isActive={this.state.firstChildActive }/>
      <Child isActive={this.state.secondChildActive } />
      <Child isActive={this.state.thirdChildActive }/>
      </div>
    );
  }
}

ReactDOM.render(<Parent />,document.getElementById('app'));


问:
Add Number of days column to Date Column in same dataframe for Spark Scala App
I have a dataframe df of columns ("id", "current_date", "days") and I am trying to add the the "days" to "current_date" and create a new dataframe with new column called "new_date" using spark scala function date_add()

```<code>val newDF = df.withColumn("new_Date", date_add(df("current_date"), df("days").cast("Int")))
</code>```

But looks like the function date_add only accepts Int values and not columns. How can get the desired output in such case? Are there any alternative functions i can use to get the desired output?

spark version: 1.6.0
scala version: 2.10.6

答:
No need to use an UDF, you can do it using an SQL expression:</p>

```<code>val newDF = df.withColumn("new_date", expr("date_add(current_date,days)"))
</code>```

Body:
I have a dataframe df of columns ("id", "current_date", "days") and I am trying to add the the "days" to "current_date" and create a new dataframe with new column called "new_date" using spark scala function date_add()

val newDF = df.withColumn("new_Date", date_add(df("current_date"), df("days").cast("Int")))

But looks like the function date_add only accepts Int values and not columns. How can get the desired output in such case? Are there any alternative functions i can use to get the desired output?

spark version: 1.6.0
scala version: 2.10.6

Body:
No need to use an UDF, you can do it using an SQL expression:

val newDF = df.withColumn("new_date", expr("date_add(current_date,days)"))


问:
Is it always possible for validation accuracy to be as high as training accuracy?
I have a very small dataset (40 training examples, 10 validation examples, 120 classes) for which I'm getting very high accuracies with a very simple model in Keras (batchnorm, flatten, and dense layers only).

My training accuracy is 94-95% and validation accuracy is 76-78%. I know it's overfitting and I have tried a few things. The data is not images, so I cannot augment the data. I also cannot add data because it's a specific type. I'm using two dropout layers with 0.5 levels, and the architecture is very simple so I don't think I can reduce the architecture complexity. I can paste the model if anyone likes.

My question is: Is there ever a situation where validation accuracy cannot be as high as the training accuracy? Is there a limitation based on the size of the dataset? Or is it ALWAYS possible for validation accuracies to match training accuracies and the network just needs the right parameters?

Thank you so much

答:
That's certainly overfitting.

Overfitting doesn't happen only because of "too powerful models", but also, and a lot, because of not enough data, and I'm quite convinced it's your case.

40 examples for 120 classes? That sounds really like a lot of data is missing.


问:
ngIf in angular 2 not working
```<code><div *ngFor="let message of messages">
  <div *ngIf="message.user===user">

  </div>

 <input [(ngModel)]="message"  />
<button (click)="sendMessage()">Send</button>
</code>```

Here user is the variable that I have assigned in the component. That is a string value 'user1'. If message.user === user1 then I need to show something but its not working.

答:
Based on your current code block, you are binding message(object instance) to input with [(ngModel)] in *ngFor, this will lead to error.

also when you type one character in input, it will turn message(object) to string and then lose the original fields(such as user). Maybe this is the reason for your current situation.

here is simple demo may help get out of this.

Title: ngIf in angular 2 not working

Body:
 <input [(ngModel)]="message"  />
<button (click)="sendMessage()">Send</button>

Here user is the variable that I have assigned in the component. That is a string value 'user1'. If message.user === user1 then I need to show something but its not working.


问:
make a text file into a list
This is what my text file consists of:
"file1
file2"

So far this is my code:

```<code>def create_filenames_list(filename):
    filenames_list = []
    file = open('input.txt', "r").readlines()
    for line in file:
            filenames_list = line

    return filenames_list.split()
def main():
    filenames_list = create_filenames_list('input.txt')
    print(filenames_list)
</code>```

The Output I got:
"file2"
What I expected is:
['file1', 'file2']

答:
If your text file had each filename on a separate line then 'file.readlines()' would readily generate the list that you wanted.

Also, you don't need to read the entire file into a variable (file = open('input.txt', "r").readlines()) before looping through it. You can loop directly over the file object (f = open('input.txt',"r")).

Do all of your filenames have to be on a single line as they appear to be? If so you can simply get the first line and then split it into the list.

```<code>filenames_list = open('input.txt',"r").readline().split()
</code>```

In your code the 'file' variable is already a list of each line in your text file. The loop following is looping over that list and ultimately returns only the last line in the file. Finally, you return a list of the space-separated values from only that final line of the file.

Again, if you place each filename on a separate line of the file your code can be very much simplified:

```<code>def create_filenames_list(filename):
  return open(filename,"r").readlines()

def main():
  filenames_list = create_filenames_list('input.txt')
  print(filenames_list)
</code>```

Title: make a text file into a list

Body:
This is what my text file consists of:
"file1
file2"

So far this is my code:

def create_filenames_list(filename):
    filenames_list = []
    file = open('input.txt', "r").readlines()
    for line in file:
            filenames_list = line

    return filenames_list.split()
def main():
    filenames_list = create_filenames_list('input.txt')
    print(filenames_list)

The Output I got:
"file2"
What I expected is:
['file1', 'file2']

Body:
If your text file had each filename on a separate line then 'file.readlines()' would readily generate the list that you wanted.

Also, you don't need to read the entire file into a variable (file = open('input.txt', "r").readlines()) before looping through it. You can loop directly over the file object (f = open('input.txt',"r")).

Do all of your filenames have to be on a single line as they appear to be? If so you can simply get the first line and then split it into the list.

filenames_list = open('input.txt',"r").readline().split()

In your code the 'file' variable is already a list of each line in your text file. The loop following is looping over that list and ultimately returns only the last line in the file. Finally, you return a list of the space-separated values from only that final line of the file.

Again, if you place each filename on a separate line of the file your code can be very much simplified:

def create_filenames_list(filename):
  return open(filename,"r").readlines()

def main():
  filenames_list = create_filenames_list('input.txt')
  print(filenames_list)


问:
how to avoid error of adding string to generator expressions?
I need to iterate over folder names and then over images but I've got this error.  May someone tell me how to avoid the error?</p>

```<code>path = '/.../'

dirs = next(os.walk(path))[1] # get my folder names inside my directory

for i in dirs:
    for img in os.listdir(path+(x for x in dirs)): <------ TypeError: must be str, not generator
        img_path = os.path.join(path,img)
        print(img_path)
</code>```

答:
```<code>import os
path = '/home/'

dirs = next(os.walk(path))[1]  # get folder names inside directory

for i in dirs:
    for img in os.listdir(path+i):
        img_path = os.path.join(path,img)
        print(img_path)
</code>```

In the line below, you're trying to concatenate the generator object and the string path. Instead, you can use i itself, as above.

```<code>path+(x for x in dirs)
</code>```

Body:
I need to iterate over folder names and then over images but I've got this error.  May someone tell me how to avoid the error?

path = '/.../'

dirs = next(os.walk(path))[1] # get my folder names inside my directory

for i in dirs:
    for img in os.listdir(path+(x for x in dirs)): <------ TypeError: must be str, not generator
        img_path = os.path.join(path,img)
        print(img_path)

Body:
import os
path = '/home/'

dirs = next(os.walk(path))[1]  # get folder names inside directory

for i in dirs:
    for img in os.listdir(path+i):
        img_path = os.path.join(path,img)
        print(img_path)

In the line below, you're trying to concatenate the generator object and the string path. Instead, you can use i itself, as above.

path+(x for x in dirs)


问:
Android Web Application Submission process
Any please post me the process of submission of Web app to Android market</p>

答:
Publishing app to Android market?

http://developer.android.com/guide/publishing/publishing.html

http://market.android.com/support/

ContentLicense: CC BY-SA 2.5


问:
Save file in document directory with relative path?
is there any way to save file in document directory with relative path?

I have tried something like this but its not working

```<code>    UIImage *image = [UIImage imageNamed:@"22.png"];
[UIImagePNGRepresentation(image) writeToFile:@"../../Documents/22.png" atomically:true];
</code>```

答:
You need to retrieve the URL to the documents folder from NSFileManager

```<code>NSString *fileName = @"22.png"
UIImage *image = [UIImage imageNamed:fileName];
NSURL *documentsURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory
                                                             inDomain:NSUserDomainMask
                                                    appropriateForURL:nil
                                                               create:NO
                                                                error:nil];
NSURL *fileURL = [documentsURL URLByAppendingPathComponent:fileName];
[UIImagePNGRepresentation(image) writeToURL:fileURL atomically:true];
</code>```

Body:
is there any way to save file in document directory with relative path?

I have tried something like this but its not working

    UIImage *image = [UIImage imageNamed:@"22.png"];
[UIImagePNGRepresentation(image) writeToFile:@"../../Documents/22.png" atomically:true];

Body:
You need to retrieve the URL to the documents folder from NSFileManager

NSString *fileName = @"22.png"
UIImage *image = [UIImage imageNamed:fileName];
NSURL *documentsURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory
                                                             inDomain:NSUserDomainMask
                                                    appropriateForURL:nil
                                                               create:NO
                                                                error:nil];
NSURL *fileURL = [documentsURL URLByAppendingPathComponent:fileName];
[UIImagePNGRepresentation(image) writeToURL:fileURL atomically:true];


问:
Channel never dies although closed
In the following code, i am trying to write all files that are sent to the inputs channel and send a corresponding response over the operationOutcomes channel

main.go

```<code>package main

import(
    lr "github.com/fabulousduck/librarian"
    "fmt"
)

func main() {
    writeOpCount := 100;
    operationOutcomes, inputs := make(chan lr.WriteOpResponse), make(chan lr.WriteOp)
    go lr.WriteC(inputs, operationOutcomes)

    for i := 0; i < writeOpCount; i++ {
        inputs <- lr.WriteOp{ Dest: `../exampleFiles/createdFiles/{i}.txt`, Content: `Invoice #{i}` }
    }

    close(inputs)

    for i := 0; i < writeOpCount; i++ {
        writeResult := <-operationOutcomes
        fmt.Println("Response from write operation : ", writeResult.Msg, "err ", writeResult.Err, "bytes written : ", writeResult.BytesWritten)
    }

    close(operationOutcomes)
}
</code>```

librarian.go
    package librarian

```<code>import(
    "os"
    "fmt"
)

type WriteOp struct {
    Dest, Content string
}

type WriteOpResponse struct {
    Msg error
    Err bool
    BytesWritten int
}

func WriteC (inputChannel <-chan WriteOp, outputChannel chan<- WriteOpResponse) {
    workOp :=  <-inputChannel
    go writeWorker(workOp, outputChannel)
}

func writeWorker (job WriteOp, outGoing chan<- WriteOpResponse) {
    file, err := os.OpenFile(job.Dest, os.O_RDWR, 0666)
    if err != nil {
        fmt.Println("err : ", err)
        outGoing <- WriteOpResponse{ Msg: err, Err: true, BytesWritten: 0 }
    }
    bytesWritten , err := file.WriteString(job.Content)
    if err != nil {
        outGoing <- WriteOpResponse{ Msg: err, Err: true, BytesWritten: 0 }
    }
    outGoing <- WriteOpResponse{ Msg: nil, Err: false, BytesWritten: bytesWritten }
}
</code>```

This throws a deadlock in both cases when there is and isn't an error, even though i am closing both channels when i am done with them ?

答:
You only read from operationOutcomes up to writeOpCount times, even though in writeWorker each execution can result in up to 3 messages being written on that channel (none of your error cases causes the function to return, to it continues processing). Because it's unbuffered and it stops being read, at some point the workers writing to it can no longer add messages and so lock forever.

Also, since you only call WriteC once and it does not loop, it will only ever read and process one message from the inputs. If writeOpCount is > 1, then it will lock forever within the first loop when it tries to queue a second message.

Title: Channel never dies although closed

Body:
In the following code, i am trying to write all files that are sent to the inputs channel and send a corresponding response over the operationOutcomes channel

main.go

package main

import(
    lr "github.com/fabulousduck/librarian"
    "fmt"
)

func main() {
    writeOpCount := 100;
    operationOutcomes, inputs := make(chan lr.WriteOpResponse), make(chan lr.WriteOp)
    go lr.WriteC(inputs, operationOutcomes)

    for i := 0; i < writeOpCount; i++ {
        inputs <- lr.WriteOp{ Dest: `../exampleFiles/createdFiles/{i}.txt`, Content: `Invoice #{i}` }
    }

    close(inputs)

    for i := 0; i < writeOpCount; i++ {
        writeResult := <-operationOutcomes
        fmt.Println("Response from write operation : ", writeResult.Msg, "err ", writeResult.Err, "bytes written : ", writeResult.BytesWritten)
    }

    close(operationOutcomes)
}

librarian.go
    package librarian

import(
    "os"
    "fmt"
)

type WriteOp struct {
    Dest, Content string
}

type WriteOpResponse struct {
    Msg error
    Err bool
    BytesWritten int
}

func WriteC (inputChannel <-chan WriteOp, outputChannel chan<- WriteOpResponse) {
    workOp :=  <-inputChannel
    go writeWorker(workOp, outputChannel)
}

func writeWorker (job WriteOp, outGoing chan<- WriteOpResponse) {
    file, err := os.OpenFile(job.Dest, os.O_RDWR, 0666)
    if err != nil {
        fmt.Println("err : ", err)
        outGoing <- WriteOpResponse{ Msg: err, Err: true, BytesWritten: 0 }
    }
    bytesWritten , err := file.WriteString(job.Content)
    if err != nil {
        outGoing <- WriteOpResponse{ Msg: err, Err: true, BytesWritten: 0 }
    }
    outGoing <- WriteOpResponse{ Msg: nil, Err: false, BytesWritten: bytesWritten }
}

This throws a deadlock in both cases when there is and isn't an error, even though i am closing both channels when i am done with them ?


问:
Combining two python codes for raspberry pi with a servo and ldr sensor
I have Python code running on my raspberry pi 2b and a light sensor, which measures the amount of time it takes for the capacitor of the light sensor to charge and send the pin high:

```<code>import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BOARD)

pin_to_circuit = 7

def rc_time (pin_to_circuit):
    count = 0

    #Output on the pin for
    GPIO.setup(pin_to_circuit, GPIO.OUT)
    GPIO.output(pin_to_circuit, GPIO.LOW)
    time.sleep(0.1)

    #Change the pin back to input
    GPIO.setup(pin_to_circuit, GPIO.IN)

    #Count until the pin goes high
    while (GPIO.input(pin_to_circuit) == GPIO.LOW):
        count += 1

    if count > 1000000:
        return True
    else:
        return count

#Catch when script is interrupted, cleanup correctly
try:
# Main loop
while True:
    print rc_time(pin_to_circuit)
except KeyboardInterrupt:
    pass
finally:
    GPIO.cleanup()
</code>```

I want when the count goes higher than 1000000, a MG90S, that I have also connected to the pi and a 4AA battery pack, moves about 90 degrees.
The code I was trying to integrate to move the servo:

```<code>import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BOARD)
GPIO.setup(12, GPIO.OUT)

p.ChangeDutyCycle(7.5)  # turn towards 90 degree
time.sleep(1) # sleep 1 second
p.stop()
GPIO.cleanup()
</code>```

I want to combine these two Python codes. I tried for a bit, but I have almost no Python experience.

答:
You could just integrate the code block you are using to move the MG90S into a function, insert it before or below your def rc_time (pin_to_circuit): (but first you have to define p inside, its not really clear what p refers to):

New Function from second code block:

```<code>def move_90_degrees():
    p = '???'
    GPIO.setup(12, GPIO.OUT)
    p.ChangeDutyCycle(7.5)  # turn towards 90 degree
    time.sleep(1) # sleep 1 second
    p.stop()
</code>```

After defining this function, call it inside your first block like:

```<code>if count > 1000000:
    move_90_degrees()
    return True
else:
    return count
</code>```

That should work.

Body:
I have Python code running on my raspberry pi 2b and a light sensor, which measures the amount of time it takes for the capacitor of the light sensor to charge and send the pin high:

import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BOARD)

pin_to_circuit = 7

def rc_time (pin_to_circuit):
    count = 0

    #Output on the pin for
    GPIO.setup(pin_to_circuit, GPIO.OUT)
    GPIO.output(pin_to_circuit, GPIO.LOW)
    time.sleep(0.1)

    #Change the pin back to input
    GPIO.setup(pin_to_circuit, GPIO.IN)

    #Count until the pin goes high
    while (GPIO.input(pin_to_circuit) == GPIO.LOW):
        count += 1

    if count > 1000000:
        return True
    else:
        return count

#Catch when script is interrupted, cleanup correctly
try:
# Main loop
while True:
    print rc_time(pin_to_circuit)
except KeyboardInterrupt:
    pass
finally:
    GPIO.cleanup()

I want when the count goes higher than 1000000, a MG90S, that I have also connected to the pi and a 4AA battery pack, moves about 90 degrees.
The code I was trying to integrate to move the servo:

import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BOARD)
GPIO.setup(12, GPIO.OUT)

p.ChangeDutyCycle(7.5)  # turn towards 90 degree
time.sleep(1) # sleep 1 second
p.stop()
GPIO.cleanup()

I want to combine these two Python codes. I tried for a bit, but I have almost no Python experience.

Body:
You could just integrate the code block you are using to move the MG90S into a function, insert it before or below your def rc_time (pin_to_circuit): (but first you have to define p inside, its not really clear what p refers to):

New Function from second code block:

def move_90_degrees():
    p = '???'
    GPIO.setup(12, GPIO.OUT)
    p.ChangeDutyCycle(7.5)  # turn towards 90 degree
    time.sleep(1) # sleep 1 second
    p.stop()

After defining this function, call it inside your first block like:

if count > 1000000:
    move_90_degrees()
    return True
else:
    return count

That should work.


问:
How to group inner list data based on a key in outer list in c# linq
I have a class structure and data as follows:

```<code>   public class Company
{
    public string CompanyName { get; set; }
    public List<Employee> Employees { get; set; }
}
public class Employee
{
    public string EmployeeName { get; set; }
}
  ObservableCollection<Company> list1 = new ObservableCollection<Company>
        { new Company { CompanyName = "com1",
                        Employees = new List<Employee>
                        { new Employee {EmployeeName = "Ron"},
                          new Employee { EmployeeName = "John" },
                          new Employee { EmployeeName = "David"  } } },
        new Company { CompanyName = "com2",
                        Employees = new List<Employee>
                        { new Employee {EmployeeName = "manuel"},
                          new Employee { EmployeeName = "smith" },
                          new Employee { EmployeeName = "rony"  } } },
        new Company { CompanyName = "com3",
                        Employees = new List<Employee>
                        { new Employee {EmployeeName = "kevin"},
                          new Employee { EmployeeName = "chacko" },
                          new Employee { EmployeeName = "willy"  } } }};
</code>```

I want to group employeenames in Employee class based on outer company name in company class. How can i achieve this in linq.

答:
I got it working,
 I have added a class that inherits IEnumerable

```<code>    class GroupViewModel<T> : IEnumerable<T>
{
    public IEnumerable<T> Items { get; private set; }

    public string Name { get; private set; }
    public string Id { get; private set; }
    public GroupViewModel(string name,string id, IEnumerable<T> items)
    {
        this.Id = id;
        this.Name = name;
        this.Items = items;
    }

    public IEnumerator<T> GetEnumerator()
    {
        return this.Items.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return this.Items.GetEnumerator();
    }
}
</code>```

Then i have grouped the list as below:

```<code>            var groupedList = from model in list1
                  group model by new { model.CompanyName,model.Id, model.Employees } into wordCollection
                  select new GroupViewModel<Employee>(wordCollection.Key.CompanyName, wordCollection.Key.Id, wordCollection.Key.Employees);
</code>```

Body:
I have a class structure and data as follows:

   public class Company
{
    public string CompanyName { get; set; }
    public List<Employee> Employees { get; set; }
}
public class Employee
{
    public string EmployeeName { get; set; }
}
  ObservableCollection<Company> list1 = new ObservableCollection<Company>
        { new Company { CompanyName = "com1",
                        Employees = new List<Employee>
                        { new Employee {EmployeeName = "Ron"},
                          new Employee { EmployeeName = "John" },
                          new Employee { EmployeeName = "David"  } } },
        new Company { CompanyName = "com2",
                        Employees = new List<Employee>
                        { new Employee {EmployeeName = "manuel"},
                          new Employee { EmployeeName = "smith" },
                          new Employee { EmployeeName = "rony"  } } },
        new Company { CompanyName = "com3",
                        Employees = new List<Employee>
                        { new Employee {EmployeeName = "kevin"},
                          new Employee { EmployeeName = "chacko" },
                          new Employee { EmployeeName = "willy"  } } }};

I want to group employeenames in Employee class based on outer company name in company class. How can i achieve this in linq.

Body:
I got it working,
 I have added a class that inherits IEnumerable

    class GroupViewModel<T> : IEnumerable<T>
{
    public IEnumerable<T> Items { get; private set; }

    public string Name { get; private set; }
    public string Id { get; private set; }
    public GroupViewModel(string name,string id, IEnumerable<T> items)
    {
        this.Id = id;
        this.Name = name;
        this.Items = items;
    }

    public IEnumerator<T> GetEnumerator()
    {
        return this.Items.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return this.Items.GetEnumerator();
    }
}

Then i have grouped the list as below:

            var groupedList = from model in list1
                  group model by new { model.CompanyName,model.Id, model.Employees } into wordCollection
                  select new GroupViewModel<Employee>(wordCollection.Key.CompanyName, wordCollection.Key.Id, wordCollection.Key.Employees);


问:
Unable to set file-field to nil using CarrierWave
I'm writing a rails 5 app where I have an object called link that has a title, url and picture. The picture is of string type and stores the path for the image uploaded by the user. I want to give the user the option of deleting this image and I set up an action in the links controller but I am trying to set the value of 'picture' to nil but it doesn't do anything.

Here's the output from the rails console:-

```<code>2.4.0 :007 > link = Link.first
  Link Load (0.4ms)  SELECT  "links".* FROM "links" ORDER BY "links"."created_at" DESC LIMIT ?  [["LIMIT", 1]]
 => #<Link id: 20, title: "large", url: "http://www.large.com", user_id: 12, created_at: "2017-06-05 07:59:03", updated_at: "2017-06-05 10:20:30", picture: "dummy5.jpg">
2.4.0 :008 > link.picture
 => #<PictureUploader:0x00000002df4ab0 @model=#<Link id: 20, title: "large", url: "http://www.large.com", user_id: 12, created_at: "2017-06-05 07:59:03", updated_at: "2017-06-05 10:20:30", picture: "dummy5.jpg">, @mounted_as=:picture, @storage=#<CarrierWave::Storage::File:0x00000002df44e8 @uploader=#<PictureUploader:0x00000002df4ab0 ...>>, @file=#<CarrierWave::SanitizedFile:0x00000002ddf9d0 @file="/home/ryarasi/rails/practice/raddit/public/uploads/link/picture/20/dummy5.jpg", @original_filename=nil, @content_type=nil>, @versions={}>
2.4.0 :009 > link.picture=nil
 => nil
2.4.0 :010 > link
 => #<Link id: 20, title: "large", url: "http://www.large.com", user_id: 12, created_at: "2017-06-05 07:59:03", updated_at: "2017-06-05 10:20:30", picture: "dummy5.jpg">
2.4.0 :011 > link.update_attributes(picture:nil)
   (0.1ms)  begin transaction
  User Load (0.1ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT ?  [["id", 12], ["LIMIT", 1]]
  Link Load (0.1ms)  SELECT  "links".* FROM "links" WHERE "links"."id" = ? ORDER BY "links"."created_at" DESC LIMIT ?  [["id", 20], ["LIMIT", 1]]
  SQL (1.2ms)  UPDATE "links" SET "updated_at" = ?, "picture" = ? WHERE "links"."id" = ?  [["updated_at", "2017-06-05 10:21:15.623761"], ["picture", "dummy5.jpg"], ["id", 20]]
   (48.1ms)  commit transaction
 => true
2.4.0 :012 > link
 => #<Link id: 20, title: "large", url: "http://www.large.com", user_id: 12, created_at: "2017-06-05 07:59:03", updated_at: "2017-06-05 10:21:15", picture: "dummy5.jpg">
2.4.0 :013 > link.picture
 => #<PictureUploader:0x00000002df4ab0 @model=#<Link id: 20, title: "large", url: "http://www.large.com", user_id: 12, created_at: "2017-06-05 07:59:03", updated_at: "2017-06-05 10:21:15", picture: "dummy5.jpg">, @mounted_as=:picture, @storage=#<CarrierWave::Storage::File:0x00000002df44e8 @uploader=#<PictureUploader:0x00000002df4ab0 ...>>, @file=#<CarrierWave::SanitizedFile:0x00000002ddf9d0 @file="/home/ryarasi/rails/practice/raddit/public/uploads/link/picture/20/dummy5.jpg", @original_filename=nil, @content_type=nil>, @versions={}>
2.4.0 :014 >
</code>```

I'm able to set the title or the url of the link to nil, but doing so for the picture attribute doesn't do anything. Is this because it's a file_field whereas the title and url are just strings?

Also, here's the schema.rb where picture is actually set as a string:-

```<code>  create_table "links", force: :cascade do |t|
    t.string   "title"
    t.string   "url"
    t.integer  "user_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.string   "picture"
    t.index ["user_id"], name: "index_links_on_user_id"
  end
</code>```

Don't know what to make of this.

More details:-

This is the view for submitting a new link. This is where the picture is uploaded:-

```<code><h1>Submit Link</h1>

<div class="row">
  <div class="col-md-6 col-md-offset-3">

    <%= form_for(@link, url: link_path) do |f| %>
      <%= render partial: 'shared/error_messages',
                 locals: {object: @link} %>

      <%= f.label :title %>
      <%= f.text_field :title, class: 'form-control' %>

      <%= f.label :url %>
      <%= f.text_field :url, class: 'form-control' %>

      <%= f.label :picture %>
      <%= f.file_field :picture,
          accept: 'image/jpeg, image/png, image/gif',
          class: 'form-control' %>

      <%= f.submit "Submit link", class: "btn btn-primary" %>
    <% end %>
  </div>
</div>

<script type="text/javascript">
  $('#micropost_picture').bind('change', function() {
    var size_in_megabytes = this.files[0].size/1024/1024;
    if (size_in_megabytes > 5) {
      alert('Maximum file size is 5MB. Please choose a smaller file.');
    }
  });
</script>
</code>```

link.rb:-

```<code>class Link < ApplicationRecord

  belongs_to :user
  default_scope -> { order(created_at: :desc) }
  mount_uploader :picture, PictureUploader
  validates :title, presence: true
  validates :url, presence: true
  validates :user_id, presence: true
  validate :picture_size
  after_destroy :delete_empty_upload_directory

  def picture_size
    if picture.size > 5.megabytes
      errors.add(:picture, "Should be less than 5MB")
    end
  end

  private

    def delete_empty_upload_directory
      FileUtils.rm_rf(Rails.root.join('public', 'uploads', 'link', 'picture',
                                      self.id.to_s)) if self.picture
    end
end
</code>```

答:
You must use the remove method in CarrierWave</p>

```<code>@link = Link.first
@link.remove_picture!
@link.save
</code>```

Body:
I'm writing a rails 5 app where I have an object called link that has a title, url and picture. The picture is of string type and stores the path for the image uploaded by the user. I want to give the user the option of deleting this image and I set up an action in the links controller but I am trying to set the value of 'picture' to nil but it doesn't do anything.

Here's the output from the rails console:-

2.4.0 :007 > link = Link.first
  Link Load (0.4ms)  SELECT  "links".* FROM "links" ORDER BY "links"."created_at" DESC LIMIT ?  [["LIMIT", 1]]
 => #<Link id: 20, title: "large", url: "http://www.large.com", user_id: 12, created_at: "2017-06-05 07:59:03", updated_at: "2017-06-05 10:20:30", picture: "dummy5.jpg">
2.4.0 :008 > link.picture
 => #<PictureUploader:0x00000002df4ab0 @model=#<Link id: 20, title: "large", url: "http://www.large.com", user_id: 12, created_at: "2017-06-05 07:59:03", updated_at: "2017-06-05 10:20:30", picture: "dummy5.jpg">, @mounted_as=:picture, @storage=#<CarrierWave::Storage::File:0x00000002df44e8 @uploader=#<PictureUploader:0x00000002df4ab0 ...>>, @file=#<CarrierWave::SanitizedFile:0x00000002ddf9d0 @file="/home/ryarasi/rails/practice/raddit/public/uploads/link/picture/20/dummy5.jpg", @original_filename=nil, @content_type=nil>, @versions={}>
2.4.0 :009 > link.picture=nil
 => nil
2.4.0 :010 > link
 => #<Link id: 20, title: "large", url: "http://www.large.com", user_id: 12, created_at: "2017-06-05 07:59:03", updated_at: "2017-06-05 10:20:30", picture: "dummy5.jpg">
2.4.0 :011 > link.update_attributes(picture:nil)
   (0.1ms)  begin transaction
  User Load (0.1ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT ?  [["id", 12], ["LIMIT", 1]]
  Link Load (0.1ms)  SELECT  "links".* FROM "links" WHERE "links"."id" = ? ORDER BY "links"."created_at" DESC LIMIT ?  [["id", 20], ["LIMIT", 1]]
  SQL (1.2ms)  UPDATE "links" SET "updated_at" = ?, "picture" = ? WHERE "links"."id" = ?  [["updated_at", "2017-06-05 10:21:15.623761"], ["picture", "dummy5.jpg"], ["id", 20]]
   (48.1ms)  commit transaction
 => true
2.4.0 :012 > link
 => #<Link id: 20, title: "large", url: "http://www.large.com", user_id: 12, created_at: "2017-06-05 07:59:03", updated_at: "2017-06-05 10:21:15", picture: "dummy5.jpg">
2.4.0 :013 > link.picture
 => #<PictureUploader:0x00000002df4ab0 @model=#<Link id: 20, title: "large", url: "http://www.large.com", user_id: 12, created_at: "2017-06-05 07:59:03", updated_at: "2017-06-05 10:21:15", picture: "dummy5.jpg">, @mounted_as=:picture, @storage=#<CarrierWave::Storage::File:0x00000002df44e8 @uploader=#<PictureUploader:0x00000002df4ab0 ...>>, @file=#<CarrierWave::SanitizedFile:0x00000002ddf9d0 @file="/home/ryarasi/rails/practice/raddit/public/uploads/link/picture/20/dummy5.jpg", @original_filename=nil, @content_type=nil>, @versions={}>
2.4.0 :014 >

I'm able to set the title or the url of the link to nil, but doing so for the picture attribute doesn't do anything. Is this because it's a file_field whereas the title and url are just strings?

Also, here's the schema.rb where picture is actually set as a string:-

  create_table "links", force: :cascade do |t|
    t.string   "title"
    t.string   "url"
    t.integer  "user_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.string   "picture"
    t.index ["user_id"], name: "index_links_on_user_id"
  end

Don't know what to make of this.

More details:-

This is the view for submitting a new link. This is where the picture is uploaded:-

Submit Link

    <%= form_for(@link, url: link_path) do |f| %>
      <%= render partial: 'shared/error_messages',
                 locals: {object: @link} %>

      <%= f.label :title %>
      <%= f.text_field :title, class: 'form-control' %>

      <%= f.label :url %>
      <%= f.text_field :url, class: 'form-control' %>

      <%= f.label :picture %>
      <%= f.file_field :picture,
          accept: 'image/jpeg, image/png, image/gif',
          class: 'form-control' %>

      <%= f.submit "Submit link", class: "btn btn-primary" %>
    <% end %>

link.rb:-

class Link < ApplicationRecord

  belongs_to :user
  default_scope -> { order(created_at: :desc) }
  mount_uploader :picture, PictureUploader
  validates :title, presence: true
  validates :url, presence: true
  validates :user_id, presence: true
  validate :picture_size
  after_destroy :delete_empty_upload_directory

  def picture_size
    if picture.size > 5.megabytes
      errors.add(:picture, "Should be less than 5MB")
    end
  end

  private

    def delete_empty_upload_directory
      FileUtils.rm_rf(Rails.root.join('public', 'uploads', 'link', 'picture',
                                      self.id.to_s)) if self.picture
    end
end

Body:
You must use the remove method in CarrierWave

@link = Link.first
@link.remove_picture!
@link.save


问:
Creating a generic edit view with ASP.NET, MVC, and Entity Framework
In my database, I have 40 tables that contain only an ID number and a name. My database is accessed using Entity Framework. While I have no trouble editing them each by generating a strongly-typed view and postback methods for each object, I would like to create a more generic method and view for viewing and editing these objects.

I am currently using the following code to access each object. In this case, it is for an object of 'AddressType':

```<code>public ActionMethod EditAddressType(int ID)
{
    var result = database.AddressType.Single(a => a.ID == ID);
    View(result);
}

[HttpPost]
public ActionMethod EditAddressType(int ID, FormCollection formValues)
{
    var result = database.AddressType.Single(a => a.ID == ID);
    UpdateModel(result);
    database.SaveChanges();
    return View("SaveSuccess");
}
</code>```

The view 'EditAddressType' is strongly typed and works fine, but there's a lot of repeated code (one instance of this for each object). I've been told that I need to use reflection, but I'm at a loss for how to implement this. My understanding is that I need to retrieve the object type so I can replace the hardcoded reference to the object, but I'm not sure how to get this information from the postback.

I've had success binding the information to ViewData in the controller and passing that to a ViewPage view that knows to look for this ViewData, but I don't know how to postback the changes to a controller.

Thanks for any help you can give me!

答:
If you are going to edit the object you don't need to refetch it from the database in your POST action. The first thing would of course be to abstract my data access code from the controller:

```<code>public class AddressesController: Controller
{
    private readonly IAddressesRepository _repository;
    public AddressesController(IAddressesRepository repository)
    {
        _repository = repository;
    }

    public ActionMethod Edit(int id)
    {
        var result = _repository.GetAddress(id);
        return View(result);
    }

    [HttpPut]
    public ActionMethod Update(AddressViewModel address)
    {
        _repository.Save(address);
        return View("SaveSuccess");
    }
}
</code>```

You will notice that I have renamed some of the actions and accept verbs to make this controller a bit more RESTFul.

The associated view might look like this:

```<code><% using (Html.BeginForm<AddressesController>(c => c.Update(null))) { %>
    <%: Html.HttpMethodOverride(HttpVerbs.Put) %>
    <%: Html.HiddenFor(model => model.Id) %>
    <%: Html.TextBoxFor(model => model.Name) %>
    <input type="submit" value="Save" />
<% } %>
</code>```

As far as the implementation of this IAddressesRepository interface is concerned, that's totally up to you: Entity Framework, NHibernate, XML File, Remote Web Service call, ..., that's an implementation detail that has nothing to do with ASP.NET MVC.

Body:
In my database, I have 40 tables that contain only an ID number and a name. My database is accessed using Entity Framework. While I have no trouble editing them each by generating a strongly-typed view and postback methods for each object, I would like to create a more generic method and view for viewing and editing these objects.

I am currently using the following code to access each object. In this case, it is for an object of 'AddressType':

public ActionMethod EditAddressType(int ID)
{
    var result = database.AddressType.Single(a => a.ID == ID);
    View(result);
}

[HttpPost]
public ActionMethod EditAddressType(int ID, FormCollection formValues)
{
    var result = database.AddressType.Single(a => a.ID == ID);
    UpdateModel(result);
    database.SaveChanges();
    return View("SaveSuccess");
}

The view 'EditAddressType' is strongly typed and works fine, but there's a lot of repeated code (one instance of this for each object). I've been told that I need to use reflection, but I'm at a loss for how to implement this. My understanding is that I need to retrieve the object type so I can replace the hardcoded reference to the object, but I'm not sure how to get this information from the postback.

I've had success binding the information to ViewData in the controller and passing that to a ViewPage view that knows to look for this ViewData, but I don't know how to postback the changes to a controller.

Thanks for any help you can give me!

Body:
If you are going to edit the object you don't need to refetch it from the database in your POST action. The first thing would of course be to abstract my data access code from the controller:

public class AddressesController: Controller
{
    private readonly IAddressesRepository _repository;
    public AddressesController(IAddressesRepository repository)
    {
        _repository = repository;
    }

    public ActionMethod Edit(int id)
    {
        var result = _repository.GetAddress(id);
        return View(result);
    }

    [HttpPut]
    public ActionMethod Update(AddressViewModel address)
    {
        _repository.Save(address);
        return View("SaveSuccess");
    }
}

You will notice that I have renamed some of the actions and accept verbs to make this controller a bit more RESTFul.

The associated view might look like this:

<% using (Html.BeginForm<AddressesController>(c => c.Update(null))) { %>
    <%: Html.HttpMethodOverride(HttpVerbs.Put) %>
    <%: Html.HiddenFor(model => model.Id) %>
    <%: Html.TextBoxFor(model => model.Name) %>
    <input type="submit" value="Save" />
<% } %>

As far as the implementation of this IAddressesRepository interface is concerned, that's totally up to you: Entity Framework, NHibernate, XML File, Remote Web Service call, ..., that's an implementation detail that has nothing to do with ASP.NET MVC.


答:
You're needlessly complicating your code by using listdir. This:

```<code>import os, os.path
path = '/.../'
for d, _, files in os.walk(path):
    for f in files:
        img_path = os.path.join(d, f)
        print(img_path)
</code>```

should be enough.

Title: how to avoid error of adding string to generator expressions?

Body:
You're needlessly complicating your code by using listdir. This:

import os, os.path
path = '/.../'
for d, _, files in os.walk(path):
    for f in files:
        img_path = os.path.join(d, f)
        print(img_path)

should be enough.


问:
MySQL round() not working as expected with sum()
I'm using the following query;

```<code>select round(sum(quantity * calories)) as calories
from tableName;
</code>```

where quantity and calories are of type double and having the values 1.00 & 110.50 respectively. I'm expecting an output of 111, but the above query is instead giving me 110. But if I execute a simple query like the below,

```<code>select round (110.50);
</code>```

It's giving me 111 as the output. I went through this Link, and used a query like the following;

```<code>select round(sum(cast(quantity * calories as char))) as calories
from tableName;
</code>```

but this one also not working for me and giving 110 as output. Can someone tell how to arrive at the desired output of 111?

答:
When you do calculations with floating point numbers, it is better to use decimal(m,d) datatype rather than float / double as both float and double represent approximate numeric data values and are prone to rounding errors when used with calculations.

For your query you can use:

```<code>select round(cast(sum(quantity * calories) as decimal(8,1))) as calories
from tableName;
</code>```

Body:
I'm using the following query;

select round(sum(quantity * calories)) as calories
from tableName;

where quantity and calories are of type double and having the values 1.00 & 110.50 respectively. I'm expecting an output of 111, but the above query is instead giving me 110. But if I execute a simple query like the below,

select round (110.50);

It's giving me 111 as the output. I went through this Link, and used a query like the following;

select round(sum(cast(quantity * calories as char))) as calories
from tableName;

but this one also not working for me and giving 110 as output. Can someone tell how to arrive at the desired output of 111?

Body:
When you do calculations with floating point numbers, it is better to use decimal(m,d) datatype rather than float / double as both float and double represent approximate numeric data values and are prone to rounding errors when used with calculations.

For your query you can use:

select round(cast(sum(quantity * calories) as decimal(8,1))) as calories
from tableName;


问:
Vnode associated file protection bits
I have a vnode and I want to get the protection bits (sticky bit, write bit, etc.) of its associated file. I know I can get the vnode's vattr struct which contains a field called u_short va_mode;  /* files access mode and type */.

However, I was wondering if this is the same thing as the vnode's associated file's mode_t st_mode; /* inode protection mode */. Does anybody know if these would be the same for a given vnode and its associated file?

My final goal is to see if a sticky bit is set for a vnode's assocated file.

答: The st_mode in struct stat is set from the vnode's va_mode, with the addition of a flag based on vnode type (eg VREG or VDIR).  Take a look at http://fxr.watson.org/fxr/source/kern/vfs_vnops.c#L1428; that's the piece of code that fills in the struct stat.</p>

Title: Vnode associated file protection bits


问:
Javascript count down timer based on hours (works in Unbounce)
I need the javascript countdown timer to work based on the hours. For E.g. If it is 5'o clock then clock should reset from one hour. When it's 6'o clock it should again reset and count down should start.

Like in this website -> https://phorge.com.au/the-dental-edge-webinar

I would like to use following JS. So it would be great if it could be modified.

```<code><script>
var startTime = 59.99; //in Minutes
var doneClass = "done"; //optional styling applied to text when timer is done

function startTimer(duration, display) {
  var timer = duration, minutes, seconds;
  var intervalLoop = setInterval(function () {
    minutes = parseInt(timer / 60, 10)
    seconds = parseInt(timer % 60, 10);
    minutes = minutes < 10 ? "0" + minutes : minutes;
    seconds = seconds < 10 ? "0" + seconds : seconds;
    display.textContent = minutes + ":" + seconds;
    if (--timer < 0) {
      document.querySelector("#timer").classList.add(doneClass);
      clearInterval(intervalLoop);
     }
   }, 1000);
}

window.onload = function () {
  var setMinutes = 60 * startTime,
  display = document.querySelector("#timer");
  startTimer(setMinutes, display);
};
/**
    * Do not remove this section; it allows our team to troubleshoot and track feature adoption.
    * TS:0002-03-069
*/
</script>
</code>```

答:
Just get the current time and subtract the minutes and seconds from your startTime. As it's a countdown timer per hour you don't care what hour it is, just how many minutes and seconds are left in it.

var startTime = 59.99; //in Minutes
var doneClass = "done"; //optional styling applied to text when timer is done

function startTimer(duration, display) {
  var timer = duration,
    minutes, seconds;
  var intervalLoop = setInterval(function() {
    minutes = parseInt(timer / 60, 10)
    seconds = parseInt(timer % 60, 10);
    minutes = minutes < 10 ? "0" + minutes : minutes;
    seconds = seconds < 10 ? "0" + seconds : seconds;
    display.textContent = minutes + ":" + seconds;
    if (--timer < 0) {
      document.querySelector("#timer").classList.add(doneClass);
      clearInterval(intervalLoop);
    }
  }, 1000);
}

window.onload = function() {
  var now = new Date();
  var hour = now.getHours();

  if (hour > 12) {
    hour = hour - 11 + " PM"
  } else {
    hour = hour + 1 + " AM"
  }

  document.getElementById("hour").textContent = "Until " + hour;

  var setMinutes = 60 * (startTime - now.getMinutes() - (now.getSeconds() / 100)),
    display = document.querySelector("#timer");

  startTimer(setMinutes, display);
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><span id="timer"></span><br/>
<span id="hour"></span></code>```

Body:
Just get the current time and subtract the minutes and seconds from your startTime. As it's a countdown timer per hour you don't care what hour it is, just how many minutes and seconds are left in it.

var startTime = 59.99; //in Minutes
var doneClass = "done"; //optional styling applied to text when timer is done

function startTimer(duration, display) {
  var timer = duration,
    minutes, seconds;
  var intervalLoop = setInterval(function() {
    minutes = parseInt(timer / 60, 10)
    seconds = parseInt(timer % 60, 10);
    minutes = minutes < 10 ? "0" + minutes : minutes;
    seconds = seconds < 10 ? "0" + seconds : seconds;
    display.textContent = minutes + ":" + seconds;
    if (--timer < 0) {
      document.querySelector("#timer").classList.add(doneClass);
      clearInterval(intervalLoop);
    }
  }, 1000);
}

window.onload = function() {
  var now = new Date();
  var hour = now.getHours();

  if (hour > 12) {
    hour = hour - 11 + " PM"
  } else {
    hour = hour + 1 + " AM"
  }

  document.getElementById("hour").textContent = "Until " + hour;

  var setMinutes = 60 * (startTime - now.getMinutes() - (now.getSeconds() / 100)),
    display = document.querySelector("#timer");

  startTimer(setMinutes, display);
};

<span id="timer"></span><br/>
<span id="hour"></span>


问:
data post to server error using GSM module bby Arduino
+HTTPACTION:1,302,213

what is the solution for this error or what does this error perfectly menas

答:
HTTP Response 302 means "FOUND" which means you are being redirected to another address.  You need to read the full response, extract the URL they're redirecting you to (Labelled as Location: hxxp://www.someurl,) then request that address instead.

If you're getting this for every URL, it may be that your SIM has not been activated for Data.

Possible Duplicate of this Arduino GSM Shield WebClient 302


问:
Install VS 2008 Team Developer on Windows 7
Has anyone successfully installed VS 2008 Team Developer edition on the Windows 7 beta yet?  Every time I try, i get an error about insufficient privileges in C:\Windows\Winsxs.

I was able to install the VS 2008 Team Database edition with no problems, and had thought that maybe installing the Dev edition after the DB edition might take care of the winsxs issue, but still no luck.

VS Error Message Image http://img152.imageshack.us/img152/7263/snipimagewd8.jpg

Edit: My install is on the 32 bit version of windows.  Looks like the 64 bit version works - has anyone tried it on 32 bit windows 7?

Edit: I tried turning off UAC, no luck.  Then, tried to install just the "team developer tools" portion (since I already had team DB installed) - and got the same error, only this time it includes an "ignore" button.  Clicked ignore, only to get another error with no ignore, this time for C:\Windows\Winsxs\Policies folder.  Only option at that point is to cancel out of the install.

答: Might try disabling UAC completely if you haven't already.  Just search User Access Control in the control panel or something and it should show up.</p>

OwnerDisplayName: Scott

LastEditorDisplayName: Scott


问:
CASE Statement to select a particular value if value exists in another table
I have a requirement where I need to order the records in the result set cursor returned by a stored procedure in a particular order. For example, assume that the SP returned 10 records.The result contains a field named FLD1. The records whose FLD1 value is present in another table must be placed at the top of the result set. That is the records whose FLD1 value returns results when used in a query like SELECT * FROM RESULTS WHERE FLD1 IN (SELECT FLD2 FROM TABLE2) must be placed at the top of the result set and the records which do not return any records must come afterward.

The approach I am following is to first select the records which satisfy the condition FLD1 IN (SELECT FLD2 FROM TABLE2) and assign a seq.no 1 and store the results in a temp table. Then select the records which do not satisfy the condition FLD1 IN (SELECT FLD2 FROM TABLE2) and assign them a sequence 2. Finally, merge the results and open a result cursor at the end of the SP ordering by the Sequence number.

Please suggest any better approach if you know of one. I was thinking of using a CASE statement like CASE WHEN FLD1 IN (SELECT FLD2 FROM TABLE2) THEN "1" ELSE "2". But this does not seem to work in DB2.

答:
It looks like the IN predicate is not valid in the CASE statement.

This works for me, as long as the assumptions are correct:

```<code>create table test1
  (field1 Char(25),
   field2 Char(5));

create table test2
  (field1 Char(5),
   descrip Char(25));

insert into test1
  values  ('This is line 1', 'OK'),
          ('This is line 2', 'FAIL'),
          ('This is line 3', 'OK'),
          ('This is line 4', 'FAIL');

insert into test2
  values ('OK', 'This is a valid code');

select field1,
       field2,
       case
         when (select field2 from test2
               where a.field2 = field1) is not null then '1'
         else '2'
       end seq
  from test1 a
  order by 3, 1;
</code>```

The results are:

```
FIELD1          FIELD2  SEQ
==============  ======  ===
This is line 1   OK      1
This is line 3   OK      1
This is line 2   FAIL    2
This is line 4   FAIL    2
```

Body:
It looks like the IN predicate is not valid in the CASE statement.

This works for me, as long as the assumptions are correct:

create table test1
  (field1 Char(25),
   field2 Char(5));

create table test2
  (field1 Char(5),
   descrip Char(25));

insert into test1
  values  ('This is line 1', 'OK'),
          ('This is line 2', 'FAIL'),
          ('This is line 3', 'OK'),
          ('This is line 4', 'FAIL');

insert into test2
  values ('OK', 'This is a valid code');

select field1,
       field2,
       case
         when (select field2 from test2
               where a.field2 = field1) is not null then '1'
         else '2'
       end seq
  from test1 a
  order by 3, 1;

The results are:

FIELD1          FIELD2  SEQ
==============  ======  ===
This is line 1   OK      1
This is line 3   OK      1
This is line 2   FAIL    2
This is line 4   FAIL    2


问:
get repeated values in JSON object with javascript (JQuery)
I have this JSON object:

```<code>[
    {
        "idMaterial": "Alloy 450 (15Cr6Ni1.5Cu)_S45000",
        "tipoMaterial": "Alloy 450 (15Cr6Ni1.5Cu)",
        "uns": "S45000",
        "temperatura": "NL",
        "ph": "≥3,5",
        "concetracionClMax": "NL",
        "azufreElemental": "ND",
        "tratamientoTermico": "Recocido + endurecimiento por envejecido a 620ºC",
        "dureza": "31",
        "comentarios": "Cualquier combinación ",
        "origen": "NORMATIVA",
        "idEnsayo": "",
        "susceptibilidadSsc": null,
        "tipoResultado": "A",
        "ensayos": null,
        "h2S": "0,103"
    },
    {
        "idMaterial": "AISI 415 (12Cr5NiMo)_S41500",
        "tipoMaterial": "AISI 415 (12Cr5NiMo)",
        "uns": "S41500",
        "temperatura": "NL",
        "ph": "≥3,5",
        "concetracionClMax": "NL",
        "azufreElemental": "ND",
        "tratamientoTermico": "Austenitizado + templado + doble revenido",
        "dureza": "23",
        "comentarios": "Cualquier combinación de T y [Cl] en medios de producción es aceptable",
        "origen": "NORMATIVA",
        "idEnsayo": "",
        "susceptibilidadSsc": null,
        "tipoResultado": "A",
        "ensayos": null,
        "h2S": "0,103"
    },
    {
        "idMaterial": "13Cr4NiMo_S42400",
        "tipoMaterial": "13Cr4NiMo",
        "uns": "S42400",
        "temperatura": "NL",
        "ph": "≥3,5",
        "concetracionClMax": "NL",
        "azufreElemental": "No",
        "tratamientoTermico": "Austenitizado + templado + doble revenido",
        "dureza": "23",
        "comentarios": "Cualquier combinación de T y [Cl] en medios de producción es aceptable",
        "origen": "NORMATIVA",
        "idEnsayo": "",
        "susceptibilidadSsc": null,
        "tipoResultado": "A",
        "ensayos": null,
        "h2S": "0,103"
    },
    {
        "idMaterial": "13Cr5Ni2Mo (Súper 13 Cr)_S41425",
        "tipoMaterial": "13Cr5Ni2Mo (Súper 13 Cr)",
        "uns": "S41425",
        "temperatura": "NL",
        "ph": "≥3,5",
        "concetracionClMax": "NL",
        "azufreElemental": "No",
        "tratamientoTermico": "Austenitizado + templado + revenido",
        "dureza": "28",
        "comentarios": "Cualquier combinación de T y [Cl] en medios de producción es aceptable",
        "origen": "NORMATIVA",
        "idEnsayo": "",
        "susceptibilidadSsc": null,
        "tipoResultado": "A",
        "ensayos": null,
        "h2S": "0,103"
    },
    {
        "idMaterial": "13Cr5Ni2Mo (Súper 13 Cr)_S41426",
        "tipoMaterial": "13Cr5Ni2Mo (Súper 13 Cr)",
        "uns": "S41426",
        "temperatura": "NL",
        "ph": "≥3,5",
        "concetracionClMax": "NL",
        "azufreElemental": "No",
        "tratamientoTermico": "Austenitizado + templado + revenido",
        "dureza": "27",
        "comentarios": "Grado máximo 105 Ksi. Cualquier combinación de T y [Cl] en medios de producción es aceptable",
        "origen": "NORMATIVA",
        "idEnsayo": "",
        "susceptibilidadSsc": null,
        "tipoResultado": "A",
        "ensayos": null,
        "h2S": "0,103"
    },
    {
        "idMaterial": "13Cr4Ni_S41429",
        "tipoMaterial": "13Cr4Ni",
        "uns": "S41429",
        "temperatura": "NL",
        "ph": "≥4,5",
        "concetracionClMax": "NL",
        "azufreElemental": "ND",
        "tratamientoTermico": "templado + revenido o normalizado +revenido",
        "dureza": "27",
        "comentarios": "Grado máximo 120 Ksi .Cualquier combinación de T y [Cl] en medios de producción es aceptable",
        "origen": "NORMATIVA",
        "idEnsayo": "",
        "susceptibilidadSsc": null,
        "tipoResultado": "A",
        "ensayos": null,
        "h2S": "0,103"
    }
]
</code>```

and that I want is to get all the repeated objects with the same "idMaterial" and "uns" value and put them in other object. Thanks for all (I havn't write all JSON data because is too long).

答:
Assign your object to a variable,

```<code>var obj = [
    {
        "idMaterial": "Alloy 450 (15Cr6Ni1.5Cu)_S45000",
        "tipoMaterial": "Alloy 450 (15Cr6Ni1.5Cu)",
        "uns": "S45000",
        "temperatura": "NL",
        "ph": "≥3,5",
        "concetracionClMax": "NL",
        "azufreElemental": "ND",
        "tratamientoTermico": "Recocido + endurecimiento por envejecido a 620ºC",
        "dureza": "31",
        "comentarios": "Cualquier combinación ",
        "origen": "NORMATIVA",
        "idEnsayo": "",
        "susceptibilidadSsc": null,
        "tipoResultado": "A",
        "ensayos": null,
        "h2S": "0,103"
    },
    {
        "idMaterial": "AISI 415 (12Cr5NiMo)_S41500",
        "tipoMaterial": "AISI 415 (12Cr5NiMo)",
        "uns": "S41500",
        "temperatura": "NL",
        "ph": "≥3,5",
        "concetracionClMax": "NL",
        "azufreElemental": "ND",
        "tratamientoTermico": "Austenitizado + templado + doble revenido",
        "dureza": "23",
        "comentarios": "Cualquier combinación de T y [Cl] en medios de producción es aceptable",
        "origen": "NORMATIVA",
        "idEnsayo": "",
        "susceptibilidadSsc": null,
        "tipoResultado": "A",
        "ensayos": null,
        "h2S": "0,103"
    },
    {
        "idMaterial": "13Cr4NiMo_S42400",
        "tipoMaterial": "13Cr4NiMo",
        "uns": "S42400",
        "temperatura": "NL",
        "ph": "≥3,5",
        "concetracionClMax": "NL",
        "azufreElemental": "No",
        "tratamientoTermico": "Austenitizado + templado + doble revenido",
        "dureza": "23",
        "comentarios": "Cualquier combinación de T y [Cl] en medios de producción es aceptable",
        "origen": "NORMATIVA",
        "idEnsayo": "",
        "susceptibilidadSsc": null,
        "tipoResultado": "A",
        "ensayos": null,
        "h2S": "0,103"
    },
    {
        "idMaterial": "13Cr5Ni2Mo (Súper 13 Cr)_S41425",
        "tipoMaterial": "13Cr5Ni2Mo (Súper 13 Cr)",
        "uns": "S41425",
        "temperatura": "NL",
        "ph": "≥3,5",
        "concetracionClMax": "NL",
        "azufreElemental": "No",
        "tratamientoTermico": "Austenitizado + templado + revenido",
        "dureza": "28",
        "comentarios": "Cualquier combinación de T y [Cl] en medios de producción es aceptable",
        "origen": "NORMATIVA",
        "idEnsayo": "",
        "susceptibilidadSsc": null,
        "tipoResultado": "A",
        "ensayos": null,
        "h2S": "0,103"
    },
    {
        "idMaterial": "13Cr5Ni2Mo (Súper 13 Cr)_S41426",
        "tipoMaterial": "13Cr5Ni2Mo (Súper 13 Cr)",
        "uns": "S41426",
        "temperatura": "NL",
        "ph": "≥3,5",
        "concetracionClMax": "NL",
        "azufreElemental": "No",
        "tratamientoTermico": "Austenitizado + templado + revenido",
        "dureza": "27",
        "comentarios": "Grado máximo 105 Ksi. Cualquier combinación de T y [Cl] en medios de producción es aceptable",
        "origen": "NORMATIVA",
        "idEnsayo": "",
        "susceptibilidadSsc": null,
        "tipoResultado": "A",
        "ensayos": null,
        "h2S": "0,103"
    },
    {
        "idMaterial": "13Cr4Ni_S41429",
        "tipoMaterial": "13Cr4Ni",
        "uns": "S41429",
        "temperatura": "NL",
        "ph": "≥4,5",
        "concetracionClMax": "NL",
        "azufreElemental": "ND",
        "tratamientoTermico": "templado + revenido o normalizado +revenido",
        "dureza": "27",
        "comentarios": "Grado máximo 120 Ksi .Cualquier combinación de T y [Cl] en medios de producción es aceptable",
        "origen": "NORMATIVA",
        "idEnsayo": "",
        "susceptibilidadSsc": null,
        "tipoResultado": "A",
        "ensayos": null,
        "h2S": "0,103"
    }
]
</code>```

Use the .map function to fetch the fields.

```<code>function grabFields(item, index) {
    var idMaterial = item.idMaterial;
    var uns = item.uns;
    return {
       idMaterial: idMaterial,
       uns: uns
    }
}
</code>```

Output the fetched values to screen.

```<code>console.log(obj.map(grabFields));
</code>```

Body:
I have this JSON object:

[
    {
        "idMaterial": "Alloy 450 (15Cr6Ni1.5Cu)_S45000",
        "tipoMaterial": "Alloy 450 (15Cr6Ni1.5Cu)",
        "uns": "S45000",
        "temperatura": "NL",
        "ph": "≥3,5",
        "concetracionClMax": "NL",
        "azufreElemental": "ND",
        "tratamientoTermico": "Recocido + endurecimiento por envejecido a 620ºC",
        "dureza": "31",
        "comentarios": "Cualquier combinación ",
        "origen": "NORMATIVA",
        "idEnsayo": "",
        "susceptibilidadSsc": null,
        "tipoResultado": "A",
        "ensayos": null,
        "h2S": "0,103"
    },
    {
        "idMaterial": "AISI 415 (12Cr5NiMo)_S41500",
        "tipoMaterial": "AISI 415 (12Cr5NiMo)",
        "uns": "S41500",
        "temperatura": "NL",
        "ph": "≥3,5",
        "concetracionClMax": "NL",
        "azufreElemental": "ND",
        "tratamientoTermico": "Austenitizado + templado + doble revenido",
        "dureza": "23",
        "comentarios": "Cualquier combinación de T y [Cl] en medios de producción es aceptable",
        "origen": "NORMATIVA",
        "idEnsayo": "",
        "susceptibilidadSsc": null,
        "tipoResultado": "A",
        "ensayos": null,
        "h2S": "0,103"
    },
    {
        "idMaterial": "13Cr4NiMo_S42400",
        "tipoMaterial": "13Cr4NiMo",
        "uns": "S42400",
        "temperatura": "NL",
        "ph": "≥3,5",
        "concetracionClMax": "NL",
        "azufreElemental": "No",
        "tratamientoTermico": "Austenitizado + templado + doble revenido",
        "dureza": "23",
        "comentarios": "Cualquier combinación de T y [Cl] en medios de producción es aceptable",
        "origen": "NORMATIVA",
        "idEnsayo": "",
        "susceptibilidadSsc": null,
        "tipoResultado": "A",
        "ensayos": null,
        "h2S": "0,103"
    },
    {
        "idMaterial": "13Cr5Ni2Mo (Súper 13 Cr)_S41425",
        "tipoMaterial": "13Cr5Ni2Mo (Súper 13 Cr)",
        "uns": "S41425",
        "temperatura": "NL",
        "ph": "≥3,5",
        "concetracionClMax": "NL",
        "azufreElemental": "No",
        "tratamientoTermico": "Austenitizado + templado + revenido",
        "dureza": "28",
        "comentarios": "Cualquier combinación de T y [Cl] en medios de producción es aceptable",
        "origen": "NORMATIVA",
        "idEnsayo": "",
        "susceptibilidadSsc": null,
        "tipoResultado": "A",
        "ensayos": null,
        "h2S": "0,103"
    },
    {
        "idMaterial": "13Cr5Ni2Mo (Súper 13 Cr)_S41426",
        "tipoMaterial": "13Cr5Ni2Mo (Súper 13 Cr)",
        "uns": "S41426",
        "temperatura": "NL",
        "ph": "≥3,5",
        "concetracionClMax": "NL",
        "azufreElemental": "No",
        "tratamientoTermico": "Austenitizado + templado + revenido",
        "dureza": "27",
        "comentarios": "Grado máximo 105 Ksi. Cualquier combinación de T y [Cl] en medios de producción es aceptable",
        "origen": "NORMATIVA",
        "idEnsayo": "",
        "susceptibilidadSsc": null,
        "tipoResultado": "A",
        "ensayos": null,
        "h2S": "0,103"
    },
    {
        "idMaterial": "13Cr4Ni_S41429",
        "tipoMaterial": "13Cr4Ni",
        "uns": "S41429",
        "temperatura": "NL",
        "ph": "≥4,5",
        "concetracionClMax": "NL",
        "azufreElemental": "ND",
        "tratamientoTermico": "templado + revenido o normalizado +revenido",
        "dureza": "27",
        "comentarios": "Grado máximo 120 Ksi .Cualquier combinación de T y [Cl] en medios de producción es aceptable",
        "origen": "NORMATIVA",
        "idEnsayo": "",
        "susceptibilidadSsc": null,
        "tipoResultado": "A",
        "ensayos": null,
        "h2S": "0,103"
    }
]

and that I want is to get all the repeated objects with the same "idMaterial" and "uns" value and put them in other object. Thanks for all (I havn't write all JSON data because is too long).

Body:
Assign your object to a variable,

var obj = [
    {
        "idMaterial": "Alloy 450 (15Cr6Ni1.5Cu)_S45000",
        "tipoMaterial": "Alloy 450 (15Cr6Ni1.5Cu)",
        "uns": "S45000",
        "temperatura": "NL",
        "ph": "≥3,5",
        "concetracionClMax": "NL",
        "azufreElemental": "ND",
        "tratamientoTermico": "Recocido + endurecimiento por envejecido a 620ºC",
        "dureza": "31",
        "comentarios": "Cualquier combinación ",
        "origen": "NORMATIVA",
        "idEnsayo": "",
        "susceptibilidadSsc": null,
        "tipoResultado": "A",
        "ensayos": null,
        "h2S": "0,103"
    },
    {
        "idMaterial": "AISI 415 (12Cr5NiMo)_S41500",
        "tipoMaterial": "AISI 415 (12Cr5NiMo)",
        "uns": "S41500",
        "temperatura": "NL",
        "ph": "≥3,5",
        "concetracionClMax": "NL",
        "azufreElemental": "ND",
        "tratamientoTermico": "Austenitizado + templado + doble revenido",
        "dureza": "23",
        "comentarios": "Cualquier combinación de T y [Cl] en medios de producción es aceptable",
        "origen": "NORMATIVA",
        "idEnsayo": "",
        "susceptibilidadSsc": null,
        "tipoResultado": "A",
        "ensayos": null,
        "h2S": "0,103"
    },
    {
        "idMaterial": "13Cr4NiMo_S42400",
        "tipoMaterial": "13Cr4NiMo",
        "uns": "S42400",
        "temperatura": "NL",
        "ph": "≥3,5",
        "concetracionClMax": "NL",
        "azufreElemental": "No",
        "tratamientoTermico": "Austenitizado + templado + doble revenido",
        "dureza": "23",
        "comentarios": "Cualquier combinación de T y [Cl] en medios de producción es aceptable",
        "origen": "NORMATIVA",
        "idEnsayo": "",
        "susceptibilidadSsc": null,
        "tipoResultado": "A",
        "ensayos": null,
        "h2S": "0,103"
    },
    {
        "idMaterial": "13Cr5Ni2Mo (Súper 13 Cr)_S41425",
        "tipoMaterial": "13Cr5Ni2Mo (Súper 13 Cr)",
        "uns": "S41425",
        "temperatura": "NL",
        "ph": "≥3,5",
        "concetracionClMax": "NL",
        "azufreElemental": "No",
        "tratamientoTermico": "Austenitizado + templado + revenido",
        "dureza": "28",
        "comentarios": "Cualquier combinación de T y [Cl] en medios de producción es aceptable",
        "origen": "NORMATIVA",
        "idEnsayo": "",
        "susceptibilidadSsc": null,
        "tipoResultado": "A",
        "ensayos": null,
        "h2S": "0,103"
    },
    {
        "idMaterial": "13Cr5Ni2Mo (Súper 13 Cr)_S41426",
        "tipoMaterial": "13Cr5Ni2Mo (Súper 13 Cr)",
        "uns": "S41426",
        "temperatura": "NL",
        "ph": "≥3,5",
        "concetracionClMax": "NL",
        "azufreElemental": "No",
        "tratamientoTermico": "Austenitizado + templado + revenido",
        "dureza": "27",
        "comentarios": "Grado máximo 105 Ksi. Cualquier combinación de T y [Cl] en medios de producción es aceptable",
        "origen": "NORMATIVA",
        "idEnsayo": "",
        "susceptibilidadSsc": null,
        "tipoResultado": "A",
        "ensayos": null,
        "h2S": "0,103"
    },
    {
        "idMaterial": "13Cr4Ni_S41429",
        "tipoMaterial": "13Cr4Ni",
        "uns": "S41429",
        "temperatura": "NL",
        "ph": "≥4,5",
        "concetracionClMax": "NL",
        "azufreElemental": "ND",
        "tratamientoTermico": "templado + revenido o normalizado +revenido",
        "dureza": "27",
        "comentarios": "Grado máximo 120 Ksi .Cualquier combinación de T y [Cl] en medios de producción es aceptable",
        "origen": "NORMATIVA",
        "idEnsayo": "",
        "susceptibilidadSsc": null,
        "tipoResultado": "A",
        "ensayos": null,
        "h2S": "0,103"
    }
]

Use the .map function to fetch the fields.

function grabFields(item, index) {
    var idMaterial = item.idMaterial;
    var uns = item.uns;
    return {
       idMaterial: idMaterial,
       uns: uns
    }
}

Output the fetched values to screen.

console.log(obj.map(grabFields));


问:
Apply css from another file to an echo statement from the ajax call
I have a registration page (say reg.php) with a form and I am using ajax for validation of the form elements (say username).
Now, if the username already exists in the db, I want to display the error message in red and if it is available I want it to be in green.
It is working if I style the echo statement like this-

```<code>echo "<span style='color:brown; font-size:14px'><b>Oophs! </b>Looks like username is already in use.</span>";
</code>```

But I want to style it from an another css file. How can I do it?

答:
<blockquote>
       if style it from an another css file
       for ex this css file is style.css
        write bellow line in your style.css
</blockquote>

```<code>  .error_msg {
           color:brown;
          font-size:14px
    }
  .success_msg {
          color:gree;
          font-size:14px
    }

//load style.css on your html page
    <link href="css/style.css" type="text/css" rel="stylesheet">
    echo "<span class='error_msg'><b>Oophs! </b>Looks like username is already in use.</span>";
</code>```

Body:
I have a registration page (say reg.php) with a form and I am using ajax for validation of the form elements (say username).
Now, if the username already exists in the db, I want to display the error message in red and if it is available I want it to be in green.
It is working if I style the echo statement like this-

echo "Oophs! Looks like username is already in use.";

But I want to style it from an another css file. How can I do it?

Body:
       if style it from an another css file
       for ex this css file is style.css
        write bellow line in your style.css

  .error_msg {
           color:brown;
          font-size:14px
    }
  .success_msg {
          color:gree;
          font-size:14px
    }

//load style.css on your html page
    <link href="css/style.css" type="text/css" rel="stylesheet">
    echo "<span class='error_msg'><b>Oophs! </b>Looks like username is already in use.</span>";


问:
Pressing back button shows same activity
I have two Activities.

LoginActivity

HomeScreen

I also have a splash screen with this setting:

```<code><activity android:name=".SplashScreen"
            android:theme="@style/AppTheme.NoActionBar"
            android:noHistory="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
</activity>
</code>```

The Splash Screen then transfers the user to the HomeScreen by using this code:

```<code>Intent intent = new Intent(SplashScreen.this, HomeScreen.class);
</code>```

Inside the HomeScreen Activity, I check if the user is already signed in or not. If he's not signed in, I transfer him to the LoginActivity:

```<code> mAuthListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(FirebaseAuth firebaseAuth) {
                if(firebaseAuth.getCurrentUser() == null)
                {
                    Intent intent = new Intent(HomeScreen.this,LoginActivity.class);
                    Toast.makeText(HomeScreen.this,"H>L on no login",Toast.LENGTH_LONG).show(); //toast to show me why my app is in infinite loop
                    startActivity(intent);
                }
            }
        };
</code>```

On the LoginActivity, I have a simple Login button which uses FireBase Google Authentication. Also, I check if the user is already signed in or not, and if he is, he's transferred to HomeScreen Activity:

```<code>mAuthListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                if(firebaseAuth.getCurrentUser() != null)
                {
                    Intent intent = new Intent(LoginActivity.this,HomeScreen.class);
                    Toast.makeText(LoginActivity.this,"L>H already signed in",Toast.LENGTH_LONG).show();
                    startActivity(intent);
                }
            }
        };
</code>```

And, also:

```<code>private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
        Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());

        AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
        mAuth.signInWithCredential(credential)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful()) {
                            Intent intent = new Intent(LoginActivity.this,HomeScreen.class);
                            Toast.makeText(LoginActivity.this,"L>H on login",Toast.LENGTH_LONG).show();
                            startActivity(intent);
                        } else {
                            // If sign in fails, display a message to the user.
                            Log.w(TAG, "signInWithCredential:failure", task.getException());
                            Toast.makeText(LoginActivity.this, "Authentication failed.",
                                    Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }
</code>```

Now, the problem is: When I open the app, I get a splash screen and I'm transferred to the Login page. Then when I press back, I get the Login page AGAIN instead of exiting the app. Also, once I'm singed in: I get the splash screen and I'm taken to the HomeScreen. Then if I press back, I am taken to the HomeScreen AGAIN instead of exiting the app.

Please help me out. I searched StackOverflow, but didn't quite reach anywhere. Any help is appreciated. Ask me for updates if you need more info! :)

答:
I am not sure it is correct, please try,

Instead of calling startActivity(new Intent(HomeScreen.this,LoginActivity.class))  from onAuthStateChanged(), simply call finish(). Hope it may help you.

Body:
I have two Activities.

LoginActivity

HomeScreen

I also have a splash screen with this setting:

<activity android:name=".SplashScreen"
            android:theme="@style/AppTheme.NoActionBar"
            android:noHistory="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
</activity>

The Splash Screen then transfers the user to the HomeScreen by using this code:

Intent intent = new Intent(SplashScreen.this, HomeScreen.class);

Inside the HomeScreen Activity, I check if the user is already signed in or not. If he's not signed in, I transfer him to the LoginActivity:

 mAuthListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(FirebaseAuth firebaseAuth) {
                if(firebaseAuth.getCurrentUser() == null)
                {
                    Intent intent = new Intent(HomeScreen.this,LoginActivity.class);
                    Toast.makeText(HomeScreen.this,"H>L on no login",Toast.LENGTH_LONG).show(); //toast to show me why my app is in infinite loop
                    startActivity(intent);
                }
            }
        };

On the LoginActivity, I have a simple Login button which uses FireBase Google Authentication. Also, I check if the user is already signed in or not, and if he is, he's transferred to HomeScreen Activity:

mAuthListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                if(firebaseAuth.getCurrentUser() != null)
                {
                    Intent intent = new Intent(LoginActivity.this,HomeScreen.class);
                    Toast.makeText(LoginActivity.this,"L>H already signed in",Toast.LENGTH_LONG).show();
                    startActivity(intent);
                }
            }
        };

And, also:

private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
        Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());

        AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
        mAuth.signInWithCredential(credential)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful()) {
                            Intent intent = new Intent(LoginActivity.this,HomeScreen.class);
                            Toast.makeText(LoginActivity.this,"L>H on login",Toast.LENGTH_LONG).show();
                            startActivity(intent);
                        } else {
                            // If sign in fails, display a message to the user.
                            Log.w(TAG, "signInWithCredential:failure", task.getException());
                            Toast.makeText(LoginActivity.this, "Authentication failed.",
                                    Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

Now, the problem is: When I open the app, I get a splash screen and I'm transferred to the Login page. Then when I press back, I get the Login page AGAIN instead of exiting the app. Also, once I'm singed in: I get the splash screen and I'm taken to the HomeScreen. Then if I press back, I am taken to the HomeScreen AGAIN instead of exiting the app.

Please help me out. I searched StackOverflow, but didn't quite reach anywhere. Any help is appreciated. Ask me for updates if you need more info! :)


问:
Chrome dev tools: Accessing the DOM element $0 pointer from bookmarklet/Snippet
Is it possible to access the $0 DOM element pointer from bookmarklet or snippet in console.?

More info about $0

https://developers.google.com/chrome-developer-tools/docs/commandline-api#0_-_4

Dev Tools remembers the last five DOM elements (or JavaScript heap objects) that you've selected in the tab (or Profiles panel). It makes those objects available as $0, $1, $2, $3, and $4. $0 returns the most recently selected element or JavaScript object, $1 returns the second most recently selected one, and so on.

答: In the bookmark I simply used angular.element(this.document) instead of angular.element($0) and it worked for me.