问:
Difference between x.toString() and x+""
Back in college one of my profs. taught us to just do x + "" as a quick conversion from basic types to strings.

I don't remember which class it was in I had him for some Java and C++ courses(I haven't used either for some time now), but I use it in C#/.Net now which is what I'm primarily developing in lately.

Is there an advantage to using .toString() over +"" for basic types such at int, decimal, float...?
What cases would .toString() be better?

Note:I was shown .toString() as well, that prof just recommended +"" because it was shorter and I have just done that since then without questioning it.

答:
In Java, for primitive types (int, double, etc.) you cannot write .toString() because the types aren't objects.  This means that your options are either to write something like

```<code>x + "";
</code>```

or to use

```<code>Integer.toString(x);
</code>```

In C++, you cannot use x + "" to do this sort of conversion, since this will be treated as pointer arithmetic and will give you a bad pointer.  Using something like boost::lexical_cast is the preferred way to do the conversion.

And... I know nothing about C#, so I won't comment on it. :-)

Body:
In Java, for primitive types (int, double, etc.) you cannot write .toString() because the types aren't objects.  This means that your options are either to write something like

x + "";

or to use

Integer.toString(x);

In C++, you cannot use x + "" to do this sort of conversion, since this will be treated as pointer arithmetic and will give you a bad pointer.  Using something like boost::lexical_cast is the preferred way to do the conversion.

And... I know nothing about C#, so I won't comment on it. :-)


来源: stackexchange

问:
How to use Triggering and template to send sms
```<code>class CMSSmsTemplate(models.Model):
"""
This is the   internal template
Which will have the SMS Trigger field/the SmS body/the SmS Template
"""
  sms_trigger = models.CharField(max_length=128)
  sms_body = models.CharField(max_length=255)
  sms_Body = models.TextField(blank=True, null=True)
  sms_template_name = models.CharField(max_length=128)
</code>```

<p>I have this model, which i'm using to send my sms, what triggers my sms to be sent is mainly the sms_template_name, how can i efficiently use,to trigger and send the sms. Any advices? </p>

答: Please use the Django signals(post_save) with celery in order trigger the SMS sending process when a new object is created I think it is the most efficient way to use. for easy implementation you can just use the post_save signal in order to trigger the SMS sending process please refer this link </p>

ContentLicense: CC BY-SA 3.0

Body:
class CMSSmsTemplate(models.Model):
"""
This is the   internal template
Which will have the SMS Trigger field/the SmS body/the SmS Template
"""
  sms_trigger = models.CharField(max_length=128)
  sms_body = models.CharField(max_length=255)
  sms_Body = models.TextField(blank=True, null=True)
  sms_template_name = models.CharField(max_length=128)

I have this model, which i'm using to send my sms, what triggers my sms to be sent is mainly the sms_template_name, how can i efficiently use,to trigger and send the sms. Any advices?


问:
route redirects to nothing react-router 4
I'm not sure why everything is redirecting to a blank page:

I'm using:

```<code>"react-router": "^4.2.0",
"react-router-dom": "^4.1.1",
</code>```

App.js

```<code>import { BrowserRouter, Route, Switch } from 'react-router-dom';

    class Container extends Component{
      render() {
        return (
          <div>{this.props.children}</div>
        );
      }
    }

    export default class App extends Component {
      render() {
        return (
          <BrowserRouter onUpdate={onUpdate}>
            <Switch>
              <Route component={HomePageContainer} exact path="/" />
              <Route component={CompanyDetailContainer} name="companydetail" path="interviews/companies/:companyId/details" />
              <Route component={InterviewContainer} name="interview" path="interviews/companies/:companyId" />
              <Route component={Container} path="/" />
              <Route component={NotFound} path="*" />
            </Switch>
          </BrowserRouter>
        );
      }
    }
</code>```

Homepage route to '/' is working fine.

What's not working are all the other routes.

For example when a user clicks a hyperlink that redirects to these routes or other routes other than the default route, I'm getting a blank page:

```<code>   <Route component={CompanyDetailContainer} name="companydetail" path="interviews/companies/:companyId/details" />
      <Route component={InterviewContainer} name="interview" path="interviews/companies/:companyId" />
</code>```

Here is how my routes were working when I was using react-router v3:

```<code><Router history={browserHistory} onUpdate={onUpdate}>
    <Route path="/">
      <IndexRoute component={HomePageContainer} />
      <Route component={InterviewContainer} name="interview"  path="interviews/companies/:companyId" />
      <Route component={About} name="about" path="about"  />
      <Route component={JobList} name="jobs" path="jobs"  />
    </Route>
    <Route component={Container} path="/"  />
    <Route component={NotFound} path="*"  />
</Router>
</code>```

Note that I also added the new route for companydetail just recently.

答:
All your paths needs to be with respect to to base path i.e. /

Change your router config to

```<code> <Switch>
          <Route component={HomePageContainer} exact path="/" />
          <Route component={CompanyDetailContainer} name="companydetail" path="/interviews/companies/:companyId/details" />
          <Route component={InterviewContainer} name="interview" path="/interviews/companies/:companyId" />
          <Route component={Container} path="/" />
          <Route component={NotFound} path="*" />
 </Switch>
</code>```

Body:
I'm not sure why everything is redirecting to a blank page:

I'm using:

"react-router": "^4.2.0",
"react-router-dom": "^4.1.1",

App.js

import { BrowserRouter, Route, Switch } from 'react-router-dom';

    class Container extends Component{
      render() {
        return (

{this.props.children}

        );
      }
    }

    export default class App extends Component {
      render() {
        return (
          <BrowserRouter onUpdate={onUpdate}>
            <Switch>
              <Route component={HomePageContainer} exact path="/" />
              <Route component={CompanyDetailContainer} name="companydetail" path="interviews/companies/:companyId/details" />
              <Route component={InterviewContainer} name="interview" path="interviews/companies/:companyId" />
              <Route component={Container} path="/" />
              <Route component={NotFound} path="*" />
            </Switch>
          </BrowserRouter>
        );
      }
    }

Homepage route to '/' is working fine.

What's not working are all the other routes.

For example when a user clicks a hyperlink that redirects to these routes or other routes other than the default route, I'm getting a blank page:

   <Route component={CompanyDetailContainer} name="companydetail" path="interviews/companies/:companyId/details" />
      <Route component={InterviewContainer} name="interview" path="interviews/companies/:companyId" />

Here is how my routes were working when I was using react-router v3:

<Router history={browserHistory} onUpdate={onUpdate}>
    <Route path="/">
      <IndexRoute component={HomePageContainer} />
      <Route component={InterviewContainer} name="interview"  path="interviews/companies/:companyId" />
      <Route component={About} name="about" path="about"  />
      <Route component={JobList} name="jobs" path="jobs"  />
    </Route>
    <Route component={Container} path="/"  />
    <Route component={NotFound} path="*"  />
</Router>

Note that I also added the new route for companydetail just recently.

Body:
All your paths needs to be with respect to to base path i.e. /

Change your router config to

 <Switch>
          <Route component={HomePageContainer} exact path="/" />
          <Route component={CompanyDetailContainer} name="companydetail" path="/interviews/companies/:companyId/details" />
          <Route component={InterviewContainer} name="interview" path="/interviews/companies/:companyId" />
          <Route component={Container} path="/" />
          <Route component={NotFound} path="*" />
 </Switch>


问:
react js and existing Laravel project
I've searched internet and no where I've found a complete solution for what I'm trying to achieve. I'm trying to:

Add react related modules to existing Laravel project.

Use existing gulp file to make all react related code available to my Laravel blade layouts.

Then put JSX code to my Laravel's public folder and use those components in the blade templates.

Here's how the structure of the existing gulp.js file looks like:

```<code>var elixir = require('laravel-elixir');

elixir(function (mix) {
    var cssFilesList = [
        ...
    ];

    var jsFooterFilesList = [
        ...
    ];

    var afterLoginjsFilesList = [
        ...
    ];

    elixir.config.assetsDir = 'custom/path';

    mix.styles(...);
    mix.scripts(...).scripts(more...);
    mix.version(...all of the above...)
});
</code>```

I've tried to follow different tutorials like:
this tutorial and this one

which more or less suggested me to update react related dependencies using npm, which I did. My package.json looks like:

```<code>{
  "private": true,
  "devDependencies": {
    "gulp": "^3.8.8"
  },
  "dependencies": {
    "babel-core": "^6.26.0",
    "babel-loader": "^7.1.2",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "bootstrap-sass": "^3.0.0",
    "express": "^4.15.3",
    "ioredis": "^3.0.0",
    "laravel-elixir": "^2.0.0",
    "laravel-elixir-webpack-official": "^1.0.10",
    "laravel-elixir-webpack-react": "^1.0.1",
    "react": "^16.1.1",
    "react-dom": "^16.1.1",
    "require-dir": "^0.3.2",
    "socket.io": "^2.0.1"
  }
}
</code>```

Now that the react related dependencies are installed, I've changed my gulp.js file so that it looks like the following:

```<code>var elixir = require('laravel-elixir');
require('laravel-elixir-webpack-official');

// configure webpack
Elixir.webpack.mergeConfig({
    babel: {
        presets: [
            'react',
            'es2015',
            'stage-0',
        ]
    }
})

elixir(function (mix) {
    var cssFilesList = [
        ...
    ];

    var jsFooterFilesList = [
        ...
    ];

    var afterLoginjsFilesList = [
        ...
    ];

    elixir.config.assetsDir = 'custom/path';

    mix.webpack('reactcode.js');

    mix.styles(...);
    mix.scripts(...).scripts(more...);
    mix.version(...all of the above...)
});
</code>```

Now I'm trying to compile this by:

```<code>gulp
</code>```

Which throws two of the following errors depending on what I'm including on the top of the gulp file. If I include the line:

```<code>require('laravel-elixir-webpack-official');
</code>```

It says:

```<code>ReferenceError: Elixir is not defined
    at Object.<anonymous> (/path_to_project/node_modules/laravel-elixir-webpack-official/dist/WebpackTask.js:110:3)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/path_to_project/node_modules/laravel-elixir-webpack-official/dist/index.js:5:20)
    at Module._compile (module.js:570:32)
</code>```

If I include the line:

```<code>require('laravel-elixir-webpack-react');
</code>```

It says:

```<code>/path_to_project/node_modules/laravel-elixir-webpack-react/main.js:3
Elixir.ready(function() {
       ^

TypeError: Elixir.ready is not a function
    at Object.<anonymous> (/path_to_project/node_modules/laravel-elixir-webpack-react/main.js:3:8)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/path_to_project/gulpfile.js:4:1)
    at Module._compile (module.js:570:32)
</code>```

All of these attempts were sort of hit and trial approaches as suggested by the above stated links.

Does anyone know a step by step method of exactly how this can be done? Any link or resource. Also if anyone can rectify what I might be doing wrong.

Any help is greatly appreciated.

答:
EDIT 2021

Now that I have been working with React over the last 3.5 years, I believe I can answer my own question. In fact the question (or approach) itself is wrong.

I should have bundled React code using Webpack. Here are the steps -

Create a folder for your React sub project inside the Laravel directory, you can organize it as you wish.

