问:
Change styling for specific jQuery UI object (selectmenu) and not all
I have two selectmenus. I want to change the look and feel of one of them. This is what I tried so far: Add two  selects then within the style tag, i tried to change the class ui-selectmenu-button and ui-selectmenu-text for only select1 but no luck.

```<code>// JS
<script>
$("#select1").selectmenu();
$("#select2").selectmenu();
</script>

 // HTML
<select id="select1">
<option value="1"> 1 </option>
</select>
<select id="select2">
<option value="2"> 2 </option>
</select>

// CSS
<style>
#select1 .ui-selectmenu-button{
    background: rgb(12,27,37);
}

#select1 .ui-selectmenu-text{
   color: white;
}
</style>
</code>```

If i simply do the thing below, it will work but change all the jquery ui selectmenus and i only want it to work for select1 in this example.

```<code><style>
.ui-selectmenu-button{
    background: rgb(12,27,37);
}
</style>
</code>```

答:
You can target it using the Adjacent sibling connector.

```<code>#select1+.ui-selectmenu-button{
   background: rgb(12,27,37);
}
</code>```

Since the #select1 element will be hidden, but still be preceding the code generated by jQuery UI, you can target it with the '+' sign in CSS.

https://jsfiddle.net/jkrielaars/vadt8neh/

Body:
I have two selectmenus. I want to change the look and feel of one of them. This is what I tried so far: Add two  selects then within the style tag, i tried to change the class ui-selectmenu-button and ui-selectmenu-text for only select1 but no luck.

// JS

 // HTML
<select id="select1">
<option value="1"> 1 </option>
</select>
<select id="select2">
<option value="2"> 2 </option>
</select>

// CSS

If i simply do the thing below, it will work but change all the jquery ui selectmenus and i only want it to work for select1 in this example.

Body:
You can target it using the Adjacent sibling connector.

#select1+.ui-selectmenu-button{
   background: rgb(12,27,37);
}

Since the #select1 element will be hidden, but still be preceding the code generated by jQuery UI, you can target it with the '+' sign in CSS.

https://jsfiddle.net/jkrielaars/vadt8neh/


来源: stackexchange

问:
What if server didn't receive fd_close
I have a high performance client server system programmed from the scratch. i am still improving my system. the server using io overlapping to handle connections. the server correctly handles disconnections and resource deallocations. at the client side i used shutdown command with sd_receive  to notify the server that the client has no data to receive after final send from the client. this works well. and server detects that as a graceful disconnection. rarely i have observed when the connection is very slow the server doesn't detect this. I feel that the shutdown partial closure doesn't reach the server. how can i handle this. this is important the server shouldn't contain this kind of connections if so the server can not be stopped. and i do not want to close all such connection by force.</p>

答:
at the client side i used shutdown command with sd_receive to notify the server that the client has no data to receive after final send from the client.

It doesn't do that.

this works well

It doesn't work at all. The shutdown command with SD_RECEIVE that you're using is completely pointless. A close, or a shutdown with SD_SEND or SD_BOTH, sends a FIN: shutdown with SD_RECEIVE does exactly nothing on the wire, and specifically it does not 'notify the server' of anything.

I feel that the shutdown partial closure doesn't reach the server.

It never reaches the server. Your code doesn't work the way you think it does. What reaches the server is the FIN, which in turn is the result of the close, not the shutdown SD_RECEIVE.

What you need here is a read timeout at the server end. As you're using select() or whatever is delivering you the events, you will have to implement the timeout manually yourself.

ContentLicense: CC BY-SA 3.0

Title: What if server didn't receive fd_close


问:
Hot swapping in Spring Boot
I've been doing a P.O.C with Spring Boot.

So far it's been going really good and promising, but there's one major drawback: I'm using an embedded server (i.e., packaging the web app in a .jar), so when developing I have to rebuild the jar and restart the server every time I change the CSS, HTML or JS files. There's not hot-swap. This really slows down the UI development.

I can think of several quick fixes, such as loading static resources off a different domain and serving it from a local nginx, and some more variations like this, but isn't there a built-in option of some sort when working with IntelliJ/Eclipse?

答:
but isn't there a built-in option of some sort when working with IntelliJ/Eclipse?

What helped me in IntelliJ 15.0, windows 10, was the following sequence:

STEP 1: Added the following dependency in pom (This is mentioned everywhere but this alone dint solve it), as mentioned by @jonashackt

```<code><dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-devtools</artifactId>
</dependency>
</code>```

STEP 2: Then from File->Settings-> Build-Execution-Deployment -> Compiler (make sure main compiler option is selected and not any of its sub-options)

enable Make Project Automatically. Click ok and close the dialog
Note : In latest version it will be Build project automatically

STEP 3: Hold Shift+Ctrl+A (on windows) you will see a search dialog with title "Enter Action or option name", type registry. Double click the first option that says "Registry..." it will open another window. Look for the following option:

```<code>compiler.automake.allow.when.app.running
</code>```

and enable it, click close

STEP 4: Restart IDE

Elaborated from this source

Title: Hot swapping in Spring Boot

Body:
but isn't there a built-in option of some sort when working with IntelliJ/Eclipse?

What helped me in IntelliJ 15.0, windows 10, was the following sequence:

STEP 1: Added the following dependency in pom (This is mentioned everywhere but this alone dint solve it), as mentioned by @jonashackt

<dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-devtools</artifactId>
</dependency>

STEP 2: Then from File->Settings-> Build-Execution-Deployment -> Compiler (make sure main compiler option is selected and not any of its sub-options)

enable Make Project Automatically. Click ok and close the dialog
Note : In latest version it will be Build project automatically

STEP 3: Hold Shift+Ctrl+A (on windows) you will see a search dialog with title "Enter Action or option name", type registry. Double click the first option that says "Registry..." it will open another window. Look for the following option:

compiler.automake.allow.when.app.running

and enable it, click close

STEP 4: Restart IDE

Elaborated from this source

ContentLicense: CC BY-SA 4.0


问:
I want to print these two words from two buttons, but it didn't work as I imagined
I want to print these two words called "yes" and "no" by two buttons.

When I clicked the first button to print "yes", the two buttons were covered by the word "yes", I don't how to work it out.

Here is my code and the screen shot:
before
after

<!DOCTYPE html>

 <meta charset="utf-8">
 <title>example</title>

 <button type="button" onclick="yes()">print yes</button>
 <button type="button" onclick="no()">print no</button>

```

答:
check this code. Using document.write() after an HTML document is fully loaded, will delete all existing HTML. if you want to show in same YES or NO in one div then use this

```<code><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>example</title>
<script type="text/javascript">
    function yes()
    {
        document.getElementById("content").innerHTML = 'YES';
    }
    function no()
    {
        document.getElementById("content").innerHTML = 'no';
    }
</script>
</head>
<body>
<div id="content"></div>

<button type="button" onclick="yes()">print yes</button>
<button type="button" onclick="no()">print no</button>

 </body>
 </html>
</code>```

if you want to show in different text in different area

```<code><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>example</title>
<script type="text/javascript">
    function yes()
    {
        document.getElementById("yes").innerHTML = 'YES';
    }
    function no()
    {
        document.getElementById("no").innerHTML = 'no';
    }
</script>
</head>
<body>
<div id="yes"></div>
 <div id="no"></div>
<button type="button" onclick="yes()">print yes</button>
<button type="button" onclick="no()">print no</button>

 </body>
 </html>
</code>```

for more information

https://www.w3schools.com/jsref/met_doc_write.asp

Body:
check this code. Using document.write() after an HTML document is fully loaded, will delete all existing HTML. if you want to show in same YES or NO in one div then use this

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>example</title>
<script type="text/javascript">
    function yes()
    {
        document.getElementById("content").innerHTML = 'YES';
    }
    function no()
    {
        document.getElementById("content").innerHTML = 'no';
    }
</script>
</head>
<body>
<div id="content"></div>

<button type="button" onclick="yes()">print yes</button>
<button type="button" onclick="no()">print no</button>

 </body>
 </html>

if you want to show in different text in different area

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>example</title>
<script type="text/javascript">
    function yes()
    {
        document.getElementById("yes").innerHTML = 'YES';
    }
    function no()
    {
        document.getElementById("no").innerHTML = 'no';
    }
</script>
</head>
<body>
<div id="yes"></div>
 <div id="no"></div>
<button type="button" onclick="yes()">print yes</button>
<button type="button" onclick="no()">print no</button>

 </body>
 </html>

for more information

https://www.w3schools.com/jsref/met_doc_write.asp


问:
Why private method does not became overwritten
I'm trying to execute code from official php docs, but I can not understand why private Bar method does not became overwritten by Foo?

```<code>class Bar
{
    public function test() {
        $this->testPrivate();
        $this->testPublic();
    }

    public function testPublic() {
        echo "Bar::testPublic\n";
    }

    private function testPrivate() {
        echo "Bar::testPrivate\n";
    }
}

class Foo extends Bar
{
    public function testPublic() {
        echo "Foo::testPublic\n";
    }

    private function testPrivate() {
        echo "Foo::testPrivate\n";
    }
}

$myFoo = new Foo();
$myFoo->test();
</code>```

Prints Bar::testPrivate Foo::testPublic, but why?

答: In PHP only public and protected method could be overwritten.Not private ones.

Body:
I'm trying to execute code from official php docs, but I can not understand why private Bar method does not became overwritten by Foo?

class Bar
{
    public function test() {
        $this->testPrivate();
        $this->testPublic();
    }

    public function testPublic() {
        echo "Bar::testPublic\n";
    }

    private function testPrivate() {
        echo "Bar::testPrivate\n";
    }
}

class Foo extends Bar
{
    public function testPublic() {
        echo "Foo::testPublic\n";
    }

    private function testPrivate() {
        echo "Foo::testPrivate\n";
    }
}

$myFoo = new Foo();
$myFoo->test();

Prints Bar::testPrivate Foo::testPublic, but why?


问:
In Redux Forms, how do I validate one field based on the value of another?
I am using Redux Form version 6.4.3 and I'm trying to validate two date fields such that the 'to' date must always be before the 'from' date.

Other examples say I ought to be able to refer to the fields array in props but there is no such array.  The form state has an array called registeredFields however but those just seem to be of the form {name: 'dob', type: 'Field'}

Here is my form code

```<code>import React      from 'react'
import DatePicker from 'react-bootstrap-date-picker'
import moment     from 'moment'

import {Field, reduxForm} from 'redux-form'
import {Form, Row, Col, Button, FormGroup, ControlLabel, FormControl, HelpBlock} from 'react-bootstrap'

// validations
const required = value => !value ? 'This field is required' : undefined
const maxDate = max => value =>
  value && moment(value).isAfter(max) ? `Must be before ${max}` : undefined
const minDate = min => value =>
  value && moment(value).isBefore(min) ? `Must be after ${min}` : undefined

const renderDatepicker = ({ input, label, hint, showTodayButton, meta: { pristine, touched, warning, error } }) => {
  const validationState = pristine ? null : error ? 'error' : warning ? 'warning' : null
  return (
  <FormGroup validationState={validationState}>
    <Col componentClass={ControlLabel} sm={3}>{label}</Col>
    <Col sm={3}>
      <FormControl
        {...input}
        componentClass={DatePicker}
        placeholder="DD/MM/YYYY"
        dateFormat="DD/MM/YYYY"
        showTodayButton={showTodayButton}/>
    </Col>
    {pristine && !!hint && (
      <Col sm={6}>
        <HelpBlock>{hint}</HelpBlock>
      </Col>
    )}
    {touched && (
      (error && (
        <Col sm={6}>
          <HelpBlock>{error}</HelpBlock>
        </Col>)
      ) || (warning && (
        <Col sm={6}>
          <HelpBlock>{warning}</HelpBlock>
        </Col>
      ))
    )}
  </FormGroup>
)}

const MyForm = props => {
  const { error, handleSubmit, pristine, reset, submitting, fields } = props
  console.debug('fields', fields) // fields is undefined
  return (
    <Form horizontal>
      <Field
        name="dateFrom"
        component={renderDatepicker}
        label="Date from"
        hint="Earliest date for enquiry"
        validate={[required, maxDate('where do I get the other date value from?')]}
      />
      <Field
        name="dateTo"
        component={renderDatepicker}
        label="Date to"
        showTodayButton={true}
        hint="Latest date for enquiry"
        validate={[required, minDate('where do I get the other date value from?')]}
      />
    </Form>
  )
}

export default reduxForm({
  form: 'MyForm',
})(MyForm)
</code>```

I get the feeling I am missing something obvious since all the examples I have seen expect that the fields array to exist in the props.

答:
It's also worth mentioning that the Field's validate function signature is validate : (value, allValues, props) => error [optional] so you actually have a reference to other fields values in field-level validation as well.

I believe you could do something like:

```<code>const maxDateValidationAdapter = (value, values) => maxDate(values.dateTo)(value);
// Alternatively, if maxDate() is used only in this form you can just change its signature
<Field
    name="dateFrom"
    component={renderDatepicker}
    label="Date from"
    hint="Earliest date for enquiry"
    validate={[required, maxDateValidationAdapter]}
/>
</code>```

See Field documentation (Props you can pass to Field => validate).

Body:
I am using Redux Form version 6.4.3 and I'm trying to validate two date fields such that the 'to' date must always be before the 'from' date.

Other examples say I ought to be able to refer to the fields array in props but there is no such array.  The form state has an array called registeredFields however but those just seem to be of the form {name: 'dob', type: 'Field'}

Here is my form code

import React      from 'react'
import DatePicker from 'react-bootstrap-date-picker'
import moment     from 'moment'

import {Field, reduxForm} from 'redux-form'
import {Form, Row, Col, Button, FormGroup, ControlLabel, FormControl, HelpBlock} from 'react-bootstrap'

// validations
const required = value => !value ? 'This field is required' : undefined
const maxDate = max => value =>
  value && moment(value).isAfter(max) ? `Must be before ${max}` : undefined
const minDate = min => value =>
  value && moment(value).isBefore(min) ? `Must be after ${min}` : undefined

const renderDatepicker = ({ input, label, hint, showTodayButton, meta: { pristine, touched, warning, error } }) => {
  const validationState = pristine ? null : error ? 'error' : warning ? 'warning' : null
  return (
  <FormGroup validationState={validationState}>
    <Col componentClass={ControlLabel} sm={3}>{label}</Col>
    <Col sm={3}>
      <FormControl
        {...input}
        componentClass={DatePicker}
        placeholder="DD/MM/YYYY"
        dateFormat="DD/MM/YYYY"
        showTodayButton={showTodayButton}/>
    </Col>
    {pristine && !!hint && (
      <Col sm={6}>
        <HelpBlock>{hint}</HelpBlock>
      </Col>
    )}
    {touched && (
      (error && (
        <Col sm={6}>
          <HelpBlock>{error}</HelpBlock>
        </Col>)
      ) || (warning && (
        <Col sm={6}>
          <HelpBlock>{warning}</HelpBlock>
        </Col>
      ))
    )}
  </FormGroup>
)}

const MyForm = props => {
  const { error, handleSubmit, pristine, reset, submitting, fields } = props
  console.debug('fields', fields) // fields is undefined
  return (
    <Form horizontal>
      <Field
        name="dateFrom"
        component={renderDatepicker}
        label="Date from"
        hint="Earliest date for enquiry"
        validate={[required, maxDate('where do I get the other date value from?')]}
      />
      <Field
        name="dateTo"
        component={renderDatepicker}
        label="Date to"
        showTodayButton={true}
        hint="Latest date for enquiry"
        validate={[required, minDate('where do I get the other date value from?')]}
      />
    </Form>
  )
}

export default reduxForm({
  form: 'MyForm',
})(MyForm)

I get the feeling I am missing something obvious since all the examples I have seen expect that the fields array to exist in the props.

Body:
It's also worth mentioning that the Field's validate function signature is validate : (value, allValues, props) => error [optional] so you actually have a reference to other fields values in field-level validation as well.

I believe you could do something like:

const maxDateValidationAdapter = (value, values) => maxDate(values.dateTo)(value);
// Alternatively, if maxDate() is used only in this form you can just change its signature
<Field
    name="dateFrom"
    component={renderDatepicker}
    label="Date from"
    hint="Earliest date for enquiry"
    validate={[required, maxDateValidationAdapter]}
/>

See Field documentation (Props you can pass to Field => validate).


问:
How to know the image size after applying aspect fit for the image in an UIImageView
I am loading an image to an imageview with mode as 'Aspect Fit'. I need to know the size to which my image is being scaled to. Please help.</p>

答:
This single line can do this job</p>

```<code>CGSize sizeInView = AVMakeRectWithAspectRatioInsideRect(imgViewFake.image.size, imgViewFake.bounds).size;
</code>```

Body:
This single line can do this job

CGSize sizeInView = AVMakeRectWithAspectRatioInsideRect(imgViewFake.image.size, imgViewFake.bounds).size;


问:
How do I keep CSS floats in one line?
I want to have two items on the same line using float: left for the item on the left.

I have no problems achieving this alone. The problem is, I want the two items to stay on the same line even when you resize the browser very small. You know... like how it was with tables.

The goal is to keep the item on the right from wrapping no matter what.

How to I tell the browser using CSS that I would rather stretch the containing div than wrap it so the the float: right; div is below the float: left; div?

what I want:

```<code>                                   \
 +---------------+  +------------------------/
 | float: left;  |  | float: right;          \
 |               |  |                        /
 |               |  |content stretching      \   Screen Edge
 |               |  |the div off the screen  /  <---
 +---------------+  +------------------------\
                                             /
</code>```

答:
Add this line to your floated element selector

```<code>.floated {
    float: left;
    ...
    box-sizing: border-box;
}
</code>```

It will prevent padding and borders to be added to width, so element always stay in row, even if you have eg. three elements with width of 33.33333%

OwnerDisplayName: Jim Robert

Title: How do I keep CSS floats in one line?

Body:
I want to have two items on the same line using float: left for the item on the left.

I have no problems achieving this alone. The problem is, I want the two items to stay on the same line even when you resize the browser very small. You know... like how it was with tables.

The goal is to keep the item on the right from wrapping no matter what.

How to I tell the browser using CSS that I would rather stretch the containing div than wrap it so the the float: right; div is below the float: left; div?

what I want:

                                   \
 +---------------+  +------------------------/
 | float: left;  |  | float: right;          \
 |               |  |                        /
 |               |  |content stretching      \   Screen Edge
 |               |  |the div off the screen  /  <---
 +---------------+  +------------------------\
                                             /

Body:
Add this line to your floated element selector

.floated {
    float: left;
    ...
    box-sizing: border-box;
}

It will prevent padding and borders to be added to width, so element always stay in row, even if you have eg. three elements with width of 33.33333%


问:
How to add multiple classes to a ReactJS Component?
I am new to ReactJS and JSX and I am having a little problem with the code below.

I am trying to add multiple classes to the className attribute on each li:

```

<p>My React component is:</p>

<pre class="lang-jsx prettyprint-override"><code>var AccountMainMenu = React.createClass({
  getInitialState: function() {
    return { focused: 0 };
  },

  clicked: function(index) {
    this.setState({ focused: index });
  },

  render: function() {
    var self = this;
    var accountMenuData = [
      {
        name: "My Account",
        icon: "icon-account"
      },
      {
        name: "Messages",
        icon: "icon-message"
      },
      {
        name: "Settings",
        icon: "icon-settings"
      }
    /*{
        name:"Help & Support   <span class='font-awesome icon-support'></span>(888) 664.6261",
        listClass:"no-mobile last help-support last"
      }*/
    ];

    return (
      <div className="acc-header-wrapper clearfix">
        <ul className="acc-btns-container">
          {accountMenuData.map(function(data, index) {
            var activeClass = "";

            if (self.state.focused == index) {
              activeClass = "active";
            }

            return (
              <li
                key={index}
                className={activeClass}
                onClick={self.clicked.bind(self, index)}
              >

                  {data.name}

              </li>
            );
          })}
        </ul>
      </div>
    );
  }
});

ReactDOM.render(<AccountMainMenu />, document.getElementById("app-container"));
</code>```

答:
Using facebook's TodoTextInput.js example

```<code>render() {
    return (
      <input className={
        classnames({
          edit: this.props.editing,
          'new-todo': this.props.newTodo
        })}
        type="text"
        placeholder={this.props.placeholder}
        autoFocus="true"
        value={this.state.text}
        onBlur={this.handleBlur}
        onChange={this.handleChange}
        onKeyDown={this.handleSubmit} />
    )
  }
</code>```

replacing classnames with plain vanilla js code will look like this:

```<code>render() {
    return (
      <input
        className={`
          ${this.props.editing ? 'edit' : ''} ${this.props.newTodo ? 'new-todo' : ''}
        `}
        type="text"
        placeholder={this.props.placeholder}
        autoFocus="true"
        value={this.state.text}
        onBlur={this.handleBlur}
        onChange={this.handleChange}
        onKeyDown={this.handleSubmit} />
    )
  }