Setup React with Webpack (out of scope for this edit), there are 100s of tutorials on net.

In development mode spin up dev server from Webpack. Typically localhost:8080. Front end will communicate to the Laravel base using API/Json bridge.

Once you are satisfied with the dev version, generate production version of the React code. This will spit out JS bundles, CSS bundles and assets in the path you configured.

Pull these bundles in your normal Laravel template and boom - you have your React app running with the main framework being Laravel.

SOLVED

It eventually worked with the version of gulp.js where I had:

```<code>require('laravel-elixir-webpack-official');
</code>```

This was initially throwing error like:

```<code>ReferenceError: Elixir is not defined
</code>```

I upgraded the package laravel-elixir to 6.0.x, such that now it looks like the following in my package.json:

```<code>"laravel-elixir": "^6.0.0-0"
</code>```

To produce a compiled JS file which includes React related code and your components, add something like the following to your gulp file:

```<code>mix.webpack('comp1.js', 'destination/to/public/directory', 'source/of/your/components/');
</code>```

Please note I kept the source JS file name as comp1.js which had my react component code. I'll experiment soon to see if they could have different names.

Compile from the root of the project using gulp. This will generate your compiled file, which when included in your blade layout or view will let you render your component in your Laravel page.

And there we go, I now have a way to use React inside Laravel.

Notes

My npm version is:

```<code>3.10.10
</code>```

And node version is:

```<code>6.12.0
</code>```

Add this because I had issues updating packages when those versions were different, particularly when node was not LTS. Hope this helps.

Title: react js and existing Laravel project

Body:
I've searched internet and no where I've found a complete solution for what I'm trying to achieve. I'm trying to:

Add react related modules to existing Laravel project.

Use existing gulp file to make all react related code available to my Laravel blade layouts.

Then put JSX code to my Laravel's public folder and use those components in the blade templates.

Here's how the structure of the existing gulp.js file looks like:

var elixir = require('laravel-elixir');

elixir(function (mix) {
    var cssFilesList = [
        ...
    ];

    var jsFooterFilesList = [
        ...
    ];

    var afterLoginjsFilesList = [
        ...
    ];

    elixir.config.assetsDir = 'custom/path';

    mix.styles(...);
    mix.scripts(...).scripts(more...);
    mix.version(...all of the above...)
});

I've tried to follow different tutorials like:
this tutorial and this one

which more or less suggested me to update react related dependencies using npm, which I did. My package.json looks like:

{
  "private": true,
  "devDependencies": {
    "gulp": "^3.8.8"
  },
  "dependencies": {
    "babel-core": "^6.26.0",
    "babel-loader": "^7.1.2",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "bootstrap-sass": "^3.0.0",
    "express": "^4.15.3",
    "ioredis": "^3.0.0",
    "laravel-elixir": "^2.0.0",
    "laravel-elixir-webpack-official": "^1.0.10",
    "laravel-elixir-webpack-react": "^1.0.1",
    "react": "^16.1.1",
    "react-dom": "^16.1.1",
    "require-dir": "^0.3.2",
    "socket.io": "^2.0.1"
  }
}

Now that the react related dependencies are installed, I've changed my gulp.js file so that it looks like the following:

var elixir = require('laravel-elixir');
require('laravel-elixir-webpack-official');

// configure webpack
Elixir.webpack.mergeConfig({
    babel: {
        presets: [
            'react',
            'es2015',
            'stage-0',
        ]
    }
})

elixir(function (mix) {
    var cssFilesList = [
        ...
    ];

    var jsFooterFilesList = [
        ...
    ];

    var afterLoginjsFilesList = [
        ...
    ];

    elixir.config.assetsDir = 'custom/path';

    mix.webpack('reactcode.js');

    mix.styles(...);
    mix.scripts(...).scripts(more...);
    mix.version(...all of the above...)
});

Now I'm trying to compile this by:

gulp

Which throws two of the following errors depending on what I'm including on the top of the gulp file. If I include the line:

require('laravel-elixir-webpack-official');

It says:

ReferenceError: Elixir is not defined
    at Object.<anonymous> (/path_to_project/node_modules/laravel-elixir-webpack-official/dist/WebpackTask.js:110:3)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/path_to_project/node_modules/laravel-elixir-webpack-official/dist/index.js:5:20)
    at Module._compile (module.js:570:32)

If I include the line:

require('laravel-elixir-webpack-react');

It says:

/path_to_project/node_modules/laravel-elixir-webpack-react/main.js:3
Elixir.ready(function() {
       ^

TypeError: Elixir.ready is not a function
    at Object.<anonymous> (/path_to_project/node_modules/laravel-elixir-webpack-react/main.js:3:8)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/path_to_project/gulpfile.js:4:1)
    at Module._compile (module.js:570:32)

All of these attempts were sort of hit and trial approaches as suggested by the above stated links.

Does anyone know a step by step method of exactly how this can be done? Any link or resource. Also if anyone can rectify what I might be doing wrong.

Any help is greatly appreciated.

Body:
EDIT 2021

Now that I have been working with React over the last 3.5 years, I believe I can answer my own question. In fact the question (or approach) itself is wrong.

I should have bundled React code using Webpack. Here are the steps -

Create a folder for your React sub project inside the Laravel directory, you can organize it as you wish.

Setup React with Webpack (out of scope for this edit), there are 100s of tutorials on net.

In development mode spin up dev server from Webpack. Typically localhost:8080. Front end will communicate to the Laravel base using API/Json bridge.

Once you are satisfied with the dev version, generate production version of the React code. This will spit out JS bundles, CSS bundles and assets in the path you configured.

Pull these bundles in your normal Laravel template and boom - you have your React app running with the main framework being Laravel.

SOLVED

It eventually worked with the version of gulp.js where I had:

require('laravel-elixir-webpack-official');

This was initially throwing error like:

ReferenceError: Elixir is not defined

I upgraded the package laravel-elixir to 6.0.x, such that now it looks like the following in my package.json:

"laravel-elixir": "^6.0.0-0"

To produce a compiled JS file which includes React related code and your components, add something like the following to your gulp file:

mix.webpack('comp1.js', 'destination/to/public/directory', 'source/of/your/components/');

Please note I kept the source JS file name as comp1.js which had my react component code. I'll experiment soon to see if they could have different names.

Compile from the root of the project using gulp. This will generate your compiled file, which when included in your blade layout or view will let you render your component in your Laravel page.

And there we go, I now have a way to use React inside Laravel.

Notes

My npm version is:

3.10.10

And node version is:

6.12.0

Add this because I had issues updating packages when those versions were different, particularly when node was not LTS. Hope this helps.

ContentLicense: CC BY-SA 4.0


问:
Unable to get the "Text" of the "element" using "Protractor"
Hi I am writing Protractor automation scripts for "Angular 4" application .

The development code is below.

```<code><!--Byndd Title div-->
            <div class="ui-g-12 ui-md-8 ui-lg-10">
                <div class="bynndTitleClass"  i18n="@@introductionBynddHeader">
                    BynddYour Information Together And CONNECT to the world  in an EFFICIENT way
                </div>
            </div>
</code>```

my protractor test script is below.

Page Object code :

```<code>//to return login page heading
    getLoginPageMainHeading(){
              return element(by.css('div[class="bynndTitleClass"]')).getText();
    }
</code>```

Spec code :

```<code> //Testcase1 : To open the "Login page" of the application
    it('should open the Login page' , ()=>{
        //To open the Login page
        page.loginPageDisplay();

        // to verify whether the Current page is Login page or not by comparing with Login page Main heading
        expect(page.getLoginPageMainHeading().toString()).toBe('BynddYour Information Together And CONNECT to the world  in an EFFICIENT way');
    });
</code>```

After execution it is displaying below error message.
W

```<code>1) should test certificate tab should open the Login page
  - Expected '[object Object]' to be 'BynddYour Information Together And CONNECT to the world  in an EFFICIENT way'.
</code>```

Can anyone help me how to solve this issue

答:
Because expect() resolves a promise itself, you're on the right path to return element.getText() within your pageObject.

However, because you added .toString(), your expect command now puts the element to String rather than resolving the promise.

I'd suggest to return just the element, and apply the getText() within your expect statement. It makes more sense and keeps your pageObject function better re-usable for other tests as well.

So here my suggestion:

PageObject (return just the element without getText()):

```<code>//to return login page heading
getLoginPageMainHeading(){
          return element(by.css('div[class="bynndTitleClass"]'));
}
</code>```

and Spec (getText() instead of toString()):

```<code>//Testcase1 : To open the "Login page" of the application
it('should open the Login page' , ()=>{
    //To open the Login page
    page.loginPageDisplay();

    // to verify whether the Current page is Login page or not by comparing with Login page Main heading
    expect(page.getLoginPageMainHeading().getText()).toBe('BynddYour Information Together And CONNECT to the world  in an EFFICIENT way');
});
</code>```

Body:
Hi I am writing Protractor automation scripts for "Angular 4" application .

The development code is below.

                    BynddYour Information Together And CONNECT to the world  in an EFFICIENT way

my protractor test script is below.

Page Object code :

//to return login page heading
    getLoginPageMainHeading(){
              return element(by.css('div[class="bynndTitleClass"]')).getText();
    }

Spec code :

 //Testcase1 : To open the "Login page" of the application
    it('should open the Login page' , ()=>{
        //To open the Login page
        page.loginPageDisplay();

        // to verify whether the Current page is Login page or not by comparing with Login page Main heading
        expect(page.getLoginPageMainHeading().toString()).toBe('BynddYour Information Together And CONNECT to the world  in an EFFICIENT way');
    });

After execution it is displaying below error message.
W

1) should test certificate tab should open the Login page
  - Expected '[object Object]' to be 'BynddYour Information Together And CONNECT to the world  in an EFFICIENT way'.

Can anyone help me how to solve this issue

Body:
Because expect() resolves a promise itself, you're on the right path to return element.getText() within your pageObject.

However, because you added .toString(), your expect command now puts the element to String rather than resolving the promise.

I'd suggest to return just the element, and apply the getText() within your expect statement. It makes more sense and keeps your pageObject function better re-usable for other tests as well.

So here my suggestion:

PageObject (return just the element without getText()):

//to return login page heading
getLoginPageMainHeading(){
          return element(by.css('div[class="bynndTitleClass"]'));
}

and Spec (getText() instead of toString()):

//Testcase1 : To open the "Login page" of the application
it('should open the Login page' , ()=>{
    //To open the Login page
    page.loginPageDisplay();

    // to verify whether the Current page is Login page or not by comparing with Login page Main heading
    expect(page.getLoginPageMainHeading().getText()).toBe('BynddYour Information Together And CONNECT to the world  in an EFFICIENT way');
});


问:
How to force an integer into two digits exactly in JavaScript?
The problem is from my trying to convert number into a time format. I'd like to put time like "8:5" into "08:05". Any elegant JavaScript code?</p>

答:
Use split, map, slice and join

```<code>"8:5".split(":").map((s)=>("0"+s).slice(-2)).join(":"); //prints 08:05
</code>```

You can invoke this at the blur/change event of your input box.

Body:
Use split, map, slice and join