</code>```

Body:
I am new to ReactJS and JSX and I am having a little problem with the code below.

I am trying to add multiple classes to the className attribute on each li:

My React component is:

var AccountMainMenu = React.createClass({
  getInitialState: function() {
    return { focused: 0 };
  },

  clicked: function(index) {
    this.setState({ focused: index });
  },

  render: function() {
    var self = this;
    var accountMenuData = [
      {
        name: "My Account",
        icon: "icon-account"
      },
      {
        name: "Messages",
        icon: "icon-message"
      },
      {
        name: "Settings",
        icon: "icon-settings"
      }
    /*{
        name:"Help & Support   (888) 664.6261",
        listClass:"no-mobile last help-support last"
      }*/
    ];

    return (

          {accountMenuData.map(function(data, index) {
            var activeClass = "";

            if (self.state.focused == index) {
              activeClass = "active";
            }

            return (

                  {data.name}

            );
          })}

    );
  }
});

ReactDOM.render(<AccountMainMenu />, document.getElementById("app-container"));

Body:
Using facebook's TodoTextInput.js example

render() {
    return (
      <input className={
        classnames({
          edit: this.props.editing,
          'new-todo': this.props.newTodo
        })}
        type="text"
        placeholder={this.props.placeholder}
        autoFocus="true"
        value={this.state.text}
        onBlur={this.handleBlur}
        onChange={this.handleChange}
        onKeyDown={this.handleSubmit} />
    )
  }

replacing classnames with plain vanilla js code will look like this:

render() {
    return (
      <input
        className={`
          ${this.props.editing ? 'edit' : ''} ${this.props.newTodo ? 'new-todo' : ''}
        `}
        type="text"
        placeholder={this.props.placeholder}
        autoFocus="true"
        value={this.state.text}
        onBlur={this.handleBlur}
        onChange={this.handleChange}
        onKeyDown={this.handleSubmit} />
    )
  }


问:
Loading specific model file from CoreNLP Model jar file rather than a local copy of it
Can refer to the already packaged model in StanfordCoreNLP library jar, instead of having duplicate copy of the model in the project working directory for this purpose?.

```<code>Properties configuration = new Properties();
configuration.put("annotators", "tokenize,ssplit,pos,lemma,ner");
configuration.put("ner.model", "english.all.3class.distsim.crf.ser.gz");
StanfordCoreNLP coreNLP  = new StanfordCoreNLP(configuration);
</code>```

ps: The question was a part of another SO question which went unanswered.

答:
To add any model that is existing in a jar file, expand the jar files as shown in the picture below and copy the qualified name of the model you want.
Note: remove the first "/" in the copied name before adding it to the properties of the pipeline.
Adding name of a model from jar files.</p>

Body:
Can refer to the already packaged model in StanfordCoreNLP library jar, instead of having duplicate copy of the model in the project working directory for this purpose?.

Properties configuration = new Properties();
configuration.put("annotators", "tokenize,ssplit,pos,lemma,ner");
configuration.put("ner.model", "english.all.3class.distsim.crf.ser.gz");
StanfordCoreNLP coreNLP  = new StanfordCoreNLP(configuration);

ps: The question was a part of another SO question which went unanswered.


问:
Create timestamp variable in bash script
I am trying to create a timestamp variable in a shell script to make the logging a little easier. I want to create the variable at the beginning of the script and have it print out the current time whenever I issue echo $timestamp. It proving to be more difficult then I thought. Here are some things I've tried:

timestamp="(date +"%T")" echo prints out (date +"%T")

timestamp="$(date +"%T")" echo prints the time when the variable was initialized.

Other things I've tried are just slight variations that didn't work any better. Does anyone know how to accomplish what I'm trying to do?

答:
```<code>DATE=`date "+%Y%m%d"`

DATE_WITH_TIME=`date "+%Y%m%d-%H%M%S"` #add %3N as we want millisecond too
</code>```


问:
How do you enable SSH on a new raspbian Jessie image without a keyboard/monitor?
Looks like SSH is disabled by default on all new Jessie images.  I only run Pi's headless with SSH, so I have no way to configure a new Pi without a keyboard/monitor (which I don't have).

Newsgroups/articles say just 'put a file called "SSH" into the /boot/ folder, but how can you do this from windows?

Is there a way to do this (enable SSH) on the SD card, then insert it into the Pi, then SSH to the new IP address?

答:
After copying the image onto the SD card:
On a Linux computer with SD card slot the boot partition of the SD card is
normally automatically mounted as /media/yourusername/boot.  In this
case you could simply execute the following command:

```<code>touch /media/`id -un`/boot/ssh
</code>```

to create an empty file called ssh in the boot directory of the SD card.
After unmounting the SD card and putting it back into a Pi the SSH service
should start fine after boot.
Verified using 2017-03-02-raspbian-jessie.zip and a laptop with SD card slot running the Ubuntu LTS Linux version 14.04.
Creating an empty file with name ssh in the FAT32 boot partition should be
also possible using a laptop running Windows.

Body:
After copying the image onto the SD card:
On a Linux computer with SD card slot the boot partition of the SD card is
normally automatically mounted as /media/yourusername/boot.  In this
case you could simply execute the following command:

touch /media/`id -un`/boot/ssh

to create an empty file called ssh in the boot directory of the SD card.
After unmounting the SD card and putting it back into a Pi the SSH service
should start fine after boot.
Verified using 2017-03-02-raspbian-jessie.zip and a laptop with SD card slot running the Ubuntu LTS Linux version 14.04.
Creating an empty file with name ssh in the FAT32 boot partition should be
also possible using a laptop running Windows.


问:
How to consume HTTPS webservice having wsdl and soap12 version.
While sending soap1.2 request what are the namespaces we need to use in soapbody? Any sample code available in ios programming? </p>

答:
SOAP request namespace start with following prefix.

http://www.w3.org/2003/05/

And depending on the type of element there are suffix. so for eg.

Envelope - http://www.w3.org/2003/05/soap-envelope

Addressing Header - http://www.w3.org/2005/08/addressing

Check This example.


问:
Clone User, copy all files and folders and copy rights (Linux)
I want to create a new user in Linux, basically creating an exact copy of that user with all permission and access, read and write rights on all folders, subfolders and files (including hidden files).

It does not seem like an easy task. I am able to copy all files but I am not able to clone the rights for all files and subfolders.

What is the right procedure here?

I first add the user

Copy all files recursively for normal files sudo cp -r
/home/user1/* /home/user2/ && sudo chown user2:user2 /home/user2

copy all files for hidden files sudo cp -r /home/user1/.[^.]* /home/user2/ && sudo chown user2:user2 /home/user2

Transfer rights?

I really have no idea whether this is right

答:
You want to recursively copy the whole user folder, not the contents. That automatically includes all "hidden" files. Afterwards you then change the ownership of the new folder:

```<code>cp -pPr /home/user1 /home/user2
chown -R user2 /home/user2
</code>```

You really want to start reading the manual pages of the tools you use. They contain a wealth of precise information to explode: man cp

Body:
You want to recursively copy the whole user folder, not the contents. That automatically includes all "hidden" files. Afterwards you then change the ownership of the new folder:

cp -pPr /home/user1 /home/user2
chown -R user2 /home/user2

You really want to start reading the manual pages of the tools you use. They contain a wealth of precise information to explode: man cp


问:
How to create a script for loop print ps information
Just as title mentioned, How can I oversee a process using ps with periodicity scanning just like command "top", thanks first:)</p>

答:
If the process you want to see is PID 4815 and you want it to update every 2 seconds you could do an infinite while loop.

```<code>while true; do ps 4815; sleep 2; clear; done
</code>```

ContentLicense: CC BY-SA 2.5

Body:
If the process you want to see is PID 4815 and you want it to update every 2 seconds you could do an infinite while loop.

while true; do ps 4815; sleep 2; clear; done


问:
Ecommerce Purchase event, fire on seperate page
Before I explain the issue it's worth noting at the start I do not have access to any html or server side code.

I'm tagging a website for a client, their website is some what similar to an ecommerce platform, there are 3 stages the user goes through before purchasing which are as follows:

Step 1 - Choose items from a table and click add button, then press submit which takes them to Step 2

Step 2 - User can modify the quantity of each product they have selected to purchase or remove the product once finished they press submit which takes them to step 3

Step 3 - On this page the user can only submit the order, once they've submitted they're taken to a confirmation page - saying thanks order received etc

The issue I'm experiencing and trying to solve is this:

I'm setting up an ecommerce purchase event, inside this event I'm trying to pass the transaction information, along with the product information.

The transaction / product information is only located on Step 3.  This event I'm setting up needs to fire on the confirmation page as this is when we know the submission has taken place and the order has been received.

I've gone through documentation around ecommerce events and I'm yet to find if any, anything that can help solve the issue.  I was hoping to find a solution whereby I can build the ecommerce event on Step 3 and on the confirmation page fire the event.  Any suggestions?

答:
I personally would try to review the requirements, the average transaction product quantity and then decide to go with JavaScript client-side code(implemented from GTM) to store the required product data on a cookie or the localstorage. Be careful though these solutions come with many limitations.

Cookies on mobile devices have smaller size restrictions for example.

The best way in my opinion is to communicate with the server-side developers. Because by doing this in the frontend you are risking many inconsistencies with the real data. Frontend code introduces browser compatibility issues, turned-off javascript and many more.

Also until you find a more suitable approach, you can scrape the minimum required information for the products and transaction, directly from the order-complete page. This could be done with pure-js or jQuery if it is available.


问:
Show more elements on button click?
I'm trying to show 5 elements on my page and then have a function to load/show 5 more and this process can continue until there is no more hidden elements left.

I have created a fiddle to show you what I have done so far: https://jsfiddle.net/89v781rL/2/

Currently, when the button is clicked, all the hidden elements are shown at the same time which is not what I want. I need to add 5 more elements to the ones that are in display at the time..

I tried something like this but it doesn't work:

```<code>$('#grid li').not(':visible').each( function() {
  $("#grid").children(":gt(4)").hide();
});
</code>```

This is my full working code:

```<code>$("#grid").children(":gt(4)").hide();

$('#sales').click(function() {
    $('#grid li').not(':visible').each( function() {
      $(this).slideDown();
    });
});
</code>```

答:
You can achieve what you need by using slice() to get the next 5 hidden elements and calling slideDown() on them. Also note that you can use CSS's :nth-child to hide the elements instead of JS so that you avoid the FOUC on load. Try this:

$('#sales').click(function() {
  $('#grid li:hidden').slice(0, 5).slideDown();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#grid li:nth-child(n+6) {
  display: none;
}</code>```

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

<button id="sales">
  Show more
</button>```

Title: Show more elements on button click?

Body:
I'm trying to show 5 elements on my page and then have a function to load/show 5 more and this process can continue until there is no more hidden elements left.

I have created a fiddle to show you what I have done so far: https://jsfiddle.net/89v781rL/2/

Currently, when the button is clicked, all the hidden elements are shown at the same time which is not what I want. I need to add 5 more elements to the ones that are in display at the time..

I tried something like this but it doesn't work:

$('#grid li').not(':visible').each( function() {
  $("#grid").children(":gt(4)").hide();
});

This is my full working code:

$("#grid").children(":gt(4)").hide();

$('#sales').click(function() {
    $('#grid li').not(':visible').each( function() {
      $(this).slideDown();
    });
});

Body:
You can achieve what you need by using slice() to get the next 5 hidden elements and calling slideDown() on them. Also note that you can use CSS's :nth-child to hide the elements instead of JS so that you avoid the FOUC on load. Try this:

$('#sales').click(function() {
  $('#grid li:hidden').slice(0, 5).slideDown();
});

#grid li:nth-child(n+6) {
  display: none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="grid effect-2 cols" id="grid">
  <li><a href="#">1</a></li>
  <li><a href="#">2</a></li>
  <li><a href="#">3</a></li>
  <li><a href="#">4</a></li>
  <li><a href="#">5</a></li>
  <li><a href="#">6</a></li>
  <li><a href="#">7</a></li>
  <li><a href="#">8</a></li>
  <li><a href="#">9</a></li>
  <li><a href="#">10</a></li>
  <li><a href="#">11</a></li>
  <li><a href="#">12</a></li>
  <li><a href="#">13</a></li>
  <li><a href="#">14</a></li>
  <li><a href="#">15</a></li>
  <li><a href="#">16</a></li>
  <li><a href="#">17</a></li>
</ul>

<button id="sales">
  Show more
</button>


问:
Portable recursive regex substitution within a string to resolve .. in path
In Bash, what is the most elegant and portable way to resolve all occurrences of .. within a string representing a path?

Example: path /aa/bb/cc/../dd/ee/../../ff/gg/hh/ii/jj/../../../kk becomes /aa/bb/ff/gg/kk

I wrote two functions that mostly accomplish this goal. (It was actually one, and it was longer, but I had a few ideas while writing this question…)

One uses repetition:

resolve_parents () {
  local previous result=$1
  local re="\/$re|$re\/" re='[^\/]{1,}\/\.\.'
  while [[ $result != $previous ]]; do
    previous=$result
    result=$(echo "$result" | awk '{sub(/\/'$re'/,"")} 1')
  done
  echo "$result"
}

resolve_parents '/aa/bb/cc/../dd/ee/../../ff/gg/hh/ii/jj/../../../kk'
```

<p>And one uses recursion:</p>

<pre class="lang-sh prettyprint-override"><code>resolve_parents_r () {
  local re="\/$re|$re\/" re='[^\/]{1,}\/\.\.'
  local result=$(echo "$1" | awk '{sub(/\/'$re'/,"")} 1')
  [[ $1 = $result ]] && echo "$1" || resolve_parents_r "$result"
}
</code>```

They do not remove a leading .., which would necessitate determining the base directory to get its parent. I am OK with that limitation. Also, it does not fully reduce aa/.. to an empty string. I suppose I would either need to separately apply a regex at the end without a leading or trailing slash, or add a slash to the string at the start and remove it at the end.

Background

I have a function that runs ln -s "$source" "$target". It needs to throw an error if $source does not exist. Confirming $source exists is straightforward if it is an absolute path, but relative paths must be normalized. I accomplish this by:

[[ -d $target ]] && target=$target/$(basename "$source")
local abs_source=$source
[[ $source = /* ]] || abs_source=$( cd "$target/../$source" && pwd -P )
```

The first line is necessary to ensure $target ends with the target name. Otherwise the ../ would need to be omitted if $target is a directory, but would be required if $target already ends with intended link name. cd works fine for resolving paths containing double dot parent references only if the directory exists. Since the test occurs before the link is created, $target unfortunately but necessarily does not exist.