"8:5".split(":").map((s)=>("0"+s).slice(-2)).join(":"); //prints 08:05

You can invoke this at the blur/change event of your input box.


问:
jpa entitymanager rollback not working
In my spring project i am using hibernate entitymanager. I have done transaction management in the project like below.

applicationContext.xml

```<code><bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
        <property name="url" value="jdbc:oracle:thin:@xxxx:1527:selva" />
        <property name="username" value="xxx" />
        <property name="password" value="yyy" />
</bean>
<bean
            class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
        <bean id="entityManagerFactory"
            class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
            <property name="dataSource" ref="dataSource" />
            <property name="packagesToScan">
                <list>
                    <value>com.selva.entity</value>
                </list>
            </property>
            <property name="jpaVendorAdapter">
                <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                    <property name="database" value="ORACLE" />
                    <property name="showSql" value="true" />
                </bean>
            </property>
        </bean>
        <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
            <property name="entityManagerFactory" ref="entityManagerFactory" />
        </bean>
</code>```

TestTranService.java

```<code>@Transactional
    public String checkTranWork() {
        try {
            testTranDao.method1();
            int i=0;
            if(i==0)
                throw new ValidationException();
            testTranDao.method2();
            testTranDao.method3();
        } catch(Exception e) {
            e.printStackTrace();
        }
        return null;
    }
</code>```

TestTranDaoImpl.java

```<code>public class TestTranDaoImpl implements TestTranDao {

    public static final Logger LOGGER = Logger
            .getLogger(TestTranDaoImpl.class);

    @PersistenceContext
    private EntityManager entityManager;

    public void setEntityManager(EntityManager entityManager) {
        this.entityManager = entityManager;
    }

    public EntityManager getEntityManager() {
        return entityManager;
    }

    @Override
    public void method1() {
        try {
            String sql = "INSERT INTO CUST(MOBNUM,CUST_NAME) values ('1','dd')";
            Query query = entityManager.createNativeQuery(sql);
            query.executeUpdate();
        } catch(Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void method2() {
try {
    String sql = "INSERT INTO CUST(MOBNUM,CUST_NAME) values ('1','dd')";
    Query query = entityManager.createNativeQuery(sql);
    query.executeUpdate();
        } catch(Exception e) {
            e.printStackTrace();
        }

    }

}
</code>```

In my code after method 1 executing the insert statement i am throwing the exception so the first statement should be rolled back.But in my case rollback is not happened.Is their any other configuration required for rollback.

Any help will be greatly appreciated!!!

答:
As explained by Gillaume for @Transactional to work, the method has to throw an exception then only the framework will know that rollback has to be performed.
One solution already suggested is to remove the try/catch and if there is a need to catch the exception and log in application error log file then make sure the exception is propagated not consumed.
So the updated code would look like:

```<code>@Transactional
    public String checkTranWork() {
        try {
            testTranDao.method1();
            int i=0;
            if(i==0)
                throw new ValidationException();
            testTranDao.method2();
            testTranDao.method3();
        } catch(Exception e) {
            e.printStackTrace();
            throw e;
        }
        return null;
    }
</code>```

Title: jpa entitymanager rollback not working

Body:
In my spring project i am using hibernate entitymanager. I have done transaction management in the project like below.

applicationContext.xml

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
        <property name="url" value="jdbc:oracle:thin:@xxxx:1527:selva" />
        <property name="username" value="xxx" />
        <property name="password" value="yyy" />
</bean>
<bean
            class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
        <bean id="entityManagerFactory"
            class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
            <property name="dataSource" ref="dataSource" />
            <property name="packagesToScan">
                <list>
                    <value>com.selva.entity</value>
                </list>
            </property>
            <property name="jpaVendorAdapter">
                <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                    <property name="database" value="ORACLE" />
                    <property name="showSql" value="true" />
                </bean>
            </property>
        </bean>
        <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
            <property name="entityManagerFactory" ref="entityManagerFactory" />
        </bean>

TestTranService.java

@Transactional
    public String checkTranWork() {
        try {
            testTranDao.method1();
            int i=0;
            if(i==0)
                throw new ValidationException();
            testTranDao.method2();
            testTranDao.method3();
        } catch(Exception e) {
            e.printStackTrace();
        }
        return null;
    }

TestTranDaoImpl.java

public class TestTranDaoImpl implements TestTranDao {

    public static final Logger LOGGER = Logger
            .getLogger(TestTranDaoImpl.class);

    @PersistenceContext
    private EntityManager entityManager;

    public void setEntityManager(EntityManager entityManager) {
        this.entityManager = entityManager;
    }

    public EntityManager getEntityManager() {
        return entityManager;
    }

    @Override
    public void method1() {
        try {
            String sql = "INSERT INTO CUST(MOBNUM,CUST_NAME) values ('1','dd')";
            Query query = entityManager.createNativeQuery(sql);
            query.executeUpdate();
        } catch(Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void method2() {
try {
    String sql = "INSERT INTO CUST(MOBNUM,CUST_NAME) values ('1','dd')";
    Query query = entityManager.createNativeQuery(sql);
    query.executeUpdate();
        } catch(Exception e) {
            e.printStackTrace();
        }

    }

}

In my code after method 1 executing the insert statement i am throwing the exception so the first statement should be rolled back.But in my case rollback is not happened.Is their any other configuration required for rollback.

Any help will be greatly appreciated!!!

Body:
As explained by Gillaume for @Transactional to work, the method has to throw an exception then only the framework will know that rollback has to be performed.
One solution already suggested is to remove the try/catch and if there is a need to catch the exception and log in application error log file then make sure the exception is propagated not consumed.
So the updated code would look like:

@Transactional
    public String checkTranWork() {
        try {
            testTranDao.method1();
            int i=0;
            if(i==0)
                throw new ValidationException();
            testTranDao.method2();
            testTranDao.method3();
        } catch(Exception e) {
            e.printStackTrace();
            throw e;
        }
        return null;
    }


问:
delim command only reading parts of a txt file
I'm a newbie to programming.

I have a txt fileA containing the list of files within a directory.

Scenario:
I'm running the delim command to remove new line special character codes and replace with commas from the list of jpg file names (cicra 10000) in the txt fileA and output the result to output fileB.

Problem:
Only a random amount of file names reach the output file! Some or many are missing.

Here's the code...

========================================

```<code>dir /o /b > fileA.txt
set "txt="
for /f "delims=" %%a in (fileA.txt) do (
  set "txt=!txt!%%a,"
)
set "txt=!txt:~0,-1!"
>fileB.txt echo !txt!
</code>```

=========================================

Any help appreciated :)
Thank you

答:
Read the Microsoft support article Command prompt (Cmd. exe) command-line string limitation which explains why not all file names are appended to the environment variable txt on such a large list of file names.

One workaround solution is writing the file names into a text file and use tools to replace all carriage return + line-feed pairs by a comma.

Here are two solutions using this workaround from answers on

How can you find and replace text in a file using the Windows command-line environment?

```<code>@echo off
rem Replace using very fast Xchang32.exe written by Clay Ruth.
dir *.jpg *.jpeg /A-D /B /ON >ImageList1.txt
"%~dp0Xchang32.exe" ImageList1.txt "^x0D^x0A" ",," >nul

rem Replace using a bit slower jrepl.bat written by Dave Benham.
dir *.jpg *.jpeg /A-D /B /ON >ImageList2.txt
call "%~dp0jrepl.bat" "\r\n" "," /M /F ImageList2.txt /O -
</code>```

Xchang32.exe written by Clay Ruth or jrepl.bat written by Dave Benham must be in same directory as the batch file.

Note 1:

The contents of the image list files end on both solutions with a comma because last line output by DIR also ends with carriage return + line-feed.

I tried also following command line:

```<code>call "%~dp0jrepl.bat" "\r\n(?=.)" "," /M /F ImageList2.txt /O -
</code>```

The regular expression search string \r\n(?=.) with replace string , is working in text editors supporting regular expressions in PRE syntax which would not replace the last carriage return + line-feed in file because the positive lookahead for any character except newline character is not true on last CR+LF, but that is not working with jrepl.bat using Microsoft's JScript (at least on Windows XP).

Note 2:

On not using *.jpg *.jpeg on DIR command line it is recommended to create the image list file not in the same directory as DIR is searching for files of any name because in this case the list file would be also included in the list.

Important note: Clay Ruth, author of Xchang32.exe and owner of domain clayruth.com died years ago. For that reason the ZIP file with this tool is not available anymore in world wide web although it was permitted explicitly to distribute this package free of charge according to read me file in the ZIP file.

Body:
I'm a newbie to programming.

I have a txt fileA containing the list of files within a directory.

Scenario:
I'm running the delim command to remove new line special character codes and replace with commas from the list of jpg file names (cicra 10000) in the txt fileA and output the result to output fileB.

Problem:
Only a random amount of file names reach the output file! Some or many are missing.

Here's the code...

========================================

dir /o /b > fileA.txt
set "txt="
for /f "delims=" %%a in (fileA.txt) do (
  set "txt=!txt!%%a,"
)
set "txt=!txt:~0,-1!"
>fileB.txt echo !txt!

=========================================

Any help appreciated :)
Thank you

Body:
Read the Microsoft support article Command prompt (Cmd. exe) command-line string limitation which explains why not all file names are appended to the environment variable txt on such a large list of file names.

One workaround solution is writing the file names into a text file and use tools to replace all carriage return + line-feed pairs by a comma.

Here are two solutions using this workaround from answers on

How can you find and replace text in a file using the Windows command-line environment?

@echo off
rem Replace using very fast Xchang32.exe written by Clay Ruth.
dir *.jpg *.jpeg /A-D /B /ON >ImageList1.txt
"%~dp0Xchang32.exe" ImageList1.txt "^x0D^x0A" ",," >nul

rem Replace using a bit slower jrepl.bat written by Dave Benham.
dir *.jpg *.jpeg /A-D /B /ON >ImageList2.txt
call "%~dp0jrepl.bat" "\r\n" "," /M /F ImageList2.txt /O -

Xchang32.exe written by Clay Ruth or jrepl.bat written by Dave Benham must be in same directory as the batch file.

Note 1:

The contents of the image list files end on both solutions with a comma because last line output by DIR also ends with carriage return + line-feed.

I tried also following command line:

call "%~dp0jrepl.bat" "\r\n(?=.)" "," /M /F ImageList2.txt /O -

The regular expression search string \r\n(?=.) with replace string , is working in text editors supporting regular expressions in PRE syntax which would not replace the last carriage return + line-feed in file because the positive lookahead for any character except newline character is not true on last CR+LF, but that is not working with jrepl.bat using Microsoft's JScript (at least on Windows XP).

Note 2:

On not using *.jpg *.jpeg on DIR command line it is recommended to create the image list file not in the same directory as DIR is searching for files of any name because in this case the list file would be also included in the list.

Important note: Clay Ruth, author of Xchang32.exe and owner of domain clayruth.com died years ago. For that reason the ZIP file with this tool is not available anymore in world wide web although it was permitted explicitly to distribute this package free of charge according to read me file in the ZIP file.