Thus, I am left to determine whether $source exists by deleting matches of the regular expression [^/]+/\.\. either preceded or followed by a slash, but not both. (I considered deleting the matches and then deleting sequences of //, but that can result in a path that was relative becoming absolute or a path that ended in a target name becoming a directory, which would get another target name appended. Yikes!) I cannot use a global regex replace with that pattern, as that could delete sequences like ../... I am not aware of a command that does global replace by resetting the search cursor to the beginning of the string upon each match, so I wrote this into a while loop.

I hoped to use a pattern stored in $re for the sake of simplicity, but that soon became rather complicated when I tried to do the replace with sed and found the + requires extended regular expressions are sometimes turned on with sed -E (on OSX) and sometimes with sed -r. Upon replacing + with {1,}, I found the braces needed escaping for sed, but escaping them caused the Bash regex match to fail. I migrated to using awk and its sub command, which apparently requires the delimiter to be /, so I needed to escape those in my pattern as well.

To prevent infinite loops due to an interpretation mismatch between the regex in Bash and awk, I first added a counter variable with an arbitrary limit. I improved that to a difference test, so while [[ $result =~ $re ]] && (( count < 1000 )) became while [[ $result =~ $re && $result != $previous ]]. Then after experimenting with making an actually recursive function, I realized the $result =~ $re && was not necessary.

At this point I start to wonder whether I really care if my $sources are nonexistent!

答:
Looks like you can just use readlink -m here:

```<code>p='/aa/bb/cc/../dd/ee/../../ff/gg/hh/ii/jj/../../../kk'

readlink -m "$p"
/aa/bb/ff/gg/kk
</code>```

As per readlink --help:

-m, --canonicalize-missing canonicalize by following every symlink in
                                  every component of the given name recursively,
                                  without requirements on components existence

Update: Here is a standard stack approach to resolve this using awk. Consider this awk script:

```<code>BEGIN {
   FS = OFS = "/"
}
/^\.\.\// {
   $0 = pwd OFS $0  # prefix with pwd if stats with ../
}
{
   for (i=1; i<=NF; i++) {
      if ($i == "..")
         delete p[k--]  # pop an element from stack
      else
         p[++k] = $i    # push an element into stack
   }
   # print final stack content
   for (i=1; i <= k; i++)
      printf "%s%s", (i>1 ? OFS : ""), p[i]
   print ""
}
</code>```

Save it as realpath.awk, then test it as:

```<code>p='/aa/bb/cc/../dd/ee/../../ff/gg/hh/ii/jj/../../../kk'
awk -v pwd="$PWD" -f realpath.awk <<< "$p"

/aa/bb/ff/gg/kk
</code>```

Body:
In Bash, what is the most elegant and portable way to resolve all occurrences of .. within a string representing a path?

Example: path /aa/bb/cc/../dd/ee/../../ff/gg/hh/ii/jj/../../../kk becomes /aa/bb/ff/gg/kk

I wrote two functions that mostly accomplish this goal. (It was actually one, and it was longer, but I had a few ideas while writing this question…)

One uses repetition:

resolve_parents () {
  local previous result=$1
  local re="\/$re|$re\/" re='[^\/]{1,}\/\.\.'
  while [[ $result != $previous ]]; do
    previous=$result
    result=$(echo "$result" | awk '{sub(/\/'$re'/,"")} 1')
  done
  echo "$result"
}

resolve_parents '/aa/bb/cc/../dd/ee/../../ff/gg/hh/ii/jj/../../../kk'

And one uses recursion:

resolve_parents_r () {
  local re="\/$re|$re\/" re='[^\/]{1,}\/\.\.'
  local result=$(echo "$1" | awk '{sub(/\/'$re'/,"")} 1')
  [[ $1 = $result ]] && echo "$1" || resolve_parents_r "$result"
}

They do not remove a leading .., which would necessitate determining the base directory to get its parent. I am OK with that limitation. Also, it does not fully reduce aa/.. to an empty string. I suppose I would either need to separately apply a regex at the end without a leading or trailing slash, or add a slash to the string at the start and remove it at the end.

Background

I have a function that runs ln -s "$source" "$target". It needs to throw an error if $source does not exist. Confirming $source exists is straightforward if it is an absolute path, but relative paths must be normalized. I accomplish this by:

[[ -d $target ]] && target=$target/$(basename "$source")
local abs_source=$source
[[ $source = /* ]] || abs_source=$( cd "$target/../$source" && pwd -P )

The first line is necessary to ensure $target ends with the target name. Otherwise the ../ would need to be omitted if $target is a directory, but would be required if $target already ends with intended link name. cd works fine for resolving paths containing double dot parent references only if the directory exists. Since the test occurs before the link is created, $target unfortunately but necessarily does not exist.

Thus, I am left to determine whether $source exists by deleting matches of the regular expression [^/]+/\.\. either preceded or followed by a slash, but not both. (I considered deleting the matches and then deleting sequences of //, but that can result in a path that was relative becoming absolute or a path that ended in a target name becoming a directory, which would get another target name appended. Yikes!) I cannot use a global regex replace with that pattern, as that could delete sequences like ../... I am not aware of a command that does global replace by resetting the search cursor to the beginning of the string upon each match, so I wrote this into a while loop.

I hoped to use a pattern stored in $re for the sake of simplicity, but that soon became rather complicated when I tried to do the replace with sed and found the + requires extended regular expressions are sometimes turned on with sed -E (on OSX) and sometimes with sed -r. Upon replacing + with {1,}, I found the braces needed escaping for sed, but escaping them caused the Bash regex match to fail. I migrated to using awk and its sub command, which apparently requires the delimiter to be /, so I needed to escape those in my pattern as well.

To prevent infinite loops due to an interpretation mismatch between the regex in Bash and awk, I first added a counter variable with an arbitrary limit. I improved that to a difference test, so while [[ $result =~ $re ]] && (( count < 1000 )) became while [[ $result =~ $re && $result != $previous ]]. Then after experimenting with making an actually recursive function, I realized the $result =~ $re && was not necessary.

At this point I start to wonder whether I really care if my $sources are nonexistent!

Body:
Looks like you can just use readlink -m here:

p='/aa/bb/cc/../dd/ee/../../ff/gg/hh/ii/jj/../../../kk'

readlink -m "$p"
/aa/bb/ff/gg/kk

As per readlink --help:

-m, --canonicalize-missing canonicalize by following every symlink in
                                  every component of the given name recursively,
                                  without requirements on components existence

Update: Here is a standard stack approach to resolve this using awk. Consider this awk script:

BEGIN {
   FS = OFS = "/"
}
/^\.\.\// {
   $0 = pwd OFS $0  # prefix with pwd if stats with ../
}
{
   for (i=1; i<=NF; i++) {
      if ($i == "..")
         delete p[k--]  # pop an element from stack
      else
         p[++k] = $i    # push an element into stack
   }
   # print final stack content
   for (i=1; i <= k; i++)
      printf "%s%s", (i>1 ? OFS : ""), p[i]
   print ""
}

Save it as realpath.awk, then test it as:

p='/aa/bb/cc/../dd/ee/../../ff/gg/hh/ii/jj/../../../kk'
awk -v pwd="$PWD" -f realpath.awk <<< "$p"

/aa/bb/ff/gg/kk


问:
short not being printed correctly c++
I have this list definition in c++

```<code>short list[] = {(short)0x32, (short)0x0F, (short)0xFFFF, (short)0x2A};
</code>```

And I'm getting this print using prinf:

```<code>32 F FFFFFFFF 2A
32 F FFFFFFFF 2A
</code>```

But when I use different numbers I get the espected result.

```<code>short list[] = {(short)0x32, (short)0x0F, (short)0x7FFF, (short)0x2A};

32 F 7FFF 2A
32 F 7FFF 2A
</code>```

I'd like to know what's happening.
Why is it printing a full integer in the frist place?
Thanks.

答:
I'm guessing you are printing the numbers with printf("%X", value).

In that case you are most likely irritated by sign-extension. The short value 0xFFFF which you have specified equals the decimal value -1. If this is extended/casted to a 32bit integer value you will get the same -1 value, but it's binary representation is 0xFFFFFFFF. This is what you see that gets printed. If you print with printf("%hX", value) you should see the correct value, if you don't have another cast from short to int in between.

Title: short not being printed correctly c++

Body:
I have this list definition in c++

short list[] = {(short)0x32, (short)0x0F, (short)0xFFFF, (short)0x2A};

And I'm getting this print using prinf:

32 F FFFFFFFF 2A
32 F FFFFFFFF 2A

But when I use different numbers I get the espected result.

short list[] = {(short)0x32, (short)0x0F, (short)0x7FFF, (short)0x2A};

32 F 7FFF 2A
32 F 7FFF 2A

I'd like to know what's happening.
Why is it printing a full integer in the frist place?
Thanks.


问:
Should you lock resources when reading values?
When doing thread synchronization in C# should I also lock an object when I read a value or just changing it?

for example I have Queue<T> object. Should I just lock it when doing the Enqueue and Dequeue or should I also lock it when checking values like Count?

答:
The CLR guarantees atomic reads for values up to the width of the processor. So if you're running on 32 bit, reading ints will be atomic. If you're running on 64 bit machine, reading longs will be atomic. Ergo, if Count is an Int32 there's no need to lock.

This post is pertinent to your question.

OwnerDisplayName: Superdumbell

OwnerDisplayName: Kent Boogaart


问:
Fluent NHibernate Upgrade to NH3.0 alpha
Hy
We want to use the latest alpha version of NHibernate. Unfortunately the latest fluent nhibernate release is built for 2.1 GA. When do you plan to upgrade to latest NH? Is there a source tree which I can fork to build the latest version from?

Daniel

答: You can get it using NuGet.</p>

Body: You can get it using NuGet.


问:
If I don't want to use a nib file, what is the proper implementation of loadView that sizes the root view correctly?
There are a bunch of related questions here, but none that feels like a concise or correct answer.  Here's the situation:

I am creating a new ViewController and don't want to use a nib file.  My understanding from the Apple docs is that if I don't want to use a nib, I should implement loadView to manually create my own view hierarchy.

However, its not clear to me how I should properly instantiate self.view with the proper bounds (given this view controller might be used in a bunch of different situations, setting it simply to the screen bounds doesn't feel right).

Somehow the default UIViewController loadView does seem to properly initiate the frame size, but its not clear if I'm writing my own version what I should be doing to do this.

答:
In loadView, you should set the view property of viewController, and nothing else. Adding subviews should be done in viewDidLoad.

```<code>- (void)loadView {
    self.view = [[NSView alloc] initWithFrame:NSMakeRect(0, 0, 80, 40)];
}
</code>```

Roopesh Chander has an interesting blog post on which strategy to choose: loadView vs viewDidLoad
for Programmatic UI Setup. He recommends setting the frame in loadView rather than viewDidLoad for maximum efficiency.

Body:
In loadView, you should set the view property of viewController, and nothing else. Adding subviews should be done in viewDidLoad.

- (void)loadView {
    self.view = [[NSView alloc] initWithFrame:NSMakeRect(0, 0, 80, 40)];
}

Roopesh Chander has an interesting blog post on which strategy to choose: loadView vs viewDidLoad
for Programmatic UI Setup. He recommends setting the frame in loadView rather than viewDidLoad for maximum efficiency.


问:
Want to know about the processor information
I have seen my system specifications and I was confused in one thing, for the processor it was written
"INTEL CPU @3.20 Gigahertz 3.2 Gigahertz"

I want to know why 3.20 Gigahertz is written twice? does this mean I have two 3.20 Gigahertz processors?

答:
It is unlikely that this means that you have two 3.2 GHz processors. More likely it is simply that the computer code that generates this "processor" field simply uses something like the processor's "short description" followed by its "speed". Unfortunately, the processor's short description already contains the speed, and thus you get the speed mentioned twice (and in two slightly different forms).

That said without some more information on the specific of where this information is coming form it is impossible to answer your question.


问:
NHibernate Second Level Cache not caching results from Query Cache
In our application configuration, we've got NHibernate configured with both second level and query caches enabled with the SysCacheProvider, configured Fluently...

```<code>.Cache(x => x.UseQueryCache().ProviderClass<SysCacheProvider>().UseSecondLevelCache())
</code>```

We have an entity called Lookup that is marked with Cache.ReadOnly() in its mapping file, and we fetch it using CreateCriteria with SetCacheable(true).SetCacheMode(CacheMode.Normal).

The problem is that the second level cache doesn't seem to be used. Using NHProf, we can see that the first query to fetch the Lookup (by a unique string ID) is correctly cached, but on every call NHibernate then goes to the database to fetch the row by the cached sql ID, rather than using the second level cache.

I've done everything in this blog but to no avail.

Is there something else I need to do, or are there any pitfalls that can mean that entities don't get added to the second level cache?

答: The caching fails when we are using NHibernate from within an NServiceBus handler. It turns out that within NSB handlers, the second level cache is not supported for the version we are using (version 5.x).</p>

Body:
In our application configuration, we've got NHibernate configured with both second level and query caches enabled with the SysCacheProvider, configured Fluently...

.Cache(x => x.UseQueryCache().ProviderClass<SysCacheProvider>().UseSecondLevelCache())

We have an entity called Lookup that is marked with Cache.ReadOnly() in its mapping file, and we fetch it using CreateCriteria with SetCacheable(true).SetCacheMode(CacheMode.Normal).

The problem is that the second level cache doesn't seem to be used. Using NHProf, we can see that the first query to fetch the Lookup (by a unique string ID) is correctly cached, but on every call NHibernate then goes to the database to fetch the row by the cached sql ID, rather than using the second level cache.

I've done everything in this blog but to no avail.

Is there something else I need to do, or are there any pitfalls that can mean that entities don't get added to the second level cache?


问:
My procedure gives error when I run
My procedure gives error when I run. I couldn't find where is mistake ?

```<code>CREATE PROCEDURE testing ()
  BEGIN
  DECLARE i INT;
  DECLARE vSite VARCHAR(100);
  set @i = 1;
  BEGIN WHILE @i <= 5 DO
      SET  @vSite = @vSite + CONCAT('LINE '+@i+', ');
     SET @i = @i + 1;
  END WHILE
        SELECT @vSite;
  END

/* Error
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'SELECT @vSite; END' at line 10
*/

/* required output given below

LINE 1, LINE 2, LINE 3, LINE 4, LINE 5,

 */
</code>```

答:
Resolved By My Self

```<code>  delimiter //
CREATE procedure while_examples()
wholeblock:BEGIN
  declare str VARCHAR(255) default '';
  declare x INT default 0;
  SET x = 1;

  WHILE x <= 5 DO
    SET str = CONCAT(str,'LINE',x,',');
    SET x = x + 1;
  END WHILE;

  select str;
END//
CALL while_examples();
</code>```

Title: My procedure gives error when I run

Body:
My procedure gives error when I run. I couldn't find where is mistake ?

CREATE PROCEDURE testing ()
  BEGIN
  DECLARE i INT;
  DECLARE vSite VARCHAR(100);
  set @i = 1;
  BEGIN WHILE @i <= 5 DO
      SET  @vSite = @vSite + CONCAT('LINE '+@i+', ');
     SET @i = @i + 1;
  END WHILE
        SELECT @vSite;
  END

/* Error
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'SELECT @vSite; END' at line 10
*/

/* required output given below

LINE 1, LINE 2, LINE 3, LINE 4, LINE 5,

 */

Body:
Resolved By My Self

  delimiter //
CREATE procedure while_examples()
wholeblock:BEGIN
  declare str VARCHAR(255) default '';
  declare x INT default 0;
  SET x = 1;

  WHILE x <= 5 DO
    SET str = CONCAT(str,'LINE',x,',');
    SET x = x + 1;
  END WHILE;

  select str;
END//
CALL while_examples();


问:
npm pre commit not working
I am using npm precommit hook, but it is not stopping a file with issues to be committed, nor am I getting the message "Pre commit checks" when I try to commit a file.</p>

```<code>Package Json:
{
  "name": "myfolder",
  "version": "1.0.0",
  "description": "",
  "main": "",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 0",
    "precommit-msg": "echo 'Pre-commit checks...' && exit 0",
    "lint": "csslint global/css"
  },
  "author": "SR",
  "license": "ISC",
  "dependencies": {
    "csslint": "^1.0.4",
    "jshint": "^2.9.4",
    "pre-commit": "^1.2.2"
  },
  "pre-commit": [
    "precommit-msg",
    "lint"
  ],
  "devDependencies": {
    "pre-commit": "^1.2.2"
  }
}
</code>```

答: Please, make sure that your 'package.json' file is in the same folder, where '.git' folder is (where git repository was initialized). When you install 'pre-commit' package, 'pre-commit' file should appear under '.git/hooks/'.

Title: npm pre commit not working

Body:
I am using npm precommit hook, but it is not stopping a file with issues to be committed, nor am I getting the message "Pre commit checks" when I try to commit a file.

Package Json:
{
  "name": "myfolder",
  "version": "1.0.0",
  "description": "",
  "main": "",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 0",
    "precommit-msg": "echo 'Pre-commit checks...' && exit 0",
    "lint": "csslint global/css"
  },
  "author": "SR",
  "license": "ISC",
  "dependencies": {
    "csslint": "^1.0.4",
    "jshint": "^2.9.4",
    "pre-commit": "^1.2.2"
  },
  "pre-commit": [
    "precommit-msg",
    "lint"
  ],
  "devDependencies": {
    "pre-commit": "^1.2.2"
  }
}


问:
Javasacript get the timezone name string?
How we can get the timezone strgin name from javascript, for example

```<code>var d = new Date();
document.getElementById("demo").innerHTML =d;
</code>```

this returns

Thu Mar 30 2017 15:13:57 GMT+0500 (Pakistan Standard Time)

Now how we can get the part between the brackets(Pakistan Standard Time) ?

答:
I would suggest something like

/\((.*)\)/.exec(new Date().toString())[1];

Body:
How we can get the timezone strgin name from javascript, for example

var d = new Date();
document.getElementById("demo").innerHTML =d;

this returns

Thu Mar 30 2017 15:13:57 GMT+0500 (Pakistan Standard Time)

Now how we can get the part between the brackets(Pakistan Standard Time) ?


问:
Restarting numbering within partition once value change
I'm struggling with quite simple (I think) topic, which I can not get to run.

An example data:

```<code>|ready_signal|timestamp          |
|4           |2017-03-17 17:58:25|
|4           |2017-03-17 17:58:24|
|4           |2017-03-17 17:58:23|
|0           |2017-03-17 17:58:22|
|0           |2017-03-17 17:58:21|
|0           |2017-03-17 17:58:19|
|4           |2017-03-17 17:58:18|
|4           |2017-03-17 17:58:15|
|0           |2017-03-17 17:58:10|
|0           |2017-03-17 17:58:09|
|0           |2017-03-17 17:58:04|
|4           |2017-03-17 17:58:03|
</code>```

Now what I'm trying to achieve is, to get maximal value of timestamp, within every ready_signal change.
So the result should look like:

```<code>|ready_signal|timestamp          |
|4           |2017-03-17 17:58:25|
|0           |2017-03-17 17:58:22|
|4           |2017-03-17 17:58:18|
|0           |2017-03-17 17:58:10|
|4           |2017-03-17 17:58:09|
</code>```

I was trying with partitioning function, with ROW_NUMBER etc. but without success. I can not partition over none of this columns. Partitioning over ready_signal, will return only two values (and with use of ORDER BY within partition).

I think, somebody definitely have had the same issue. Is like, I would need a single unique partition number, but every time ready_signal value will change.

Sorry, for not posting the example code.
This is what I was experimenting with:

```<code>SELECT ready,
    timestamp,
    ROW_NUMBER() OVER(PARTITION BY ready ORDER BY timestamp DESC) AS readyTime
FROM bubu
ORDER BY timestamp DESC
</code>```

I also tried to pick up some max values:

```<code>SELECT ready,
    timestamp,
    ROW_NUMBER() OVER(PARTITION BY ready ORDER BY timestamp DESC) AS readyTime
FROM bubu
ORDER BY timestamp DESC
</code>```

Body:
I'm struggling with quite simple (I think) topic, which I can not get to run.

An example data:

|ready_signal|timestamp          |
|4           |2017-03-17 17:58:25|
|4           |2017-03-17 17:58:24|
|4           |2017-03-17 17:58:23|
|0           |2017-03-17 17:58:22|
|0           |2017-03-17 17:58:21|
|0           |2017-03-17 17:58:19|
|4           |2017-03-17 17:58:18|
|4           |2017-03-17 17:58:15|
|0           |2017-03-17 17:58:10|
|0           |2017-03-17 17:58:09|
|0           |2017-03-17 17:58:04|
|4           |2017-03-17 17:58:03|

Now what I'm trying to achieve is, to get maximal value of timestamp, within every ready_signal change.
So the result should look like:

|ready_signal|timestamp          |
|4           |2017-03-17 17:58:25|
|0           |2017-03-17 17:58:22|
|4           |2017-03-17 17:58:18|
|0           |2017-03-17 17:58:10|
|4           |2017-03-17 17:58:09|

I was trying with partitioning function, with ROW_NUMBER etc. but without success. I can not partition over none of this columns. Partitioning over ready_signal, will return only two values (and with use of ORDER BY within partition).

I think, somebody definitely have had the same issue. Is like, I would need a single unique partition number, but every time ready_signal value will change.

Sorry, for not posting the example code.
This is what I was experimenting with:

SELECT ready,
    timestamp,
    ROW_NUMBER() OVER(PARTITION BY ready ORDER BY timestamp DESC) AS readyTime
FROM bubu
ORDER BY timestamp DESC

I also tried to pick up some max values:

SELECT ready,
    timestamp,
    ROW_NUMBER() OVER(PARTITION BY ready ORDER BY timestamp DESC) AS readyTime
FROM bubu
ORDER BY timestamp DESC

Body:
Try below query, this will give you the exact required output as described in your question.

DECLARE @SAMPLEDATA TABLE(READYSIGNAL INT,TIMESTAMPP DATETIME)
INSERT INTO @SAMPLEDATA VALUES
(4,'2017-03-17 17:58:25'),
(4,'2017-03-17 17:58:24'),
(4,'2017-03-17 17:58:23'),
(0,'2017-03-17 17:58:22'),
(0,'2017-03-17 17:58:21'),
(0,'2017-03-17 17:58:19'),
(4,'2017-03-17 17:58:18'),
(4,'2017-03-17 17:58:15'),
(0,'2017-03-17 17:58:10'),
(0,'2017-03-17 17:58:09'),
(0,'2017-03-17 17:58:09'),
(4,'2017-03-17 17:58:09')
;WITH SAMPLEDATA
AS
(
SELECT *,1 COL FROM (SELECT ROW_NUMBER()OVER(ORDER BY (SELECT 100))SNO,*
 FROM @SAMPLEDATA)T WHERE SNO=1
UNION ALL
SELECT T2.SNO,T2.READYSIGNAL,T2.TIMESTAMPP,
    CASE WHEN T1.READYSIGNAL=T2.READYSIGNAL THEN T1.COL ELSE T1.COL+1 END
        FROM SAMPLEDATA T1 JOIN (SELECT ROW_NUMBER()OVER(ORDER BY (SELECT     100))SNO,*
 FROM @SAMPLEDATA) T2 ON T1.SNO=T2.SNO-1
)
SELECT READYSIGNAL,TIMESTAMPP FROM
    (SELECT READYSIGNAL,MAX(TIMESTAMPP)TIMESTAMPP,MAX(SNO)SNO FROM     SAMPLEDATA     GROUP BY COL,READYSIGNAL)RESULT ORDER BY SNO

OUTPUT

------------------------------------------
--READYSIGNAL   TIMESTAMPP
------------------------------------------
    4           2017-03-17 17:58:25.000
    0           2017-03-17 17:58:22.000
    4           2017-03-17 17:58:18.000
    0           2017-03-17 17:58:10.000
    4           2017-03-17 17:58:09.000
-----------------------------------------


问:
angular2 simulate rest service
First of all I want to emphasize I am an Angular2 newbie (or even less...). The backend REST services are not ready yet so I should simulate them somehow.

I checked on the net how it can be achieved and I found the following ways:

using a JSON server

using the MockBackend

mocking the service itself

I am just wondering if there is a magical 4th way where I have to do minimal configuration and coding (yeah, I know the options above are not complex but I am a newbie so EVERYTHING is complex to me at the moment) and it works ?

Thanks,

V.

答:
The options which you mentioned are the easiest ones. May be have a look at the links which i have shared below. You will get more ideas to process with.

http://restlet.com/company/blog/2016/04/08/interacting-efficiently-with-a-restful-service-with-angular2-and-rxjs-part-1/

https://www.sitepoint.com/angular-2-mockbackend/

Title: angular2 simulate rest service


问:
Is This An Example Of Recursion (Python)
Hi I am struggling to understand exactly what recursion is, It is a requirement of the program I am writing(a snake game) and I cannot find a clear definition of what is classified as recursion. Could someone tell me if the code below is an example of this?

while True:
    #recieve input
    player_name = input("Enter a name between 0 and 20 characters: ")
    #if length is within boundaries the loop is stopped
    if len(player_name) > 0 and len(player_name) <= 20: break
    #if the name is outwith the boundaries a message is printed and the loop restarts
    print("Too long/short, try again.")

答:
There are two types of looping:

1. Iteration:

Here you use for(), while(), do-while() loops to repeat a set of statements

2. Recursion:

Here you call a function which calls the same function from within.

Example:

```<code>def factorial(n):
if n == 0:
    return 1
else:
    return n * factorial(n - 1)
</code>```

Here the function factorial() is calling itself until value of n becomes 0. The statement n==0 is called base/terminal condition which terminates the recursion.

Body:
There are two types of looping:

1. Iteration:

Here you use for(), while(), do-while() loops to repeat a set of statements

2. Recursion:

Here you call a function which calls the same function from within.

Example:

def factorial(n):
if n == 0:
    return 1
else:
    return n * factorial(n - 1)

Here the function factorial() is calling itself until value of n becomes 0. The statement n==0 is called base/terminal condition which terminates the recursion.


问:
Sort NSArray with a specific key
I'm have requested an array from server and now I wanna filter all data which have "status_read": 1 in an new array. How can I do it? This is my data response:

```<code>{
  "status": "success",
  "message": "success",
  "data": [
    {
      "logo": "http://**.com/timepicker/images/default_o.jpg",
      "title": "Title 1",
      "icon": "https://**.com/admin/dashboard/dist/img/a.png",
      "type": 1,
      "link_detail": "",
      "id_call": 12,
      "status_read": 1
    },
    {
      "logo": "http://**.com/timepicker/images/default_go.jpg",
      "title": "Title 2",
      "icon": "https://**.com/admin/dashboard/dist/img/b.png",
      "type": 0,
      "link_detail": "http://google.com",
      "id_call": 0,
      "status_read": 0
    }
  ]
}
</code>```

Here is my code for filter array:

```<code>NSString *dictionaryKey = @"status_read";
NSInteger predicateValue = 1;
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%K == %i", dictionaryKey, predicateValue];
NSArray *filteredArr = [readNotif filteredArrayUsingPredicate:predicate];
generalArray = filteredArr;
[self.notifTableView reloadData];
</code>```

答:
```<code>NSDictionary *dic1 = @{@"status_read" : @1, @"title" : @"Title 1"};
NSDictionary *dic2 = @{@"status_read" : @0, @"title" : @"Title 0"};
NSDictionary *dic5 = @{@"status_read" : @5, @"title" : @"Title 5"};
NSDictionary *dic4 = @{@"status_read" : @4, @"title" : @"Title 4"};
NSArray *array = @[dic1, dic2, dic5, dic4];

NSArray *result = [array sortedArrayUsingComparator:^NSComparisonResult(NSDictionary *_Nonnull obj1, NSDictionary *  _Nonnull obj2) {
    NSInteger objValue1 = [obj1[@"status_read"] integerValue];
    NSInteger objValue2 = [obj2[@"status_read"] integerValue];
    if (objValue1 > objValue2) {
        return (NSComparisonResult)NSOrderedDescending;
    } else if (objValue1 < objValue2) {
        return (NSComparisonResult)NSOrderedAscending;
    }
    return (NSComparisonResult)NSOrderedSame;
}];

NSLog(@"%@", result);
</code>```

The array will not change.

Title: Sort NSArray with a specific key

Body:
I'm have requested an array from server and now I wanna filter all data which have "status_read": 1 in an new array. How can I do it? This is my data response:

{
  "status": "success",
  "message": "success",
  "data": [
    {
      "logo": "http://**.com/timepicker/images/default_o.jpg",
      "title": "Title 1",
      "icon": "https://**.com/admin/dashboard/dist/img/a.png",
      "type": 1,
      "link_detail": "",
      "id_call": 12,
      "status_read": 1
    },
    {
      "logo": "http://**.com/timepicker/images/default_go.jpg",
      "title": "Title 2",
      "icon": "https://**.com/admin/dashboard/dist/img/b.png",
      "type": 0,
      "link_detail": "http://google.com",
      "id_call": 0,
      "status_read": 0
    }
  ]
}

Here is my code for filter array:

NSString *dictionaryKey = @"status_read";
NSInteger predicateValue = 1;
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%K == %i", dictionaryKey, predicateValue];
NSArray *filteredArr = [readNotif filteredArrayUsingPredicate:predicate];
generalArray = filteredArr;
[self.notifTableView reloadData];

Body:
NSDictionary *dic1 = @{@"status_read" : @1, @"title" : @"Title 1"};
NSDictionary *dic2 = @{@"status_read" : @0, @"title" : @"Title 0"};
NSDictionary *dic5 = @{@"status_read" : @5, @"title" : @"Title 5"};
NSDictionary *dic4 = @{@"status_read" : @4, @"title" : @"Title 4"};
NSArray *array = @[dic1, dic2, dic5, dic4];

NSArray *result = [array sortedArrayUsingComparator:^NSComparisonResult(NSDictionary *_Nonnull obj1, NSDictionary *  _Nonnull obj2) {
    NSInteger objValue1 = [obj1[@"status_read"] integerValue];
    NSInteger objValue2 = [obj2[@"status_read"] integerValue];
    if (objValue1 > objValue2) {
        return (NSComparisonResult)NSOrderedDescending;
    } else if (objValue1 < objValue2) {
        return (NSComparisonResult)NSOrderedAscending;
    }
    return (NSComparisonResult)NSOrderedSame;
}];

NSLog(@"%@", result);

The array will not change.


问:
How to quickly deploy React / Redux app as a sample?
It seems one way is to deploy the React app to Heroku, but is there a simple way to deploy to our own website or to GitHub page feature so that you can see the page off from GitHub? (just as a sample, not for production)

Details:

It seems that one possible way may be to use

```<code>wget -r --no-parent http://localhost:8080 -P sample -nH
cp -rf images any_needed_folder sample
</code>```

and now you can git add sample and git commit and push to github and turn on the GitHub page for your repo and be able to see your React app inside of sample.

You also need to change the paths in the index.html, from /bundle.js to bundle.js, etc, because you need relative path instead of going to the root of your website.

(I used wget to recursively download index.html, bundle.js, and style/ (the CSS files) because bundle.js cannot be found in the whole directory on the local hard drive. I used wget because curl doesn't seem to be able to download recursively)

答:
If wget is doing what you want, cool, use that.

For the actual deploying, I recommend using gh-pages on npm. It handles creating an orphan branch and copying your output files into it, and then pushing all in one command.

Install it:

```<code>npm install --save-dev
</code>```

And in an npm script:

```<code>gh-pages -d sample
</code>```

Body:
It seems one way is to deploy the React app to Heroku, but is there a simple way to deploy to our own website or to GitHub page feature so that you can see the page off from GitHub? (just as a sample, not for production)

Details:

It seems that one possible way may be to use

wget -r --no-parent http://localhost:8080 -P sample -nH
cp -rf images any_needed_folder sample

and now you can git add sample and git commit and push to github and turn on the GitHub page for your repo and be able to see your React app inside of sample.

You also need to change the paths in the index.html, from /bundle.js to bundle.js, etc, because you need relative path instead of going to the root of your website.

(I used wget to recursively download index.html, bundle.js, and style/ (the CSS files) because bundle.js cannot be found in the whole directory on the local hard drive. I used wget because curl doesn't seem to be able to download recursively)

Body:
If wget is doing what you want, cool, use that.

For the actual deploying, I recommend using gh-pages on npm. It handles creating an orphan branch and copying your output files into it, and then pushing all in one command.

Install it:

npm install --save-dev

And in an npm script:

gh-pages -d sample


问:
How do I add another keyboards into Remix OS (Vietnam, Cambodia, Thailand Keyboards)
I have a problem which are I cannot add another keyboards namely, Vietnam, Cambodia and Thailand. I cannot change the Keyboard from English language to Vietnam, Cambodia and Thailand languages. I have tried Khmer Smart Keyboard, Cambodia Keyboard APK and Phum Keyboard for Cambodia keyboard; Keyboard ManMan, Gadgetdoor Thai Keyboard, Thai Gingerbread KB and Thai Pack Without ALM97774503 for Thailand keyboard.

My host OS is Windows 7. I use VM-ware player to run Remix OS and Remix OS is marshmallow. How do I add another keyboards into Remix OS please?

Kindly please help me out. Any suggestion, I would appreciate it.

答:
I think at now you can use Google keyboard that has those languages already: https://play.google.com/store/apps/details?id=com.google.android.inputmethod.latin&hl=en

It's also easy to switch between language.


问:
Problem with size of my SQL Server Log file
In my database on SQL 2008 Express Advanced

Recovery Model is full

AutoShrink is false

When I ran sp_spaceused, I got the following;

```<code>database_name           db_size         unallocated_space
FreeLearningTuts        1398.13 MB       0.73 MB

reserved    data           index_size          unused
211216 KB   207024 KB      2944 KB      1248 KB
</code>```

Out of this, the size of the tables is 150MB but db size shows 1398.13. It's probably the size of the log file. Can you tell what should I do to reduce the size of the Database.

Does anything look wrong with my DB from the figures above or are these the figures that a healthy db shows?

答: Do you do regular log backups? If not, the log will keep growing until you hit the maximum db size for SQL Express.</p>

Body:
In my database on SQL 2008 Express Advanced

Recovery Model is full

AutoShrink is false

When I ran sp_spaceused, I got the following;

database_name           db_size         unallocated_space
FreeLearningTuts        1398.13 MB       0.73 MB

reserved    data           index_size          unused
211216 KB   207024 KB      2944 KB      1248 KB

Out of this, the size of the tables is 150MB but db size shows 1398.13. It's probably the size of the log file. Can you tell what should I do to reduce the size of the Database.

Does anything look wrong with my DB from the figures above or are these the figures that a healthy db shows?


问:
SonarQube issue: Method may fail to clean up stream or resource on checked exception
The following statement in my code is being red-marked by SonarQube as a critical issue.
    stmt=conn.createStatement();

The exact issue is, "method may fail to clean up java.sql.Statement on checked exception".

Code snippet below:

```<code>.
.
.
try{
    .
    .
    .

    **stmt=conn.createStatement();**

    .
    .
    .
} catch (SQLException e) {
    ...exception logged...
} catch (NullPointerException e) {
    ...exception logged...
}finally{

    try {
            if(rs !=  null)
            {
                    rs.close();
            }
        } catch (SQLException e) {
        ...exception logged...
    }

    if(stmt !=  null)
    {
        try {
            stmt.close();
        } catch (SQLException e) {

            ...exception logged...
        }catch (NullPointerException e) {
            ...exception logged...
        }
    }

    if(conn !=  null)
    {
        try {
            conn.close();
        } catch (SQLException e) {
            ...exception logged...              }
    }

}
.
.
.
</code>```

The rule shown by SonarQube is as below:

Method may fail to clean up stream or resource on checked exception
This method may fail to clean up (close, dispose of) a stream, database object, or other resource requiring an explicit cleanup operation.
In general, if a method opens a stream or other resource, the method should use a try/finally block to ensure that the stream or resource is cleaned up before the method returns.
This bug pattern is essentially the same as the OS_OPEN_STREAM and ODR_OPEN_DATABASE_RESOURCE bug patterns, but is based on a different (and hopefully better) static analysis technique. See Weimer and Necula, Finding and Preventing Run-Time Error Handling Mistakes, for a description of the analysis technique. .
findbugs:OBL_UNSATISFIED_OBLIGATION_EXCEPTION_EDGE  Sep12 Reliability > Exception handling

I have closed all the connections, statements and resultsets.
What might be the issue here?

答:
From this message method may fail to clean up java.sql.Statement on checked exception, my suspect is you are specific exception like NPE or SqlException. Try to catch Exception as a whole and try if it works . Reference as below.

```<code>try {
        if(rs !=  null)
        {
                rs.close();
        }
    } catch (Exception e) {
    ...exception logged...
}

if(stmt !=  null)
{
    try {
        stmt.close();
    } catch (Exception e) {

        ...exception logged...
    }
}

if(conn !=  null)
{
    try {
        conn.close();
    } catch (Exception e) {
        ...exception logged...              }
}
</code>```

Body:
The following statement in my code is being red-marked by SonarQube as a critical issue.
    stmt=conn.createStatement();

The exact issue is, "method may fail to clean up java.sql.Statement on checked exception".

Code snippet below:

.
.
.
try{
    .
    .
    .

    **stmt=conn.createStatement();**

    .
    .
    .
} catch (SQLException e) {
    ...exception logged...
} catch (NullPointerException e) {
    ...exception logged...
}finally{

    try {
            if(rs !=  null)
            {
                    rs.close();
            }
        } catch (SQLException e) {
        ...exception logged...
    }

    if(stmt !=  null)
    {
        try {
            stmt.close();
        } catch (SQLException e) {

            ...exception logged...
        }catch (NullPointerException e) {
            ...exception logged...
        }
    }

    if(conn !=  null)
    {
        try {
            conn.close();
        } catch (SQLException e) {
            ...exception logged...              }
    }

}
.
.
.

The rule shown by SonarQube is as below:

Method may fail to clean up stream or resource on checked exception
This method may fail to clean up (close, dispose of) a stream, database object, or other resource requiring an explicit cleanup operation.
In general, if a method opens a stream or other resource, the method should use a try/finally block to ensure that the stream or resource is cleaned up before the method returns.
This bug pattern is essentially the same as the OS_OPEN_STREAM and ODR_OPEN_DATABASE_RESOURCE bug patterns, but is based on a different (and hopefully better) static analysis technique. See Weimer and Necula, Finding and Preventing Run-Time Error Handling Mistakes, for a description of the analysis technique. .
findbugs:OBL_UNSATISFIED_OBLIGATION_EXCEPTION_EDGE  Sep12 Reliability > Exception handling

I have closed all the connections, statements and resultsets.
What might be the issue here?

Body:
From this message method may fail to clean up java.sql.Statement on checked exception, my suspect is you are specific exception like NPE or SqlException. Try to catch Exception as a whole and try if it works . Reference as below.

try {
        if(rs !=  null)
        {
                rs.close();
        }
    } catch (Exception e) {
    ...exception logged...
}

if(stmt !=  null)
{
    try {
        stmt.close();
    } catch (Exception e) {

        ...exception logged...
    }
}

if(conn !=  null)
{
    try {
        conn.close();
    } catch (Exception e) {
        ...exception logged...              }
}


问:
Unity Debug log not showing in iOS build
guys I've been struggling with the following issue for couple of days and hope that somebody could help me.

I want to get my app logs from running iOS device. If I run the app from the Xcode, then I see my logs in debug view as expected.

However, when I download a build from my testflight app I'm not able to access the logs anymore. Google suggest that I use Xcode -> Devices -> Log of a device, but there are only system events log and no messages from my app.

Running Unity 5.5.2.p2, Xcode 8.2.1. with ios 10 and 9 tested.

Would appreciate any help, because this issue is really exhausting.

答:
After a bit more searching I found out that it's not possible, unfortunately. But I've managed to make a solution, hope it helps somebody.

Apple's native NSLog prints all the logs to a console app even after the app was downloaded from TestFlight.

I made a simple iOS plugin wich catches all the debug logs and forwards them to a NSLog. Make sure you call

```<code>LogManager.Init()
</code>```

somewhere on app start.

Hope this will help somebody. The plugin is here

https://drive.google.com/open?id=0B7Yn93mXrM82ODZlbDVTNmo0QlU

Body:
After a bit more searching I found out that it's not possible, unfortunately. But I've managed to make a solution, hope it helps somebody.

Apple's native NSLog prints all the logs to a console app even after the app was downloaded from TestFlight.

I made a simple iOS plugin wich catches all the debug logs and forwards them to a NSLog. Make sure you call

LogManager.Init()

somewhere on app start.

Hope this will help somebody. The plugin is here

https://drive.google.com/open?id=0B7Yn93mXrM82ODZlbDVTNmo0QlU


问:
Why does the AutoGeneratingColumn event in a DataGrid repeat the columns?
When I search in a list I pass the result to a function to load the DataGrid
Each time the AutoGeneratingColumn event is fired, it repeats the same column once more.
When starting the application, the event checks the column once, doing the first search checks twice, with the second three times and so on.
I have the next function to load the DataGrid:</p>

```<code>private void cargarListaAgenda(List<listaAgendaClass> lista)
{
    Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() =>
    {
        gridAgendaDataGridAgenda.AutoGeneratingColumn += (s, e) =>
        {
            e.Column.Visibility = Visibility.Hidden;

            if (e.Column.Header.ToString() == "Nombre" || e.Column.Header.ToString() == "Alias" || e.Column.Header.ToString() == "Apellidos")
            {
                e.Column.Visibility = Visibility.Visible;

                if (e.Column.Header.ToString() != "Apellidos")
                    e.Column.Width = new DataGridLength(gridAgendaDataGridAgenda.Width * 0.33);

                else
                    e.Column.Width = new DataGridLength(1, DataGridLengthUnitType.Star);
            }
        };

        gridAgendaDataGridAgenda.ItemsSource = null;
        gridAgendaDataGridAgenda.ItemsSource = lista;
    }));
}
</code>```

答:
It seems like you are attaching a new event handler each time your cargarListaAgenda method is called.

Try to remove the event handler before you attach a new one:

```<code>private void cargarListaAgenda(List<listaAgendaClass> lista)
{
    Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() =>
    {
        gridAgendaDataGridAgenda.AutoGeneratingColumn -= GridAgendaDataGridAgenda_AutoGeneratingColumn;
        gridAgendaDataGridAgenda.AutoGeneratingColumn += GridAgendaDataGridAgenda_AutoGeneratingColumn;

        gridAgendaDataGridAgenda.ItemsSource = lista;
    }));
}