问:
How to deploy Play Framework based apps
I am new to Play Framework (2.0.4). I have developed a little app and ran it locally on built-in play framework web server. Now I want to deploy it on remote server (APPFOG.COM or any other web server). Can some one guide me how deploy it remotely.

Whether I have to create war file, if so, then guide me how to create it and deploy it on remote server.

If there is some other way, please guide me in this regards.

Thanks in advance

答:
Recently wrote a post showing steps for deploying a full proof self-reloadable play-application using supervisor and monit.

I wrote this because the play deploying documentation doesn't have solutions to problems, like failures due to tun time exceptions or application hang due to memory leakage, at the point of writing.  Monit is a great tool for monitoring processes running in background.
http://www.ravinderpayal.com/Deploying-Play-Scala-application-into-production-by-Ravinder-Payal/

Title: How to deploy Play Framework based apps


问:
AudioKit: Can I disable an AKMicrophone without calling AudioKit.stop()?
I've got an app with two features. One plays an AKMetronome and allows background playback when the app is not in the foreground. The other is a tuner feature which uses AKMicrophone, which only needs to be active when the app is in the foreground. These features can be used simultaneously (a blinking metronome light while the tuner is active).

When I press the home button, the metronome keeps playing (as expected). But the active microphone for the tuner also causes the bright red "recording"-style bar across the top of the device in all other apps. I don't need the tuner to function when the app isn't open though.

How do I disable the AKMicrophone node so that this bar doesn't show up, while also keeping the AKMetronome node playing uninterrupted?

I've tried the following, all with no success:

Calling AudioKit.stop() in the app delegate applicationWillResignActive() method. This gets rid of the recording bar, but stops the metronome.

Calling stop() on the AKMicrophone node during applicationWillResignActive(). This doesn't remove the recording bar.

Calling stop() and disconnectOutput() on the AKMicrophone node during applicationWillResignActive(). This doesn't remove the recording bar either.

I suspect that I may need to kill the entire engine (i.e. AudioKit.stop()), remove the microphone node from the chain, and rebuild and restart the engine, all within the applicationWillResignActive method. But that'll interrupt the tempo of the AKMetronome, so I'm hoping it doesn't come to that.

答:
I think you should use AudioKit for the metronome, and use a part of AudioKit called the AKMicrophoneTracker for the tuner.

http://audiokit.io/docs/Classes/AKMicrophoneTracker.html
https://github.com/AudioKit/AudioKit/blob/master/AudioKit/Common/Internals/Microphone%20Tracker/AKMicrophoneTracker.swift

AudioKit uses AVAudioEngine for its signal flow while the tracker is actually a completely separate signal flow based off of EZAudio. I believe the two can be used independently.

The way you're currently tracking the microphone probably resembles this:
http://audiokit.io/playgrounds/Analysis/Tracking%20Microphone%20Input/

You'll want to make it more like this:

```<code>let tracker = AKMicrophoneTracker()
tracker.start()

//: User Interface
import AudioKitUI

class LiveView: AKLiveViewController {

    var trackedAmplitudeSlider: AKSlider?
    var trackedFrequencySlider: AKSlider?

    override func viewDidLoad() {

        AKPlaygroundLoop(every: 0.1) {
            self.trackedAmplitudeSlider?.value = tracker.amplitude
            self.trackedFrequencySlider?.value = tracker.frequency
        }

        addTitle("Tracking With Microphone Tracker")

        trackedAmplitudeSlider = AKSlider(property: "Tracked Amplitude", range: 0 ... 0.8) { _ in
            // Do nothing, just for display
        }
        addView(trackedAmplitudeSlider)

        trackedFrequencySlider = AKSlider(property: "Tracked Frequency",
                                          range: 0 ... 2_400,
                                          format: "%0.3f Hz"
        ) { _ in
            // Do nothing, just for display
        }
        addView(trackedFrequencySlider)

    }
}
</code>```

HTH.

Body:
I think you should use AudioKit for the metronome, and use a part of AudioKit called the AKMicrophoneTracker for the tuner.

http://audiokit.io/docs/Classes/AKMicrophoneTracker.html
https://github.com/AudioKit/AudioKit/blob/master/AudioKit/Common/Internals/Microphone%20Tracker/AKMicrophoneTracker.swift

AudioKit uses AVAudioEngine for its signal flow while the tracker is actually a completely separate signal flow based off of EZAudio. I believe the two can be used independently.

The way you're currently tracking the microphone probably resembles this:
http://audiokit.io/playgrounds/Analysis/Tracking%20Microphone%20Input/

You'll want to make it more like this:

let tracker = AKMicrophoneTracker()
tracker.start()

//: User Interface
import AudioKitUI

class LiveView: AKLiveViewController {

    var trackedAmplitudeSlider: AKSlider?
    var trackedFrequencySlider: AKSlider?

    override func viewDidLoad() {

        AKPlaygroundLoop(every: 0.1) {
            self.trackedAmplitudeSlider?.value = tracker.amplitude
            self.trackedFrequencySlider?.value = tracker.frequency
        }

        addTitle("Tracking With Microphone Tracker")

        trackedAmplitudeSlider = AKSlider(property: "Tracked Amplitude", range: 0 ... 0.8) { _ in
            // Do nothing, just for display
        }
        addView(trackedAmplitudeSlider)

        trackedFrequencySlider = AKSlider(property: "Tracked Frequency",
                                          range: 0 ... 2_400,
                                          format: "%0.3f Hz"
        ) { _ in
            // Do nothing, just for display
        }
        addView(trackedFrequencySlider)

    }
}

HTH.


问:
Coalesce over Rows in MSSQL 2008,
I'm trying to determine the best approach here in MSSQL 2008.

Here is my sample data

```<code>TransDate  Id     Active
-------------------------
1/18 1pm   5      1
1/18 2pm   5      0
1/18 3pm   5      Null
1/18 4pm   5      1
1/18 5pm   5      0
1/18 6pm   5      Null
</code>```

If grouped by Id and ordered by the TransDate, I want the last Non Null Value for the Active Column, and the MAX of TransDate

```<code>SELECT MAX(TransDate) AS TransDate,
       Id,
       --LASTNonNull(Active) AS Active
</code>```

Here would be the results:

```<code>TransDate  Id  Active
---------------------
1/18 6pm   5   0
</code>```

It would be like a Coalesce but over the rows, instead of two values/columns.

There would be many other columns that would also have this similiar method applied, so I really don't want to make a seperate join for each of the columns.

Any ideas?

答:
I'd probably use a correlated sub query.

```<code>SELECT MAX(TransDate)             AS TransDate,
       Id,
       (SELECT TOP (1) Active
        FROM   T t2
        WHERE  t2.Id = t1.Id
               AND Active IS NOT NULL
        ORDER  BY TransDate DESC) AS Active
FROM   T t1
GROUP  BY Id
</code>```

A way without

```<code>SELECT
    Id,
    MAX(TransDate) AS TransDate,
    CAST(RIGHT(MAX(CONVERT(CHAR(23),TransDate,121) + CAST(Active AS CHAR(1))),1) AS BIT) AS Active,
    /*You can probably figure out a more efficient thing to
    compare than the above depending on your data. e.g.*/
    CAST(MAX(DATEDIFF(SECOND,'19500101',TransDate) * CAST(10 AS BIGINT) + Active)%10  AS BIT) AS Active2
FROM T
GROUP BY Id
</code>```

Or following the comments would cross apply work better for you?

```<code>WITH T (TransDate, Id, Active, SomeOtherColumn) AS
(
select GETDATE(), 5, 1, 'A' UNION ALL
select 1+GETDATE(), 5, 0, 'B' UNION ALL
select 2+GETDATE(), 5, null, 'C' UNION ALL
select 3+GETDATE(), 5, 1, 'D' UNION ALL
select 4+GETDATE(), 5, 0, 'E' UNION ALL
select 5+GETDATE(), 5, null,'F'

),
T1 AS
(
SELECT MAX(TransDate) AS TransDate,
       Id
FROM   T
GROUP  BY Id
)
SELECT T1.TransDate,
       Id,
       CA.Active AS Active,
       CA.SomeOtherColumn AS SomeOtherColumn
FROM   T1
CROSS APPLY (SELECT TOP (1) Active, SomeOtherColumn
        FROM   T t2
        WHERE  t2.Id = T1.Id
               AND Active IS NOT NULL
        ORDER  BY TransDate DESC) CA
</code>```

ContentLicense: CC BY-SA 2.5

Title: Coalesce over Rows in MSSQL 2008,

Body:
I'm trying to determine the best approach here in MSSQL 2008.

Here is my sample data

TransDate  Id     Active
-------------------------
1/18 1pm   5      1
1/18 2pm   5      0
1/18 3pm   5      Null
1/18 4pm   5      1
1/18 5pm   5      0
1/18 6pm   5      Null

If grouped by Id and ordered by the TransDate, I want the last Non Null Value for the Active Column, and the MAX of TransDate

SELECT MAX(TransDate) AS TransDate,
       Id,
       --LASTNonNull(Active) AS Active

Here would be the results:

TransDate  Id  Active
---------------------
1/18 6pm   5   0

It would be like a Coalesce but over the rows, instead of two values/columns.

There would be many other columns that would also have this similiar method applied, so I really don't want to make a seperate join for each of the columns.

Any ideas?

Body:
I'd probably use a correlated sub query.

SELECT MAX(TransDate)             AS TransDate,
       Id,
       (SELECT TOP (1) Active
        FROM   T t2
        WHERE  t2.Id = t1.Id
               AND Active IS NOT NULL
        ORDER  BY TransDate DESC) AS Active
FROM   T t1
GROUP  BY Id

A way without

SELECT
    Id,
    MAX(TransDate) AS TransDate,
    CAST(RIGHT(MAX(CONVERT(CHAR(23),TransDate,121) + CAST(Active AS CHAR(1))),1) AS BIT) AS Active,
    /*You can probably figure out a more efficient thing to
    compare than the above depending on your data. e.g.*/
    CAST(MAX(DATEDIFF(SECOND,'19500101',TransDate) * CAST(10 AS BIGINT) + Active)%10  AS BIT) AS Active2
FROM T
GROUP BY Id

Or following the comments would cross apply work better for you?

WITH T (TransDate, Id, Active, SomeOtherColumn) AS
(
select GETDATE(), 5, 1, 'A' UNION ALL
select 1+GETDATE(), 5, 0, 'B' UNION ALL
select 2+GETDATE(), 5, null, 'C' UNION ALL
select 3+GETDATE(), 5, 1, 'D' UNION ALL
select 4+GETDATE(), 5, 0, 'E' UNION ALL
select 5+GETDATE(), 5, null,'F'

),
T1 AS
(
SELECT MAX(TransDate) AS TransDate,
       Id
FROM   T
GROUP  BY Id
)
SELECT T1.TransDate,
       Id,
       CA.Active AS Active,
       CA.SomeOtherColumn AS SomeOtherColumn
FROM   T1
CROSS APPLY (SELECT TOP (1) Active, SomeOtherColumn
        FROM   T t2
        WHERE  t2.Id = T1.Id
               AND Active IS NOT NULL
        ORDER  BY TransDate DESC) CA