private void GridAgendaDataGridAgenda_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
    e.Column.Visibility = Visibility.Hidden;

    if (e.Column.Header.ToString() == "Nombre" || e.Column.Header.ToString() == "Alias" || e.Column.Header.ToString() == "Apellidos")
    {
        e.Column.Visibility = Visibility.Visible;

        if (e.Column.Header.ToString() != "Apellidos")
            e.Column.Width = new DataGridLength(gridAgendaDataGridAgenda.Width * 0.33);

        else
            e.Column.Width = new DataGridLength(1, DataGridLengthUnitType.Star);
    }
}
</code>```

Body:
When I search in a list I pass the result to a function to load the DataGrid
Each time the AutoGeneratingColumn event is fired, it repeats the same column once more.
When starting the application, the event checks the column once, doing the first search checks twice, with the second three times and so on.
I have the next function to load the DataGrid:

private void cargarListaAgenda(List<listaAgendaClass> lista)
{
    Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() =>
    {
        gridAgendaDataGridAgenda.AutoGeneratingColumn += (s, e) =>
        {
            e.Column.Visibility = Visibility.Hidden;

            if (e.Column.Header.ToString() == "Nombre" || e.Column.Header.ToString() == "Alias" || e.Column.Header.ToString() == "Apellidos")
            {
                e.Column.Visibility = Visibility.Visible;

                if (e.Column.Header.ToString() != "Apellidos")
                    e.Column.Width = new DataGridLength(gridAgendaDataGridAgenda.Width * 0.33);

                else
                    e.Column.Width = new DataGridLength(1, DataGridLengthUnitType.Star);
            }
        };

        gridAgendaDataGridAgenda.ItemsSource = null;
        gridAgendaDataGridAgenda.ItemsSource = lista;
    }));
}

Body:
It seems like you are attaching a new event handler each time your cargarListaAgenda method is called.

Try to remove the event handler before you attach a new one:

private void cargarListaAgenda(List<listaAgendaClass> lista)
{
    Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() =>
    {
        gridAgendaDataGridAgenda.AutoGeneratingColumn -= GridAgendaDataGridAgenda_AutoGeneratingColumn;
        gridAgendaDataGridAgenda.AutoGeneratingColumn += GridAgendaDataGridAgenda_AutoGeneratingColumn;

        gridAgendaDataGridAgenda.ItemsSource = lista;
    }));
}

private void GridAgendaDataGridAgenda_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
    e.Column.Visibility = Visibility.Hidden;

    if (e.Column.Header.ToString() == "Nombre" || e.Column.Header.ToString() == "Alias" || e.Column.Header.ToString() == "Apellidos")
    {
        e.Column.Visibility = Visibility.Visible;

        if (e.Column.Header.ToString() != "Apellidos")
            e.Column.Width = new DataGridLength(gridAgendaDataGridAgenda.Width * 0.33);

        else
            e.Column.Width = new DataGridLength(1, DataGridLengthUnitType.Star);
    }
}


问:
How to select Item Type with right join
I have a table

```<code>tblItemType(ID int,ItemType varchar(50))
</code>```

in this there are 7 enteries.

```<code>1   Tyre
2   Nozle
3   Brake
4   Headlight
5   KickPad
6   Battery
7   Seat
</code>```

I have Another table

```<code>Items (ItemType varchar(20), Size int)
</code>```

In this table there is only 2 itemtype.I want to select first entry each itemtype in items table and if there is no entry for any item type there should be 0. For this i used following query:-

```<code>select s.ItemType,s.Size from (SELECT SL.Size,SL.ItemType, ROW_NUMBER()
    OVER (PARTITION BY SL.ItemType ORDER BY SL.ItemType) AS RowNum
FROM    Items SL   )s
right join tblItemType as TS on TS.ItemType=S.ItemType
where s.RowNum = 1 and s.ItemType<>'' group by ts.ItemType,s.ItemType,s.size
</code>```

But the above query is returning

```<code> ID    ItemType     Size
 1       Tyre        17
 2       Battery     3