问:
Django MonitorField() not working with Foreign Key if when condition is added
Greeting, as mention in the question, my MonitorField stop updating the date when I add a when condition in it, below is my code :

```<code>class A(models.Model):

    name = models.CharField(max_length=50, unique=True)

    def __str__(self):
        return self.name

class B(models.Model):
 status = models.ForeignKey(A, on_delete=models.CASCADE, default=4, null=True)
 monitor = fields.MonitorField(monitor='status', when=[1])
</code>```

答:
You missed comma between monitor and when field

```<code>monitor = fields.MonitorField(monitor='status', when=[1])
</code>```

Check this issue of django-model-utils on github if above doesnt work LINK

Body:
Greeting, as mention in the question, my MonitorField stop updating the date when I add a when condition in it, below is my code :

class A(models.Model):

    name = models.CharField(max_length=50, unique=True)

    def __str__(self):
        return self.name

class B(models.Model):
 status = models.ForeignKey(A, on_delete=models.CASCADE, default=4, null=True)
 monitor = fields.MonitorField(monitor='status', when=[1])

Body:
You missed comma between monitor and when field

monitor = fields.MonitorField(monitor='status', when=[1])

Check this issue of django-model-utils on github if above doesnt work LINK


问:
MySQL not launching: /data/user.local.err: Permission denied
I have just installed MySQL on macOS 10.6, and it will not launch.
When I launch it the traditional way, I get the following:

```<code>Starting MySQL........
</code>```

ERROR! The server quit without updating PID file
(/usr/local/mysql/data/user.local.pid).

I followed some other instructions online and deleted my custom my.cnf
file and executed this command:

```<code>sudo chown -R _mysql:_mysql /usr/local/mysql/
</code>```

Then tried to launch it in safe mode, to which I received the following list of errors:

```<code>160414 12:48:18 mysqld_safe Logging to '/usr/local/mysql/data/user.local.err'.
touch: /usr/local/mysql/data/user.local.err: Permission denied
160414 12:48:18 mysqld_safe Starting mysqld daemon with databases from /usr/local/mysql/data
/usr/local/mysql/bin/mysqld_safe: line 129: /usr/local/mysql/data/user.local.err: Permission denied
/usr/local/mysql/bin/mysqld_safe: line 166: /usr/local/mysql/data/user.local.err: Permission denied
160414 12:48:18 mysqld_safe mysqld from pid file /usr/local/mysql/data/user.local.pid ended
/usr/local/mysql/bin/mysqld_safe: line 129: /usr/local/mysql/data/user.local.err: Permission denied
</code>```

How can I get it working?

答:
I know its late, thought helpful for someone in future.

This question already have the answer here:
MySQL server start issues on Mavericks.

The following answer is referenced from the above question

Reason:

Probably the folder /usr/local/mysql/ don't have the write permissions for the user _mysql

Try changing the folder permission by using the following commands

sudo chown -R _mysql:admin /usr/local/mysql

sudo chmod -R u+rwX,g+rwX,o-rwx /usr/local/mysql

Body:
I have just installed MySQL on macOS 10.6, and it will not launch.
When I launch it the traditional way, I get the following:

Starting MySQL........

ERROR! The server quit without updating PID file
(/usr/local/mysql/data/user.local.pid).

I followed some other instructions online and deleted my custom my.cnf
file and executed this command:

sudo chown -R _mysql:_mysql /usr/local/mysql/

Then tried to launch it in safe mode, to which I received the following list of errors:

160414 12:48:18 mysqld_safe Logging to '/usr/local/mysql/data/user.local.err'.
touch: /usr/local/mysql/data/user.local.err: Permission denied
160414 12:48:18 mysqld_safe Starting mysqld daemon with databases from /usr/local/mysql/data
/usr/local/mysql/bin/mysqld_safe: line 129: /usr/local/mysql/data/user.local.err: Permission denied
/usr/local/mysql/bin/mysqld_safe: line 166: /usr/local/mysql/data/user.local.err: Permission denied
160414 12:48:18 mysqld_safe mysqld from pid file /usr/local/mysql/data/user.local.pid ended
/usr/local/mysql/bin/mysqld_safe: line 129: /usr/local/mysql/data/user.local.err: Permission denied

How can I get it working?


问:
difference between stack segment and uninitialized data segment
I was trying to get a hand over the memory allocation in c.

According to the following link, the stack and the uninitialized data segment are different and the uninitialized data of the local function goes to the uninitialized data segment.

If that is the case then what is stored in the stack segment in case of a code with uninitialized local variables? Is it empty?

答:
the uninitialized data of the local function goes to the uninitialized data segment.

Well, that is not entirely true.

Read carefully, (from the same link, emphasis mine)

[...] uninitialized data starts at the end of the data segment and contains all global variables and static variables that are initialized to zero or do not have explicit initialization in source code. [...]

So, the automatic storage variables still resides in stack segment, irrespective of the fact whether they are initialized or not.

That said, a word of caution, this is "A typical memory representation", not universal. C standard does not mandate to have a stack segment (or any other), for the matter.


问:
Azure IoT Hub - How to use Table Storage in IoT Hub?
First of all, sorry for my english skill.

I'm a high school student from South Korea who's doing project with Azure IoT Hub.

I am working on a project where a raspberry pi device is sending values to an Azure IoT Hub. I would like to save this data in Azure Table Storage as this data will be used by some other services (Azure WebApp for example).

So I tried to save raspberry pi values in Azure Table Storage.
But when I add endpoints of IoT Hub, I just can use only blob storage container

of course i still don't understand about iot hub
please don't look so bad.

In a nutshell

I want to send raspberry pi values to Azure Table Storage and not Blob Storage however only option available to me is Blob Storage when I am setting endpoints for Azure IoT Hub.

How to send values to Table Storage via Azure IoT Hub.

by any chance, my logic for Azure is completely wrong?

答:
IoT Hub natively supports routing messages to Azure storage as blobs. Refer Save IoT hub messages that contain sensor data to your Azure blob storage.
There does, however, seem to be a typo in the doc where it lists ‘table storage’ instead of 'blob storage'. We’ll get those typos corrected.</p>


问:
Fatal error: Can't open and lock privilege tables: Table 'mysql.host' doesn't exist
I am on a server that has  afresh install on RHEL 5.  I was able to install Apache and PHP just fine., but I am having serious trouble with my MySQL installation.  I tried the following:

```<code>yum install mysql-server mysql
</code>```

And didn't get any errors or conflicts.  Then I tried to start mysql with the following commands:

```<code>chkconfig --levels 235 mysqld on
service mysqld start
</code>```

And get Timeout error occurred trying to start MySQL Daemon.

I checked my logs and see this error:

```<code>[ERROR] Fatal error: Can't open and lock privilege tables: Table 'mysql.host' doesn't exist
</code>```

I'm not sure where to go from here.

For reference I am using RHEL 5 and installed the latest versions of PHP 5 and Apache.

答:
I got similar error on overlayfs (overlay2) that is the default on Docker for Mac.
The error happens when starting mysql on the image, after creating a image with mysql.

```<code>2017-11-15T06:44:22.141481Z 0 [ERROR] Fatal error: Can't open and lock privilege tables: Table storage engine for 'user' doesn't have this option
</code>```

Switching to "aufs" solved the issue.
(On Docker for Mac, the "daemon.json" can be edited by choosing "Preferences..." menu, and selecting "Daemon" tab, and selecting "Advanced" tab.)

/etc/docker/daemon.json :

```<code>{
  "storage-driver" : "aufs",
  "debug" : true,
  "experimental" : true
}
</code>```

Ref:

https://github.com/moby/moby/issues/35503

https://qiita.com/Hige-Moja/items/7b1208f16997e2aa9028

Body:
I am on a server that has  afresh install on RHEL 5.  I was able to install Apache and PHP just fine., but I am having serious trouble with my MySQL installation.  I tried the following:

yum install mysql-server mysql

And didn't get any errors or conflicts.  Then I tried to start mysql with the following commands:

chkconfig --levels 235 mysqld on
service mysqld start

And get Timeout error occurred trying to start MySQL Daemon.

I checked my logs and see this error:

[ERROR] Fatal error: Can't open and lock privilege tables: Table 'mysql.host' doesn't exist

I'm not sure where to go from here.

For reference I am using RHEL 5 and installed the latest versions of PHP 5 and Apache.

Body:
I got similar error on overlayfs (overlay2) that is the default on Docker for Mac.
The error happens when starting mysql on the image, after creating a image with mysql.

2017-11-15T06:44:22.141481Z 0 [ERROR] Fatal error: Can't open and lock privilege tables: Table storage engine for 'user' doesn't have this option

Switching to "aufs" solved the issue.
(On Docker for Mac, the "daemon.json" can be edited by choosing "Preferences..." menu, and selecting "Daemon" tab, and selecting "Advanced" tab.)

/etc/docker/daemon.json :

{
  "storage-driver" : "aufs",
  "debug" : true,
  "experimental" : true
}

Ref:

https://github.com/moby/moby/issues/35503

https://qiita.com/Hige-Moja/items/7b1208f16997e2aa9028


问:
Pip not working in my system,
I am getting the following error while using pip command, in anaconda.

```<code>C:\Users\name>pip install xmlschema
Traceback (most recent call last):
  File "C:\ANACONDA2\Scripts\pip-script.py", line 9, in <module>
    load_entry_point('pip==9.0.1', 'console_scripts', 'pip')()
  File "C:\ANACONDA2\lib\site-packages\setuptools-18.4-py2.7.egg\pkg_resources\__init__.py", line 558, in load_entry_point
  File "C:\ANACONDA2\lib\site-packages\setuptools-18.4-py2.7.egg\pkg_resources\__init__.py", line 2682, in load_entry_point
  File "C:\ANACONDA2\lib\site-packages\setuptools-18.4-py2.7.egg\pkg_resources\__init__.py", line 2355, in load
  File "C:\ANACONDA2\lib\site-packages\setuptools-18.4-py2.7.egg\pkg_resources\__init__.py", line 2361, in resolve
  File "c:\anaconda2\lib\site-packages\pip\__init__.py", line 28, in <module>
    from pip.vcs import git, mercurial, subversion, bazaar  # noqa
  File "c:\anaconda2\lib\site-packages\pip\vcs\subversion.py", line 9, in <module>
    from pip.index import Link
  File "c:\anaconda2\lib\site-packages\pip\index.py", line 33, in <module>
    from pip._vendor import html5lib, requests, six
  File "c:\anaconda2\lib\site-packages\pip\_vendor\html5lib\__init__.py", line 19, in <module>
    from .serializer import serialize
  File "c:\anaconda2\lib\site-packages\pip\_vendor\html5lib\serializer\__init__.py", line 5, in <module>
    from .htmlserializer import HTMLSerializer
  File "c:\anaconda2\lib\site-packages\pip\_vendor\html5lib\serializer\htmlserializer.py", line 11, in <module>
    from .. import utils
ImportError: cannot import name utils
</code>```

I am having utils package, but still throwing ImportError: cannot import name utils

答: On windows there is no sudo command. You have to run the command line as administrator and run the pip commands from above without sudo. </p>

Title: Pip not working in my system,

Body:
I am getting the following error while using pip command, in anaconda.