</code>```

The OutPut should be

```<code>        ItemType     Size
        Tyre          17
        Battery       3
        Nozle         0
        Brake         0
        Headlight     0
        KickPad       0
        Seat          0
</code>```

How to do that.

答:
Unless I'm missing something, a simple left join with coalesce should get you what you need:

```<code>SELECT it.ItemType, COALESCE(Size, 0)
FROM tblItemType it
LEFT JOIN Items i ON it.ItemType = i.ItemType
</code>```

btw, if you already have an id in tblItemType, you better use it to create a foriegn key with item - so if you can change the database structure you should change the Items table to something like this:

```<code>Items (itemTypeId int (fk to tblItem), size)
</code>```

and then your query would look like this:

```<code>SELECT it.ItemType, COALESCE(Size, 0)
FROM tblItemType it
LEFT JOIN Items i ON it.id = i.ItemTypeId
</code>```

Title: How to select Item Type with right join

Body:
I have a table

tblItemType(ID int,ItemType varchar(50))

in this there are 7 enteries.

1   Tyre
2   Nozle
3   Brake
4   Headlight
5   KickPad
6   Battery
7   Seat

I have Another table

Items (ItemType varchar(20), Size int)

In this table there is only 2 itemtype.I want to select first entry each itemtype in items table and if there is no entry for any item type there should be 0. For this i used following query:-

select s.ItemType,s.Size from (SELECT SL.Size,SL.ItemType, ROW_NUMBER()
    OVER (PARTITION BY SL.ItemType ORDER BY SL.ItemType) AS RowNum
FROM    Items SL   )s
right join tblItemType as TS on TS.ItemType=S.ItemType
where s.RowNum = 1 and s.ItemType<>'' group by ts.ItemType,s.ItemType,s.size

But the above query is returning

 ID    ItemType     Size
 1       Tyre        17
 2       Battery     3

The OutPut should be

        ItemType     Size
        Tyre          17
        Battery       3
        Nozle         0
        Brake         0
        Headlight     0
        KickPad       0
        Seat          0

How to do that.

Body:
Unless I'm missing something, a simple left join with coalesce should get you what you need:

SELECT it.ItemType, COALESCE(Size, 0)
FROM tblItemType it
LEFT JOIN Items i ON it.ItemType = i.ItemType

btw, if you already have an id in tblItemType, you better use it to create a foriegn key with item - so if you can change the database structure you should change the Items table to something like this:

Items (itemTypeId int (fk to tblItem), size)

and then your query would look like this:

SELECT it.ItemType, COALESCE(Size, 0)
FROM tblItemType it
LEFT JOIN Items i ON it.id = i.ItemTypeId


问:
Javascript click start / stop interval function
I want to start a interval / function if the user clicks on a button and stop that if the user clicks on stop. But somehow it immidietly starts the startRecord function. What am I doing wrong.

HTML:

window.onload = startRecord;

startRecord = document.getElementById('startRecord');
stopRecord = document.getElementById('stopRecord');

function startRecord() {
  startRecord.onclick = generateImg(true);
  startRecord.style.display = "none";
  stopRecord.style.display = "block";
}

function stopRecord() {
  stopRecord.onclick = generateImg(false);
  startRecord.style.display = "block";
  stopRecord.style.display = "none";
}

function generateImg(start) {
  if (start) {
    var startInterval = setInterval(function() {
      console.log("foo")
    }, 1000);
  } else {
    clearInterval(startInterval);
    console.log("stop foo")
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="btn-group">
  <button type="button" class="btn btn-default btn-lg" id="startRecord">
            Start
        </button>
  <button type="button" class="btn btn-default btn-lg" id="stopRecord">
            Stop
        </button>
</div></code>```