C:\Users\name>pip install xmlschema
Traceback (most recent call last):
  File "C:\ANACONDA2\Scripts\pip-script.py", line 9, in <module>
    load_entry_point('pip==9.0.1', 'console_scripts', 'pip')()
  File "C:\ANACONDA2\lib\site-packages\setuptools-18.4-py2.7.egg\pkg_resources\__init__.py", line 558, in load_entry_point
  File "C:\ANACONDA2\lib\site-packages\setuptools-18.4-py2.7.egg\pkg_resources\__init__.py", line 2682, in load_entry_point
  File "C:\ANACONDA2\lib\site-packages\setuptools-18.4-py2.7.egg\pkg_resources\__init__.py", line 2355, in load
  File "C:\ANACONDA2\lib\site-packages\setuptools-18.4-py2.7.egg\pkg_resources\__init__.py", line 2361, in resolve
  File "c:\anaconda2\lib\site-packages\pip\__init__.py", line 28, in <module>
    from pip.vcs import git, mercurial, subversion, bazaar  # noqa
  File "c:\anaconda2\lib\site-packages\pip\vcs\subversion.py", line 9, in <module>
    from pip.index import Link
  File "c:\anaconda2\lib\site-packages\pip\index.py", line 33, in <module>
    from pip._vendor import html5lib, requests, six
  File "c:\anaconda2\lib\site-packages\pip\_vendor\html5lib\__init__.py", line 19, in <module>
    from .serializer import serialize
  File "c:\anaconda2\lib\site-packages\pip\_vendor\html5lib\serializer\__init__.py", line 5, in <module>
    from .htmlserializer import HTMLSerializer
  File "c:\anaconda2\lib\site-packages\pip\_vendor\html5lib\serializer\htmlserializer.py", line 11, in <module>
    from .. import utils
ImportError: cannot import name utils

I am having utils package, but still throwing ImportError: cannot import name utils


问:
How can I make design as shown in the attached image?

I want to design a screen like this. For displaying the grid items, I am using recycle view. But my concern is how to apply pagination and implement slide for next section of items when user swipe.

In case swipe is not possible, at least on click of the dots below the layout.

答:
First Step - Use ViewPager

Second Step - Inside Fragment you can use RecyclerView with GridLayout

Third - Finally you can use CirlcePageIndicator

What you are looking is actually you can found in this block GridView with Viewpager

You can also use RecyclerView instead of GridView


问:
How can I access the raw documents from the Brown corpus?
For all other NLTK corpora, calling corpus.raw() yields the original text from the files.
For example:

```<code>>>> from nltk.corpus import webtext
>>> webtext.raw()[:10]
'Cookie Man'
</code>```

However, when calling brown.raw() you get tagged text.

```<code>>>> from nltk.corpus import brown
>>> brown.raw()[:10]
'\n\n\tThe/at '
</code>```

I've read all the documentation I can find but can't seem to find an obvious explanation or way to get the un-tagged version. Is there a reason this corpus is tagged and the others aren't?

答:
TL;DR

```<code>import nltk
nltk.download('brown')
nltk.download('nonbreaking_prefixes')
nltk.download('perluniprops')

from nltk.corpus import brown
from nltk.tokenize.moses import MosesDetokenizer

mdetok = MosesDetokenizer()

brown_natural = [mdetok.detokenize(' '.join(sent).replace('``', '"').replace("''", '"').replace('`', "'").split(), return_str=True)  for sent in brown.sents()]

for sent in brown_natural:
    print(sent)
</code>```

In Long

It's because the "raw" version of the Brown corpus is tokenized and tagged i.e. the corpus comes tagged an that's the original form of the corpus =)

You can look at the individual files in your nltk_data directory:

```<code>$ head -n10 nltk_data/corpora/brown/ca01

    The/at Fulton/np-tl County/nn-tl Grand/jj-tl Jury/nn-tl said/vbd Friday/nr an/at investigation/nn of/in Atlanta's/np$ recent/jj primary/nn election/nn produced/vbd ``/`` no/at evidence/nn ''/'' that/cs any/dti irregularities/nns took/vbd place/nn ./.

    The/at jury/nn further/rbr said/vbd in/in term-end/nn presentments/nns that/cs the/at City/nn-tl Executive/jj-tl Committee/nn-tl ,/, which/wdt had/hvd over-all/jj charge/nn of/in the/at election/nn ,/, ``/`` deserves/vbz the/at praise/nn and/cc thanks/nns of/in the/at City/nn-tl of/in-tl Atlanta/np-tl ''/'' for/in the/at manner/nn in/in which/wdt the/at election/nn was/bedz conducted/vbn ./.

    The/at September-October/np term/nn jury/nn had/hvd been/ben charged/vbn by/in Fulton/np-tl Superior/jj-tl Court/nn-tl Judge/nn-tl Durwood/np Pye/np to/to investigate/vb reports/nns of/in possible/jj ``/`` irregularities/nns ''/'' in/in the/at hard-fought/jj primary/nn which/wdt was/bedz won/vbn by/in Mayor-nominate/nn-tl Ivan/np Allen/np Jr./np ./.
</code>```

If you want the words from the corpus, you can use brown.words(), e.g.

```<code>>>> from nltk.corpus import brown

>>> brown.words()
[u'The', u'Fulton', u'County', u'Grand', u'Jury', ...]

>>> ' '.join(brown.words()[:30])
u"The Fulton County Grand Jury said Friday an investigation of Atlanta's recent primary election produced `` no evidence '' that any irregularities took place . The jury further said in"
</code>```

If you want to get words from a specific file:

```<code>>>> brown.fileids()[:10] # The first 10 fileids from brown.
[u'ca01', u'ca02', u'ca03', u'ca04', u'ca05', u'ca06', u'ca07', u'ca08', u'ca09', u'ca10']

>>> ' '.join(brown.words('ca01')[:30]) # First 30 words from the 'ca01' file.
u"The Fulton County Grand Jury said Friday an investigation of Atlanta's recent primary election produced `` no evidence '' that any irregularities took place . The jury further said in"
</code>```

And the sentences from a specific file:

```<code>>>> brown.sents('ca01')
[[u'The', u'Fulton', u'County', u'Grand', u'Jury', u'said', u'Friday', u'an', u'investigation', u'of', u"Atlanta's", u'recent', u'primary', u'election', u'produced', u'``', u'no', u'evidence', u"''", u'that', u'any', u'irregularities', u'took', u'place', u'.'], [u'The', u'jury', u'further', u'said', u'in', u'term-end', u'presentments', u'that', u'the', u'City', u'Executive', u'Committee', u',', u'which', u'had', u'over-all', u'charge', u'of', u'the', u'election', u',', u'``', u'deserves', u'the', u'praise', u'and', u'thanks', u'of', u'the', u'City', u'of', u'Atlanta', u"''", u'for', u'the', u'manner', u'in', u'which', u'the', u'election', u'was', u'conducted', u'.'], ...]
</code>```

To print out the individual sentences:

```<code>>>> for sent in brown.sents('ca01')[:5]: # First 5 sentences.
...     print(' '.join(sent))
...
The Fulton County Grand Jury said Friday an investigation of Atlanta's recent primary election produced `` no evidence '' that any irregularities took place .
The jury further said in term-end presentments that the City Executive Committee , which had over-all charge of the election , `` deserves the praise and thanks of the City of Atlanta '' for the manner in which the election was conducted .
The September-October term jury had been charged by Fulton Superior Court Judge Durwood Pye to investigate reports of possible `` irregularities '' in the hard-fought primary which was won by Mayor-nominate Ivan Allen Jr. .
`` Only a relative handful of such reports was received '' , the jury said , `` considering the widespread interest in the election , the number of voters and the size of this city '' .
The jury said it did find that many of Georgia's registration and election laws `` are outmoded or inadequate and often ambiguous '' .
</code>```

Trying to detokenize the tokenized corpus rather messy and may or may not work but you can try the MosesDetokenizer:

First download the data needed by the MosesDetokenizer:

```<code>>>> import nltk
>>> nltk.download('perluniprops')
[nltk_data] Downloading package perluniprops to
[nltk_data]     /home/ltan/nltk_data...
[nltk_data]   Unzipping misc/perluniprops.zip.
True
>>> nltk.download('nonbreaking_prefixes')
[nltk_data] Downloading package nonbreaking_prefixes to
[nltk_data]     /home/ltan/nltk_data...
[nltk_data]   Package nonbreaking_prefixes is already up-to-date!
True
</code>```

Then initialize the MosesDetokenizer:

```<code>>>> from nltk.tokenize.moses import MosesDetokenizer
>>> mdetok = MosesDetokenizer()
</code>```

And use the MosesDetokenizer.detokenize():

```<code>>>> for sent in brown.sents('ca01')[:5]: # First 5 sentences.
...     # Join the words in sentences and convert the `` -> "
...     # also convert '' -> " and ` -> '
...     munged_sentence = ' '.join(sent).replace('``', '"').replace("''", '"').replace('`', "'")
...     print(mdetok.detokenize(munged_sentence.split(), return_str=True)) # MosesDetokenizer expects a list of strings as input.
...
The Fulton County Grand Jury said Friday an investigation of Atlanta's recent primary election produced "no evidence" that any irregularities took place.
The jury further said in term-end presentments that the City Executive Committee, which had over-all charge of the election, "deserves the praise and thanks of the City of Atlanta" for the manner in which the election was conducted.
The September-October term jury had been charged by Fulton Superior Court Judge Durwood Pye to investigate reports of possible "irregularities" in the hard-fought primary which was won by Mayor-nominate Ivan Allen Jr..
"Only a relative handful of such reports was received", the jury said, "considering the widespread interest in the election, the number of voters and the size of this city".
The jury said it did find that many of Georgia's registration and election laws "are outmoded or inadequate and often ambiguous".
</code>```

To convert every sentence in brown into natural reading text:

```<code>from nltk.tokenize.moses import MosesDetokenizer
mdetok = MosesDetokenizer()
brown_natural = [mdetok.detokenize(' '.join(sent).replace('``', '"').replace("''", '"').replace('`', "'").split(), return_str=True)  for sent in brown.sents()]
</code>```

[out]:

```<code>>>> for sent in brown_natural:
...     print(sent)
...     break
...
The Fulton County Grand Jury said Friday an investigation of Atlanta's recent primary election produced "no evidence" that any irregularities took place.
</code>```

Body:
For all other NLTK corpora, calling corpus.raw() yields the original text from the files.
For example:

>>> from nltk.corpus import webtext
>>> webtext.raw()[:10]
'Cookie Man'

However, when calling brown.raw() you get tagged text.

>>> from nltk.corpus import brown
>>> brown.raw()[:10]
'\n\n\tThe/at '

I've read all the documentation I can find but can't seem to find an obvious explanation or way to get the un-tagged version. Is there a reason this corpus is tagged and the others aren't?

Body:
TL;DR

import nltk
nltk.download('brown')
nltk.download('nonbreaking_prefixes')
nltk.download('perluniprops')

from nltk.corpus import brown
from nltk.tokenize.moses import MosesDetokenizer

mdetok = MosesDetokenizer()

brown_natural = [mdetok.detokenize(' '.join(sent).replace('``', '"').replace("''", '"').replace('`', "'").split(), return_str=True)  for sent in brown.sents()]

for sent in brown_natural:
    print(sent)

In Long

It's because the "raw" version of the Brown corpus is tokenized and tagged i.e. the corpus comes tagged an that's the original form of the corpus =)

You can look at the individual files in your nltk_data directory:

$ head -n10 nltk_data/corpora/brown/ca01

    The/at Fulton/np-tl County/nn-tl Grand/jj-tl Jury/nn-tl said/vbd Friday/nr an/at investigation/nn of/in Atlanta's/np$ recent/jj primary/nn election/nn produced/vbd ``/`` no/at evidence/nn ''/'' that/cs any/dti irregularities/nns took/vbd place/nn ./.

    The/at jury/nn further/rbr said/vbd in/in term-end/nn presentments/nns that/cs the/at City/nn-tl Executive/jj-tl Committee/nn-tl ,/, which/wdt had/hvd over-all/jj charge/nn of/in the/at election/nn ,/, ``/`` deserves/vbz the/at praise/nn and/cc thanks/nns of/in the/at City/nn-tl of/in-tl Atlanta/np-tl ''/'' for/in the/at manner/nn in/in which/wdt the/at election/nn was/bedz conducted/vbn ./.

    The/at September-October/np term/nn jury/nn had/hvd been/ben charged/vbn by/in Fulton/np-tl Superior/jj-tl Court/nn-tl Judge/nn-tl Durwood/np Pye/np to/to investigate/vb reports/nns of/in possible/jj ``/`` irregularities/nns ''/'' in/in the/at hard-fought/jj primary/nn which/wdt was/bedz won/vbn by/in Mayor-nominate/nn-tl Ivan/np Allen/np Jr./np ./.

If you want the words from the corpus, you can use brown.words(), e.g.

>>> from nltk.corpus import brown

>>> brown.words()
[u'The', u'Fulton', u'County', u'Grand', u'Jury', ...]

>>> ' '.join(brown.words()[:30])
u"The Fulton County Grand Jury said Friday an investigation of Atlanta's recent primary election produced `` no evidence '' that any irregularities took place . The jury further said in"

If you want to get words from a specific file:

>>> brown.fileids()[:10] # The first 10 fileids from brown.
[u'ca01', u'ca02', u'ca03', u'ca04', u'ca05', u'ca06', u'ca07', u'ca08', u'ca09', u'ca10']

>>> ' '.join(brown.words('ca01')[:30]) # First 30 words from the 'ca01' file.
u"The Fulton County Grand Jury said Friday an investigation of Atlanta's recent primary election produced `` no evidence '' that any irregularities took place . The jury further said in"

And the sentences from a specific file:

>>> brown.sents('ca01')
[[u'The', u'Fulton', u'County', u'Grand', u'Jury', u'said', u'Friday', u'an', u'investigation', u'of', u"Atlanta's", u'recent', u'primary', u'election', u'produced', u'``', u'no', u'evidence', u"''", u'that', u'any', u'irregularities', u'took', u'place', u'.'], [u'The', u'jury', u'further', u'said', u'in', u'term-end', u'presentments', u'that', u'the', u'City', u'Executive', u'Committee', u',', u'which', u'had', u'over-all', u'charge', u'of', u'the', u'election', u',', u'``', u'deserves', u'the', u'praise', u'and', u'thanks', u'of', u'the', u'City', u'of', u'Atlanta', u"''", u'for', u'the', u'manner', u'in', u'which', u'the', u'election', u'was', u'conducted', u'.'], ...]

To print out the individual sentences:

>>> for sent in brown.sents('ca01')[:5]: # First 5 sentences.
...     print(' '.join(sent))
...
The Fulton County Grand Jury said Friday an investigation of Atlanta's recent primary election produced `` no evidence '' that any irregularities took place .
The jury further said in term-end presentments that the City Executive Committee , which had over-all charge of the election , `` deserves the praise and thanks of the City of Atlanta '' for the manner in which the election was conducted .
The September-October term jury had been charged by Fulton Superior Court Judge Durwood Pye to investigate reports of possible `` irregularities '' in the hard-fought primary which was won by Mayor-nominate Ivan Allen Jr. .
`` Only a relative handful of such reports was received '' , the jury said , `` considering the widespread interest in the election , the number of voters and the size of this city '' .
The jury said it did find that many of Georgia's registration and election laws `` are outmoded or inadequate and often ambiguous '' .

Trying to detokenize the tokenized corpus rather messy and may or may not work but you can try the MosesDetokenizer:

First download the data needed by the MosesDetokenizer:

>>> import nltk
>>> nltk.download('perluniprops')
[nltk_data] Downloading package perluniprops to
[nltk_data]     /home/ltan/nltk_data...
[nltk_data]   Unzipping misc/perluniprops.zip.
True
>>> nltk.download('nonbreaking_prefixes')
[nltk_data] Downloading package nonbreaking_prefixes to
[nltk_data]     /home/ltan/nltk_data...
[nltk_data]   Package nonbreaking_prefixes is already up-to-date!
True

Then initialize the MosesDetokenizer:

>>> from nltk.tokenize.moses import MosesDetokenizer
>>> mdetok = MosesDetokenizer()

And use the MosesDetokenizer.detokenize():

>>> for sent in brown.sents('ca01')[:5]: # First 5 sentences.
...     # Join the words in sentences and convert the `` -> "
...     # also convert '' -> " and ` -> '
...     munged_sentence = ' '.join(sent).replace('``', '"').replace("''", '"').replace('`', "'")
...     print(mdetok.detokenize(munged_sentence.split(), return_str=True)) # MosesDetokenizer expects a list of strings as input.
...
The Fulton County Grand Jury said Friday an investigation of Atlanta's recent primary election produced "no evidence" that any irregularities took place.
The jury further said in term-end presentments that the City Executive Committee, which had over-all charge of the election, "deserves the praise and thanks of the City of Atlanta" for the manner in which the election was conducted.
The September-October term jury had been charged by Fulton Superior Court Judge Durwood Pye to investigate reports of possible "irregularities" in the hard-fought primary which was won by Mayor-nominate Ivan Allen Jr..
"Only a relative handful of such reports was received", the jury said, "considering the widespread interest in the election, the number of voters and the size of this city".
The jury said it did find that many of Georgia's registration and election laws "are outmoded or inadequate and often ambiguous".

To convert every sentence in brown into natural reading text:

from nltk.tokenize.moses import MosesDetokenizer
mdetok = MosesDetokenizer()
brown_natural = [mdetok.detokenize(' '.join(sent).replace('``', '"').replace("''", '"').replace('`', "'").split(), return_str=True)  for sent in brown.sents()]

[out]:

>>> for sent in brown_natural:
...     print(sent)
...     break
...
The Fulton County Grand Jury said Friday an investigation of Atlanta's recent primary election produced "no evidence" that any irregularities took place.


问:
Adding days to date jquery or JS
I have a select to add days from an input on 'dd/mm/yy' format to show the result in another input, I tried to do this but this is not working.</p>

```<code><input type="text" id="startdate" value="15/11/17">

<select name="Select1" id="days">
<option value="1">1 day</option>
<option value="2">2 days</option>
<option value="3">3 days</option>
</select>

<input type="text" id="fdate" value="">

$( "#days" ).change(function() {
var sta = $('#startdate').val()
var sel = parseInt($(this).val())
$('#fdate').val(sta+sel )
});
</code>```

答:
The input "#startdate" has text type, if you sum an "integer" the result it's not your target.

You need use a type date in the first input, convert his value to Date object and add a number of day with the correct function.

Here you have more info about Date object's.

Title: Adding days to date jquery or JS

Body:
I have a select to add days from an input on 'dd/mm/yy' format to show the result in another input, I tried to do this but this is not working.

<input type="text" id="startdate" value="15/11/17">

<select name="Select1" id="days">
<option value="1">1 day</option>
<option value="2">2 days</option>
<option value="3">3 days</option>
</select>

<input type="text" id="fdate" value="">

$( "#days" ).change(function() {
var sta = $('#startdate').val()
var sel = parseInt($(this).val())
$('#fdate').val(sta+sel )
});


问:
mysql: design practices
I have tables setup as such:

A message is sent out to a group of users.

This message is put in the parent_message table

This table contains id | sender_id | date

each message that is sent in that group is put in the child_message table

this table contains id | parent_id | message | date_sent

when a reply is received it is put into the reply_message table

this table contains id | child_id | message | date_received.

Now I have a few questions about this setup.

1) Every time the page is loaded I need to show how many child messages each parent message has.

Would you add a column to the parent_message table called child_count or work it out in your query.

why, why not?

Example query

```<code>select *,
count(select parent_id from child_message c where c.parent_id = p.parent_id ) child_count
from parent_message;
</code>```

2) If the user chooses they can view all reply messages to a parent message.

would you add the parent_id to the reply reply_message table or work it out in your query?

Why, why not?

Example query

```<code>select * from reply_message
where child_id in(select id from child_message where parent_id = '66')
</code>```

答:
I'd say it very much depends on the amount of messages. If you have like a million messages in the system, a join to child_message can become very expensive. In that case adding a child_count to the parent table can be beneficial for your performance. Same goes for your second use case. Of course that is some de-normalization of your data, so if your system allows for reshaping topics and replies (like splitting a topic) you have to do additional bookkeeping in that case.

Another approach would be creating index tables, which hold the information you need and update them offline in an asynchronous way, if you don't need the information to be 100% accurate all the time e.g.

table message_counts (parent_id, child_count)

And then schedule updates on these when a new message is added to the system, e.g. by using a trigger.

So bottom line, unless you encounter performance issues, keep your tables normalized, just like they are. When you expect millions of messages and replies, some de-normalization can help speed up things. Index tables can help creating aggregated statistics offline, unless you need them to be accurate and up-to-date.

Title: mysql: design practices

Body:
I have tables setup as such:

A message is sent out to a group of users.

This message is put in the parent_message table

This table contains id | sender_id | date

each message that is sent in that group is put in the child_message table

this table contains id | parent_id | message | date_sent

when a reply is received it is put into the reply_message table

this table contains id | child_id | message | date_received.

Now I have a few questions about this setup.

1) Every time the page is loaded I need to show how many child messages each parent message has.

Would you add a column to the parent_message table called child_count or work it out in your query.

why, why not?

Example query

select *,
count(select parent_id from child_message c where c.parent_id = p.parent_id ) child_count
from parent_message;

2) If the user chooses they can view all reply messages to a parent message.

would you add the parent_id to the reply reply_message table or work it out in your query?

Why, why not?

Example query

select * from reply_message
where child_id in(select id from child_message where parent_id = '66')


问:
Appending php array values with string doesn't give expected output
I have database query which returns an array of string values. I want them to be comma separated and appended to another string.