答:
You will need to define var startInterval in global scope.

```<code>startRecordButton = document.getElementById('startRecord');
stopRecordButton = document.getElementById('stopRecord');
startRecordButton.onclick = startRecord;
stopRecordButton.onclick = stopRecord;

var startInterval;

function startRecord() {
  generateImg(true);
  startRecord.style.display = "none";
  stopRecord.style.display = "block";
}

function stopRecord() {
  generateImg(false);
  startRecord.style.display = "block";
  stopRecord.style.display = "none";
}

function generateImg(start) {
  if (start) {
    startInterval = setInterval(function() {
      console.log("foo")
    }, 1000);
  } else {
    clearInterval(startInterval);
    console.log("stop foo")
  }
}
</code>```

Body:
I want to start a interval / function if the user clicks on a button and stop that if the user clicks on stop. But somehow it immidietly starts the startRecord function. What am I doing wrong.

HTML:

window.onload = startRecord;

startRecord = document.getElementById('startRecord');
stopRecord = document.getElementById('stopRecord');

function startRecord() {
  startRecord.onclick = generateImg(true);
  startRecord.style.display = "none";
  stopRecord.style.display = "block";
}

function stopRecord() {
  stopRecord.onclick = generateImg(false);
  startRecord.style.display = "block";
  stopRecord.style.display = "none";
}

function generateImg(start) {
  if (start) {
    var startInterval = setInterval(function() {
      console.log("foo")
    }, 1000);
  } else {
    clearInterval(startInterval);
    console.log("stop foo")
  }
}

  <button type="button" class="btn btn-default btn-lg" id="startRecord">
            Start
        </button>
  <button type="button" class="btn btn-default btn-lg" id="stopRecord">
            Stop
        </button>

Body:
You will need to define var startInterval in global scope.

startRecordButton = document.getElementById('startRecord');
stopRecordButton = document.getElementById('stopRecord');
startRecordButton.onclick = startRecord;
stopRecordButton.onclick = stopRecord;

var startInterval;

function startRecord() {
  generateImg(true);
  startRecord.style.display = "none";
  stopRecord.style.display = "block";
}

function stopRecord() {
  generateImg(false);
  startRecord.style.display = "block";
  stopRecord.style.display = "none";
}

function generateImg(start) {
  if (start) {
    startInterval = setInterval(function() {
      console.log("foo")
    }, 1000);
  } else {
    clearInterval(startInterval);
    console.log("stop foo")
  }
}


问:
Transparently assign value to a custom numeric type
I'd like to create a custom numeric type. Basically a float whose value gets processed by my custom class after an assignment.
I have seen examples that explain how to create the class and read it as a common type (int/float/...).
Yet there's no example about how to make the value assignment as transparent as for a float variable.

What I have seen so far is something like:

```<code>a = MyCustomFloat( 20. )
print(a) # prints "20"
</code>```

What I am looking for is:

```<code>a = MyCustomFloat()
a = 20. # assign new value ; "a" is still an instance of MyCustomFloat
print(a) # prints "20"
</code>```

Is this possible at all?

If yes, how?

答:
Since Python is a dynamic language you can assign anything you want to a later, so declaring its type beforehand will probably not do you any good as you could do something like:

```<code>a = MyType()
a = 'hi'
a = 2.3
</code>```

that means, if you do something like

```<code>a = MyType()
a = 20.
type(a)
</code>```

it will probably return the default (float or float64). If you want something like static typing (once you declare a to be of type MyType it will stay that way) I recommend using something like mypy

hope it helps

Body:
I'd like to create a custom numeric type. Basically a float whose value gets processed by my custom class after an assignment.
I have seen examples that explain how to create the class and read it as a common type (int/float/...).
Yet there's no example about how to make the value assignment as transparent as for a float variable.

What I have seen so far is something like:

a = MyCustomFloat( 20. )
print(a) # prints "20"

What I am looking for is:

a = MyCustomFloat()
a = 20. # assign new value ; "a" is still an instance of MyCustomFloat
print(a) # prints "20"

Is this possible at all?

If yes, how?

Body:
Since Python is a dynamic language you can assign anything you want to a later, so declaring its type beforehand will probably not do you any good as you could do something like:

a = MyType()
a = 'hi'
a = 2.3

that means, if you do something like

a = MyType()
a = 20.
type(a)

it will probably return the default (float or float64). If you want something like static typing (once you declare a to be of type MyType it will stay that way) I recommend using something like mypy

hope it helps


问:
VS Code Extension for Loading Source Code
I am interested in extending VS Code to load/edit/save project code, files, etc from a place other than the file system. For example, let's say I wanted to store my project in a database. I have looked at the extension API docs but didn't see anything obvious. Is there an API for extending VS Code in this way? </p>

答:
After some looking around it seems like you need to look at the "Workspace" section of the official API docs:

https://code.visualstudio.com/docs/extensionAPI/vscode-api#_workspace

The rootPath variable takes a string argument, but there's nothing saying that it needs to be a file path so perhaps there's some wiggle room there.

That being said the createFileSystemWatcher() method appears to be set up to work with an actual file system. So even if you can get VSC to find files from somewhere like a database - you probably can't use any of the events that update the UI on changing a file.