```<code>$sql1 = "select location.name as name from location,destination where destination.name='".$destination."' AND location.destination_id=destination.destination_id";
$result1 = $conn->query($sql1);
if ($result1->num_rows > 0) {
  $insert = "";
    while($locations = $result1->fetch_assoc()) {
  foreach ($locations as $location) {
$insert .= $location['name'] . ",";
      }
   }

$insert = rtrim($insert, ",");

 }

$sql2 = "select destination.destination_description as description from destination where destination.name='".$destination."'";
$result2 = $conn->query($sql2);
if ($result2->num_rows > 0) {
    while($row = $result2->fetch_assoc()) {
    $response->speech = $destination." is the ".$row["description"].". ".$insert . "are some of the places you can try.";
   echo json_encode($response);
  }
}
</code>```

This $insert array doesn't give the expected result. It gives just "N".

答: I think you should look at explode function that might help you  Explode function in php</p>

Body:
I have database query which returns an array of string values. I want them to be comma separated and appended to another string.

$sql1 = "select location.name as name from location,destination where destination.name='".$destination."' AND location.destination_id=destination.destination_id";
$result1 = $conn->query($sql1);
if ($result1->num_rows > 0) {
  $insert = "";
    while($locations = $result1->fetch_assoc()) {
  foreach ($locations as $location) {
$insert .= $location['name'] . ",";
      }
   }

$insert = rtrim($insert, ",");

 }

$sql2 = "select destination.destination_description as description from destination where destination.name='".$destination."'";
$result2 = $conn->query($sql2);
if ($result2->num_rows > 0) {
    while($row = $result2->fetch_assoc()) {
    $response->speech = $destination." is the ".$row["description"].". ".$insert . "are some of the places you can try.";
   echo json_encode($response);
  }
}

This $insert array doesn't give the expected result. It gives just "N".


问:
Django: make_password outputs different password than django.auth
I am trying to implement a user password history, so that the user can not use the same passwords twice when updating his password.
I am using the Django auth module for this.

To achieve that I just save the new passwords the user creates in an additional sql table my_userpasswordhistory.

After that, I created a new PasswordValidator to check the new password against the old passwords.
They way I intend to do that, is to take all old passwords from the user in the database, split off the salt and run make_password(newpassword, salt).

See the following code:

```<code>    pass_list = UserPasswordHistory.objects.all().filter(user=user)

    for old_pass in pass_list:
        #split password so we get the hash and the salt
        split_pass = old_pass.password.split('$')
        salt = split_pass[2]
        pw   = split_pass[-1]
        if make_password(password, salt) == old_pass.password:
            raise ValidationError(
                _('Your new Password needs to be different from your old one!'),
                code='password_identic'
            )
</code>```

Problem

The problem I am having is that somehow, the password generated by Django in the admin backend (via interface) is different from the password I create with using make_password().

The value in the database for my password is:

select password from my_userpasswordhistory;
pbkdf2_sha256$36000$trlHVdErn23Z$BAxX9p3o54QGovIWluP3dM7q73HQNZy9VuYOA6rv268=

However, using the salt trlHVdErn23Z on the an identic raw password, I get:

pbkdf2_sha256$36000$trlHVdErn23Z$6WbA/0fUvDi82GjN7lqjdMoaDiaoojGY3A913CGuFBY=

Also, running make_password() multiple times will always output the same (second) password hash.

I can not figure out if Django uses some additional randomizer whilst creating the password in the admin panel, if I found a bug, or more likely, I missed something.

Thanks a lot in advance.

答:
You should use check_password instead of make_password.

From the django documentation

check_password(password, encoded)

If you’d like to manually authenticate a user by comparing a plain-text password to the hashed password in the database, use the convenience function check_password(). It takes two arguments: the plain-text password to check, and the full value of a user’s password field in the database to check against, and returns True if they match, False otherwise.

Body:
I am trying to implement a user password history, so that the user can not use the same passwords twice when updating his password.
I am using the Django auth module for this.

To achieve that I just save the new passwords the user creates in an additional sql table my_userpasswordhistory.

After that, I created a new PasswordValidator to check the new password against the old passwords.
They way I intend to do that, is to take all old passwords from the user in the database, split off the salt and run make_password(newpassword, salt).

See the following code:

    pass_list = UserPasswordHistory.objects.all().filter(user=user)

    for old_pass in pass_list:
        #split password so we get the hash and the salt
        split_pass = old_pass.password.split('$')
        salt = split_pass[2]
        pw   = split_pass[-1]
        if make_password(password, salt) == old_pass.password:
            raise ValidationError(
                _('Your new Password needs to be different from your old one!'),
                code='password_identic'
            )

Problem

The problem I am having is that somehow, the password generated by Django in the admin backend (via interface) is different from the password I create with using make_password().

The value in the database for my password is:

select password from my_userpasswordhistory;
pbkdf2_sha256$36000$trlHVdErn23Z$BAxX9p3o54QGovIWluP3dM7q73HQNZy9VuYOA6rv268=

However, using the salt trlHVdErn23Z on the an identic raw password, I get:

pbkdf2_sha256$36000$trlHVdErn23Z$6WbA/0fUvDi82GjN7lqjdMoaDiaoojGY3A913CGuFBY=

Also, running make_password() multiple times will always output the same (second) password hash.

I can not figure out if Django uses some additional randomizer whilst creating the password in the admin panel, if I found a bug, or more likely, I missed something.

Thanks a lot in advance.


问:
CSS absolute position, z-index
This must be really simple but I'm stuck.

I have a header and below I have a full height/width block that is absolutely positioned. This will be a map but I have just used a coloured block to make it simple.

On top of this background I need the page that is 100% height in the middle. I thought I could use the z-index to show this on top of the absolutely positioned background but the page is always behind the 'bg' div

I know I'm missing something simple

*{
  margin: 0;
  padding: 0;
}

html, body{
  height: 100%;
}

.header{
  background: black;
  height: 50px;
  width: 100%;
}

.bg{
  background: red;
  position: absolute;
  top: 50px;
  bottom: 0;
  left: 0;
  right: 0;
}

.page{
  background: grey;
  height: 100%;
  margin: 0 auto;
  width: 500px;
  z-index: 10;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="header"></div>

<div class="bg"></div>

<div class="page"></div></code>```

答: z-index has no effect on statically-positioned elements (which is the default). It affects relative, absolute and fixed ("positioned") elements. A common hack would be to add position:relative to your .page.

Title: CSS absolute position, z-index


答:
```<code>import tensorflow as tf
gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.2)
sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options))
from keras import backend as K
import tensorflow as tf
config = tf.ConfigProto()
config.gpu_options.per_process_gpu_memory_fraction = 0.2
session = tf.Session(config=config)
K.set_session(session)
</code>```

This works well for my case

Title: Tensorflow doesn't allocate full GPU memory

Body:
Tensorflow allocates all of GPU memory per default, but my new settings actually only are 9588 MiB / 11264 MiB. I expected around 11.000MiB like my old settings.

Tensorflow information is here:

$ from tensorflow.python.client import device_lib
$ print(device_lib.list_local_devices())

[name: "/cpu:0"
device_type: "CPU"
memory_limit: 268435456
locality {
}
incarnation: 9709578925658430097
, name: "/gpu:0"
device_type: "GPU"
memory_limit: 9273834701
locality {
  bus_id: 1
}
incarnation: 16668416364446126258
physical_device_desc: "device: 0, name: GeForce GTX 1080 Ti, pci bus id: 0000:03:00.0"
, name: "/gpu:1"
device_type: "GPU"
memory_limit: 9273834701
locality {
  bus_id: 1
}
incarnation: 2094938711079475130
physical_device_desc: "device: 1, name: GeForce GTX 1080 Ti, pci bus id: 0000:04:00.0"
]

nvidia-smi.exe says:

+-----------------------------------------------------------------------------+
| NVIDIA-SMI 385.41                 Driver Version: 385.41                    |
|-------------------------------+----------------------+----------------------+
| GPU  Name            TCC/WDDM | Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|===============================+======================+======================|
|   0  GeForce GTX 108... WDDM  | 00000000:03:00.0 Off |                  N/A |
| 23%   35C    P8    13W / 250W |   9284MiB / 11264MiB |      0%      Default |
+-------------------------------+----------------------+----------------------+
|   1  GeForce GTX 108... WDDM  | 00000000:04:00.0 Off |                  N/A |
| 23%   38C    P2    55W / 250W |   9146MiB / 11264MiB |      0%      Default |
+-------------------------------+----------------------+----------------------+

+-----------------------------------------------------------------------------+
| Processes:                                                       GPU Memory |
|  GPU       PID   Type   Process name                             Usage      |
|=============================================================================|
|    0      1280    C+G   ...mmersiveControlPanel\SystemSettings.exe N/A      |
|    0      1448      C   ...ers\Administrator\Anaconda3\pythonw.exe N/A      |
|    0      1560    C+G   Insufficient Permissions                   N/A      |
|    0      4120    C+G   ...6)\Google\Chrome\Application\chrome.exe N/A      |
|    0      4580    C+G   C:\Windows\explorer.exe                    N/A      |
|    0      5188    C+G   ...t_cw5n1h2txyewy\ShellExperienceHost.exe N/A      |
|    0      5324    C+G   ...dows.Cortana_cw5n1h2txyewy\SearchUI.exe N/A      |
|    1      1228    C+G   Insufficient Permissions                   N/A      |
|    1      1244    C+G   Insufficient Permissions                   N/A      |
|    1      1448      C   ...ers\Administrator\Anaconda3\pythonw.exe N/A      |
+-----------------------------------------------------------------------------+

My environment is this:

OS: Windows10
library: python 3.6, keras 2.0.8, tensorflow-gpu 1.3.0, CUDA8.0 CUDNN6.0

Does anyone know the reason?

Body:
import tensorflow as tf
gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.2)
sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options))
from keras import backend as K
import tensorflow as tf
config = tf.ConfigProto()
config.gpu_options.per_process_gpu_memory_fraction = 0.2
session = tf.Session(config=config)
K.set_session(session)

This works well for my case


问:
Spring boot jpa tool is not available in STS(Spring Tool Suite) for converting tables to entities
Here i am working in Spring boot in Spring tool Suite.I want to convert an Oracle databse tables to JPA Class Entites. But i did not get any JPA tools in project_folder ->jpa tools. What i have to do can you please suggest a better solution. Thanks</p>

答:
Create a JPA project like so

```<code>File -> New -> JPA Project(Go to Others if JPA projects is not here)
</code>```

After you have created your JPA project you can right click the project in the Project Explorer

```<code>Project Explorer -> Right-Click -> JPA Tools -> Generate Entities from Tables
</code>```

Hope this helps.

Update 1

If you are not getting options of creating a JPA project in your eclipse you might not be having the required tools for JPA support. Check this.

You can go to "Install New Software", select the Eclipse Oxygen Update
  Site, and then search for the JPA tooling - and install it from there.
  This brings back the JPA tooling.

Body:
Create a JPA project like so

File -> New -> JPA Project(Go to Others if JPA projects is not here)

After you have created your JPA project you can right click the project in the Project Explorer

Project Explorer -> Right-Click -> JPA Tools -> Generate Entities from Tables

Hope this helps.

Update 1

If you are not getting options of creating a JPA project in your eclipse you might not be having the required tools for JPA support. Check this.

You can go to "Install New Software", select the Eclipse Oxygen Update
  Site, and then search for the JPA tooling - and install it from there.
  This brings back the JPA tooling.