问:
How to click toggle switch in webdriverIO
the HTML Element looks like

<input class="workplayEnabled switch" type="checkbox" ng-checked="settings.$storage.enabledApps[app.name]">

i tried browser.click('.toggleButton .switch'),browser.click('.toggleButton'), browser.click(' .switch')

but it's not working
it throws the error as element not visible
whereas if i try browser.isSelected('.toggleButton .switch'),browser.isSelected('.toggleButton'), browser.isSelected(' .switch') it returns false

答:
As it stands, it's really hard to pin-point your EXACT problem as you're doing multiple things wrong.

HTML breakdown:

that is HTML generated via AngularJS;

if you analyze the Angular attributes (ng-attributes/directives) you'll notice only your
 has click-triggered functionality added (via ng-click="settings.apps.toggleApp(app.name)"), thus you only have to target the
 element;

the <input> only has reactive behavior (if the toggle-button is checked, then it gets populated on ng-checked trigger);

Your problem: Now that we narrowed down the solution to clicking your
, we need to make sure your selector is returning the correct element.

open your Angular app, open the browser console & try seeing if your selector is working (e.g.: $(div.toggleButton)). If the CSS-selector returns more than an element($(div.toggleButton).length > 1), that means you have multiple
s with that class so you will have to find a more specific locator;

after you have found the correct locator for your
, I would add a .debug()(more info here) prior to your click in your WebdriverIO script so I could easily debug the scenario;

once in debug-mode, I would try with the same selector that found my element in the browser console.

!!! Note: .isSelected() will always return false in your scenario as you mentioned you failed to click the toggle switch, which is satisfying the ng-checked condition. You can verify this by manually selecting your toggle switch in debug-mode and then performing the .isSelected() command on your <input>. Then it should return true.

Body:
As it stands, it's really hard to pin-point your EXACT problem as you're doing multiple things wrong.

HTML breakdown:

that is HTML generated via AngularJS;

if you analyze the Angular attributes (ng-attributes/directives) you'll notice only your <div> has click-triggered functionality added (via ng-click="settings.apps.toggleApp(app.name)"), thus you only have to target the <div> element;

the <input> only has reactive behavior (if the toggle-button is checked, then it gets populated on ng-checked trigger);

Your problem: Now that we narrowed down the solution to clicking your <div>, we need to make sure your selector is returning the correct element.

open your Angular app, open the browser console & try seeing if your selector is working (e.g.: $(div.toggleButton)). If the CSS-selector returns more than an element($(div.toggleButton).length > 1), that means you have multiple <div>s with that class so you will have to find a more specific locator;

after you have found the correct locator for your <div>, I would add a .debug()(more info here) prior to your click in your WebdriverIO script so I could easily debug the scenario;

once in debug-mode, I would try with the same selector that found my element in the browser console.

!!! Note: .isSelected() will always return false in your scenario as you mentioned you failed to click the toggle switch, which is satisfying the ng-checked condition. You can verify this by manually selecting your toggle switch in debug-mode and then performing the .isSelected() command on your <input>. Then it should return true.


来源: stackexchange

问:
replace string with patterns in file
I've used sed to replace variables on *.go files using sed -i 's/\<old_name\>/newName/g' *.go
My objective is to eliminate golinter errors.
How can strings with common patterns, e.g. replace 1 with 2

fmt.Printf("blah blah blah") or fmt.Printf("yadda yadda yadda")

fmt.Println("blah blah blah") or fmt.Println("yadda yadda yadda")

In this case, we do NOT want to replace:
1. fmt.Printf("print speed= %d",speed) //So the key here is the ending pattern should be ").
2. log.Printf statements //only replace "fmt."
Any pointers on this?

答:
Do

```<code>gofmt -w -r "printf -> println" .
</code>```

Note that make backup file before do this.

ContentLicense: CC BY-SA 3.0

Title: replace string with patterns in file

Body:
Do

gofmt -w -r "printf -> println" .

Note that make backup file before do this.


问:
IIS7 Application Configuration
I have a custom ASP.NET application that I utilize for several clients that I host.  Each client has a separate domain and the application is normally a child application under the root domain (http://domain.com/customapp).  The application files are the same (aspx, ascx, style sheets, images, etc.).  The only thing different is the web.config file for each client.  As development of the application continues to evolve, I have to update the application for each directory and this obviously becoming tedious.  I am trying to come up with a method keep the application up to date.  My first though is placing the application into a single physical path and creating multiple applications pointing to that path (the problem with this method is I can't have different web.config files).  I am curious as to what solution others are using in this scenario...</p>

答:
If you want to handle this entirely in Visual Studio, VS2010 offers web.config transforms which could solve your problem.

In a nutshell, create a build configuration (In VS, select Build|Configuration Manager...) for each site. Add a web.config transform for each client, which only specifies the differences required for each application.

I use this for differentiating between development, staging and release configurations - each transform adjusts the connection string, app settings, etc - and it works quite well both within Visual Studio and when deploying via MSBuild.

Also, note that web.config settings are inherited by IIS applications. So, if you have a root site

```<code>/root
</code>```

and client apps

```<code>/root/client1
/root/client2
...
</code>```

you could place the client-specific config settings in a web.config in each client-specific folder, and global settings a web.config in the root folder.

ContentLicense: CC BY-SA 2.5

Title: IIS7 Application Configuration

Body:
If you want to handle this entirely in Visual Studio, VS2010 offers web.config transforms which could solve your problem.

In a nutshell, create a build configuration (In VS, select Build|Configuration Manager...) for each site. Add a web.config transform for each client, which only specifies the differences required for each application.

I use this for differentiating between development, staging and release configurations - each transform adjusts the connection string, app settings, etc - and it works quite well both within Visual Studio and when deploying via MSBuild.

Also, note that web.config settings are inherited by IIS applications. So, if you have a root site

/root

and client apps

/root/client1
/root/client2
...

you could place the client-specific config settings in a web.config in each client-specific folder, and global settings a web.config in the root folder.


问:
Routing not working in reactjs application
I have created a reactjs app having three pages (components), App, Login and Register, where I need to navigate from page to page by entering the url in the browser but the navigation is not working for me. Entering any url just shows me the 'App' page.

following is the code that I have written in main.js file of the app and the url that I am using to navigate looks something like this http://localhost:8080/#/login or http://localhost:8080/#/reg

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router, Route, NavLink, Redirect, Switch, hashHistory} from 'react-router-dom'
import App from './../jsx/App.jsx';
import Login from './../jsx/Login.jsx';
import Register from './../jsx/Register.jsx';

ReactDOM.render((
     <Router history={hashHistory}>
        <div>
            <Route path="/" component={App}/>
            <Route path="/login" component={Login}/>
            <Route path="/reg" component={Register}/>
        </div>
    </Router>

), document.getElementById('app'))
</code>```

答:
If you are using react router 4, then that looks fine. However, you can try using a  as shown below:

```<code><BrowserRouter>
    <Switch>
      <Route path="/" component={Home} />
    </Switch>
</BrowserRouter>
</code>```

This is in latest versions of react. The Home component is as below:

```<code> render() {
    return (
        <div>
            <p>Header Section</p>
            <Header/>
            <p>Home component</p>
            <Link to="/search">search</Link>
            <Route path="/search" component={Search}/>
        </div>
    );
}
</code>```

So most probably what you need to do is to just add a switch. Other solutions may be possible too. Hope this helps :)

Body:
I have created a reactjs app having three pages (components), App, Login and Register, where I need to navigate from page to page by entering the url in the browser but the navigation is not working for me. Entering any url just shows me the 'App' page.

following is the code that I have written in main.js file of the app and the url that I am using to navigate looks something like this http://localhost:8080/#/login or http://localhost:8080/#/reg

import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router, Route, NavLink, Redirect, Switch, hashHistory} from 'react-router-dom'
import App from './../jsx/App.jsx';
import Login from './../jsx/Login.jsx';
import Register from './../jsx/Register.jsx';

ReactDOM.render((
     <Router history={hashHistory}>

            <Route path="/" component={App}/>
            <Route path="/login" component={Login}/>
            <Route path="/reg" component={Register}/>

    </Router>

), document.getElementById('app'))

Body:
If you are using react router 4, then that looks fine. However, you can try using a  as shown below:

<BrowserRouter>
    <Switch>
      <Route path="/" component={Home} />
    </Switch>
</BrowserRouter>

This is in latest versions of react. The Home component is as below:

 render() {
    return (
        <div>
            <p>Header Section</p>
            <Header/>
            <p>Home component</p>
            <Link to="/search">search</Link>
            <Route path="/search" component={Search}/>
        </div>
    );
}

So most probably what you need to do is to just add a switch. Other solutions may be possible too. Hope this helps :)


问:
Issue with clicking link on selenium java
I tried everything. By xpath , by css-selector , by class name too.

```<code>//*[@id="opbox-listing"]/div/div/section[2]/section/article[5]/div/div/div[2]/h2/a
thats look xpath , but don't work
</code>```

on selenium i tried thats way:

```<code>        driver.findElement(By.xpath("//*[@id=opbox-listing']/div/div/section[2]/section/article[5]/div/div/div[2]/h2/a")).submit();

        driver.findElement(By.xpath("//*[@id=opbox-listing']/div/div/section[2]/section/article[5]/div/div/div[2]/h2/a")).click();
</code>```

what i do wrong? someone have any ideas?

答:
Try out clicking on the element using one of following methods

Method 1:

```<code>Actions action = new Actions(driver);
action.moveToElement(<your WebElement>).click().perform();
</code>```

Method 2:

```<code>JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("arguments[0].click();", <your WebElement>);
</code>```

These are just workarounds. Please provide the exception that you are getting while performing the normal selenium click operation may be that can help you find an answer.

Body:
I tried everything. By xpath , by css-selector , by class name too.

//*[@id="opbox-listing"]/div/div/section[2]/section/article[5]/div/div/div[2]/h2/a
thats look xpath , but don't work

on selenium i tried thats way:

        driver.findElement(By.xpath("//*[@id=opbox-listing']/div/div/section[2]/section/article[5]/div/div/div[2]/h2/a")).submit();

        driver.findElement(By.xpath("//*[@id=opbox-listing']/div/div/section[2]/section/article[5]/div/div/div[2]/h2/a")).click();

what i do wrong? someone have any ideas?

Body:
Try out clicking on the element using one of following methods

Method 1:

Actions action = new Actions(driver);
action.moveToElement(<your WebElement>).click().perform();

Method 2:

JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("arguments[0].click();", <your WebElement>);

These are just workarounds. Please provide the exception that you are getting while performing the normal selenium click operation may be that can help you find an answer.


问:
How to read image as FileInputStream from source folder?
I have been trying to upload image to database. So I made a browse button to go through directories and get the image.  Suppose if no image is selected, a default image will be uploaded to the database. The image is stored in a folder named 'resources' under source folder.In the image, helper is the folder containting .java files and below is the resources folder I am uploading the image as FileInputStream and the code is

```<code>File pic=new File(imgloc);
FileInputStream fis=new FileInputStream(pic);
</code>```

If the image is not selected to upload a default image my code is

```<code>File pic=new File(this.getClass().getResource("/resources/profile1.png").getFile());
FileInputStream fis=new FileInputStream(pic);
</code>```

And my query to database is

```<code>    ps.setBinaryStream(1,fis ,(int) pic.length()); //While substituing for '?' in query
</code>```

After build to jar it produce FileNotFoundException when trying to add default image. May be the question is asked several times I didn't find solution in that.  I want read the image as file..Thanks in advance.

答:
Consider following package structure

```<code>/
/testing_package
/testing_package/Main.java
/testing_package/Image.png
</code>```

Now Here is a program to get Image.png and put it in database

```<code>public class Main {
    public static void main(String...args) {
        System.out.println(Main.class.getResource("image.jpg"));
        //PreparedStatement as ps
        ps.setBinaryStream(1, Main.class.getResourceAsStream("image.jpg")));
    }
}
</code>```

Thing to keep in mind

When using getResource(...) or getResourceAsStream(...) use relative location to the class instance whose function you are invoking.

Have a look at this answer too

Body:
I have been trying to upload image to database. So I made a browse button to go through directories and get the image.  Suppose if no image is selected, a default image will be uploaded to the database. The image is stored in a folder named 'resources' under source folder.In the image, helper is the folder containting .java files and below is the resources folder I am uploading the image as FileInputStream and the code is

File pic=new File(imgloc);
FileInputStream fis=new FileInputStream(pic);

If the image is not selected to upload a default image my code is

File pic=new File(this.getClass().getResource("/resources/profile1.png").getFile());
FileInputStream fis=new FileInputStream(pic);

And my query to database is

    ps.setBinaryStream(1,fis ,(int) pic.length()); //While substituing for '?' in query

After build to jar it produce FileNotFoundException when trying to add default image. May be the question is asked several times I didn't find solution in that.  I want read the image as file..Thanks in advance.

Body:
Consider following package structure

/
/testing_package
/testing_package/Main.java
/testing_package/Image.png

Now Here is a program to get Image.png and put it in database

public class Main {
    public static void main(String...args) {
        System.out.println(Main.class.getResource("image.jpg"));
        //PreparedStatement as ps
        ps.setBinaryStream(1, Main.class.getResourceAsStream("image.jpg")));
    }
}

Thing to keep in mind

When using getResource(...) or getResourceAsStream(...) use relative location to the class instance whose function you are invoking.

Have a look at this answer too


问:
how to get selected id inside interval using jquery
Having this piece of code and i want to get selected element id (popup_w) but this.id or $(this).attr('id') or $this returning undefined...

Is there any problem with interval? How i will get the selected element id?

console.clear();
$('#btn').on('click', function(){
   $("body").prepend('
A new popup div added
');
});

var found = false;
var checkDiv = setInterval( function() {

  if ( $("div[id$='_w']").length && !found) {
    found = true;
    console.log( this.id );
  };

}, 1000);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" value="click" id="btn"></code>```

答:
Instead of using setInterval use jQuery custom event handler.

First we generate random new Id, then we trigger new event called elementAdded.

param1 is your id attribute, you can easly access now your newly created element via $('#' + param1);

See working example.

console.clear();
$('#btn').on('click', function(){
    var newId = makeid();
   $("body").prepend('
A new popup div added
');
   $("body").trigger("elementAdded", [ newId ]);
});

 $("body").on("elementAdded", function (event, param1) {
   // our new button
  var element = $('#' + param1);
  // Access your element $('#' + param1)
  console.log(element.length); // if 1 element is found any usable
});

function makeid() {
  var text = "";
  var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

  for (var i = 0; i < 5; i++)
    text += possible.charAt(Math.floor(Math.random() * possible.length));

  return text;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" value="click" id="btn"></code>```

Body:
Having this piece of code and i want to get selected element id (popup_w) but this.id or $(this).attr('id') or $this returning undefined...

Is there any problem with interval? How i will get the selected element id?

console.clear();
$('#btn').on('click', function(){
   $("body").prepend('
A new popup div added
');
});

var found = false;
var checkDiv = setInterval( function() {

  if ( $("div[id$='_w']").length && !found) {
    found = true;
    console.log( this.id );
  };

}, 1000);

<input type="button" value="click" id="btn">

Body:
Instead of using setInterval use jQuery custom event handler.

First we generate random new Id, then we trigger new event called elementAdded.

param1 is your id attribute, you can easly access now your newly created element via $('#' + param1);

See working example.

console.clear();
$('#btn').on('click', function(){
    var newId = makeid();
   $("body").prepend('<div id="' + newId + '">A new popup div added</div>');
   $("body").trigger("elementAdded", [ newId ]);
});

 $("body").on("elementAdded", function (event, param1) {
   // our new button
  var element = $('#' + param1);
  // Access your element $('#' + param1)
  console.log(element.length); // if 1 element is found any usable
});

function makeid() {
  var text = "";
  var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

  for (var i = 0; i < 5; i++)
    text += possible.charAt(Math.floor(Math.random() * possible.length));

  return text;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" value="click" id="btn">


问:
How can I pass an array as argument to TCL script command line run?
I have script 2 script main.tcl and sub.tcl, Where in main.tcl I create 2 arrays, which I need to pass to the sub.tcl script as command line arguments.

Main.tcl:

```<code>   set arr1(0) 100
   set arr1(1) 200

   set arr2(0) 300
   set arr2(1) 400
   set res [exec tclsh.exe sub.tcl arr1 arr2]
   puts $res
</code>```

sub.tcl

```<code>      set arr1 [lindex $argv 0]
      set arr2 [lindex $argv 1]
      puts [array get arr1]
      puts [array get arr2]
</code>```

The sub.tcl script consider the array arguments as variables and it does not print any values at the output. Could you please help, how can specify the array while passing array as command line argument.

答:
To pass an array we should use array get <arrayname>. So, you should be calling the sub.tcl, as

```<code>set res [exec tclsh.exe sub.tcl [array get arr1] [array get arr2]]
</code>```

In sub.tcl, directly print the args as

```<code>array set arr1 [lindex $argv 0]
array set arr2 [lindex $argv 1]
parray arr1
parray arr2
</code>```

Body:
I have script 2 script main.tcl and sub.tcl, Where in main.tcl I create 2 arrays, which I need to pass to the sub.tcl script as command line arguments.

Main.tcl:

   set arr1(0) 100
   set arr1(1) 200

   set arr2(0) 300
   set arr2(1) 400
   set res [exec tclsh.exe sub.tcl arr1 arr2]
   puts $res

sub.tcl

      set arr1 [lindex $argv 0]
      set arr2 [lindex $argv 1]
      puts [array get arr1]
      puts [array get arr2]

The sub.tcl script consider the array arguments as variables and it does not print any values at the output. Could you please help, how can specify the array while passing array as command line argument.

Body:
To pass an array we should use array get <arrayname>. So, you should be calling the sub.tcl, as

set res [exec tclsh.exe sub.tcl [array get arr1] [array get arr2]]

In sub.tcl, directly print the args as

array set arr1 [lindex $argv 0]
array set arr2 [lindex $argv 1]
parray arr1
parray arr2


问:
how to restart my tp-link router from java
I need to restart my router from java(or any script that can do this every 5 minute!)

I tried this but my problem is when I execute this command "telnet 192.168.1.1" I can not enter my password.

```<code> Process process = Runtime.getRuntime().exec("cmd.exe /c start telnet 192.168.1.1");
</code>```

and after this code I see this on screen and I don't know how to enter my pass to it from my java code!!

答:
I solve it.

just by using chrome driver:)

Body:
I need to restart my router from java(or any script that can do this every 5 minute!)

I tried this but my problem is when I execute this command "telnet 192.168.1.1" I can not enter my password.

 Process process = Runtime.getRuntime().exec("cmd.exe /c start telnet 192.168.1.1");

and after this code I see this on screen and I don't know how to enter my pass to it from my java code!!


问:
No Angular source maps in Karma DEBUG RUNNER
Since recently upgrading to the latest angular-cli and angular, I no longer see source-maps in the Chrome Karma debug runner.

Having done a bit of research I came across the ng test --sourcemaps=true option but that has made no difference, there is no webpack:// folder like there used to be in the chrome debug tools source tab.

ng -v log:

```<code>@angular/cli: 1.1.3
node: 6.9.4
os: win32 x64
@angular/animations: 4.2.4
@angular/common: 4.2.4
@angular/compiler: 4.2.4
@angular/core: 4.2.4
@angular/forms: 4.2.4
@angular/http: 4.2.4
@angular/platform-browser: 4.2.4
@angular/platform-browser-dynamic: 4.2.4
@angular/router: 4.2.4
@angular/cli: 1.1.3
@angular/compiler-cli: 4.2.4
@angular/language-service: 4.2.4
</code>```

karma.conf:

```<code>module.exports = function (config) {
    config.set({
        basePath: '',
        frameworks: ['jasmine', '@angular/cli'],
        plugins: [
            require('karma-jasmine'),
            require('karma-chrome-launcher'),
            require('karma-jasmine-html-reporter'),
            //require('karma-coverage-istanbul-reporter'),
            require('@angular/cli/plugins/karma')
        ],
        client: {
            clearContext: false // leave Jasmine Spec Runner output visible in browser
        },
        // coverageIstanbulReporter: {
        //     reports: ['html', 'lcovonly'],
        //     fixWebpackSourcePaths: true
        // },
        angularCli: {
            environment: 'dev'
        },
        reporters: ['progress', 'kjhtml'],
        port: 9876,
        colors: true,
        browsers: ['Chrome'],
        logLevel: config.LOG_DEBUG,
        autoWatch: true,
        singleRun: false,
        sourceMaps: true,
        captureTimeout: 25000,
        browserDisconnectTolerance: 3, //this one helps
        browserDisconnectTimeout: 25000,
        browserNoActivityTimeout: 25000,
        skipFiles: [
            "node_modules/**/*"
        ],
        webRoot: "${workspaceRoot}"
    });
};
</code>```

答: This has been fixed see https://github.com/angular/angular-cli/pull/6862 in the latest angular-cli build</p>

Body:
Since recently upgrading to the latest angular-cli and angular, I no longer see source-maps in the Chrome Karma debug runner.

Having done a bit of research I came across the ng test --sourcemaps=true option but that has made no difference, there is no webpack:// folder like there used to be in the chrome debug tools source tab.

ng -v log:

@angular/cli: 1.1.3
node: 6.9.4
os: win32 x64
@angular/animations: 4.2.4
@angular/common: 4.2.4
@angular/compiler: 4.2.4
@angular/core: 4.2.4
@angular/forms: 4.2.4
@angular/http: 4.2.4
@angular/platform-browser: 4.2.4
@angular/platform-browser-dynamic: 4.2.4
@angular/router: 4.2.4
@angular/cli: 1.1.3
@angular/compiler-cli: 4.2.4
@angular/language-service: 4.2.4

karma.conf:

module.exports = function (config) {
    config.set({
        basePath: '',
        frameworks: ['jasmine', '@angular/cli'],
        plugins: [
            require('karma-jasmine'),
            require('karma-chrome-launcher'),
            require('karma-jasmine-html-reporter'),
            //require('karma-coverage-istanbul-reporter'),
            require('@angular/cli/plugins/karma')
        ],
        client: {
            clearContext: false // leave Jasmine Spec Runner output visible in browser
        },
        // coverageIstanbulReporter: {
        //     reports: ['html', 'lcovonly'],
        //     fixWebpackSourcePaths: true
        // },
        angularCli: {
            environment: 'dev'
        },
        reporters: ['progress', 'kjhtml'],
        port: 9876,
        colors: true,
        browsers: ['Chrome'],
        logLevel: config.LOG_DEBUG,
        autoWatch: true,
        singleRun: false,
        sourceMaps: true,
        captureTimeout: 25000,
        browserDisconnectTolerance: 3, //this one helps
        browserDisconnectTimeout: 25000,
        browserNoActivityTimeout: 25000,
        skipFiles: [
            "node_modules/**/*"
        ],
        webRoot: "${workspaceRoot}"
    });
};


问:
How does PHP actually work?
Is there some guide out there that describes how the PHP internals?

How files are loaded (required, included)?

How they are parsed and executed?

How memory is allocated?

How objects are created/destroyed?

How external modules are loaded?

How the stack/heap works?

How opcode caching actually work?

Common hacks and performance tips?

答: This excellent although somewhat outdated book by Sara Golemon has answers to the most of your questions. Otherwise, the best way to learn php internals is to compile a debug version of it and run it step by step under a debugger. I did it once and it was an exciting experience.</p>

Title: How does PHP actually work?


问:
SYNC with master failed: -ERR unknown command 'SYNC'
I was trying to dump my Redis data that is hosted via AWS.  I can log into the interactive mode via redis-cli, but when I tried dumping the data to an RDB file I received the following error in the title...

user@awshost:~/TaoRedisExtract$ redis-cli -h myawsredis.amazonaws.com --rdb redis.dump.rdb
SYNC with master failed: -ERR unknown command 'SYNC'

I'm not sure if this is a bug, a configuration issue, or known/expected behavior for AWS redis?  I've searched and searched and not found any other reports of users getting this error message.

答:
according to reply of similar question of aws forum

From redis version 2.8.22 SYNC has been disabled:

"To maintain enhanced replication performance in Multi-AZ replication groups and for increased cluster stability, non-ElastiCache replicas are no longer supported"


问:
Bench test using siege by using dynamic url generated using bash script
I want to bench test my website with 1M requests with different urls using siege, I need to know can I create a bash script to do a random loop or php script to read urls from database and create dynamic urls and give this urls to siege command to perform bench test ?

for example I have this type of banner_sizes :

```<code>[
    {
        "id": 1,
        "size": "normal_x970h90",
    },
    {
        "id": 2,
        "size": "normal_x234h60",
    },
    {
        "id": 3,
        "size": "normal_x468h60",
    },
    {
        "id": 4,
        "size": "normal_x300h600",
    },
    {
        "id": 5,
        "size": "normal_x120h600",
    },
    {
        "id": 6,
        "size": "normal_x160h600",
    },
    {
        "id": 7,
        "size": "normal_x120h240",
    },
    {
        "id": 8,
        "size": "normal_x300h250",
    },
    {
        "id": 9,
        "size": "normal_x250h250",
    },
    {
        "id": 10,
        "size": "normal_x600h300",
    },
    {
        "id": 11,
        "size": "normal_x728h90",
    },
    {
        "id": 12,
        "size": "normal_x300h100",
    },
    {
        "id": 13,
        "size": "normal_x125h125",
    }
]
</code>```

And also I have these id's :

```<code> [
  0 => array:1 [
    "_id" => MongoDB\BSON\ObjectID {#915}
  ]
  1 => array:1 [
    "_id" => MongoDB\BSON\ObjectID {#926}
  ]
  2 => array:1 [
    "_id" => MongoDB\BSON\ObjectID {#924}
  ]
  3 => array:1 [
    "_id" => MongoDB\BSON\ObjectID {#913}
  ]
  4 => array:1 [
    "_id" => MongoDB\BSON\ObjectID {#929}
  ]
  5 => array:1 [
    "_id" => MongoDB\BSON\ObjectID {#862}
  ]
  6 => array:1 [
    "_id" => MongoDB\BSON\ObjectID {#863}
  ]
  7 => array:1 [
    "_id" => MongoDB\BSON\ObjectID {#864}
  ]
  8 => array:1 [
    "_id" => MongoDB\BSON\ObjectID {#865}
  ]
  9 => array:1 [
    "_id" => MongoDB\BSON\ObjectID {#928}
  ]
  10 => array:1 [
    "_id" => MongoDB\BSON\ObjectID {#927}
  ]
  11 => array:1 [
    "_id" => MongoDB\BSON\ObjectID {#917}
  ]
  12 => array:1 [
    "_id" => MongoDB\BSON\ObjectID {#918}
  ]
  13 => array:1 [
    "_id" => MongoDB\BSON\ObjectID {#899}
  ]
  14 => array:1 [
    "_id" => MongoDB\BSON\ObjectID {#898}
  ]
]
</code>```

I need to create these type of url using above info :

```<code>www.example.come/api/is/normal_x234h60/899
www.example.com/api/is/normal_x600h300/898
</code>```

and more like this.

Is there a way to create this urls and put them in txt file and then run my siege command :

```<code>   siege -c10000 -b -t30m -f urls.txt
</code>```

Or using apache ab bench test ?

答:
I've found a solution for this matter, I've created a php file which it connects to mysql and mongodb database and read the data, then in a nested for loop I created those urls I needed and stored them in txt file.
then I just needed to run the siege command :

```<code>siege -c10000 -b -t30m -f urls.txt
</code>```

but because of siege issue with big size requests I created a bash script which will read each line of urls.txt file and runs an apache ab test using each url to stress test with dynamic urls my application.

php code to create urls :

```<code>        $seats = Seat::where('status', 'ACTIVE')->get();
        $s_count = Seat::where('status', 'ACTIVE')->count();

        $bs = Banners::where('status', 'enable')->get();
        $bs_count = Banners::where('status', 'enable')->count();

        $url = Config('conf.APP_PATH') . "/api/is/";
        $url_array = array();

        for ($i = 0; $i < $s_count; $i++) {
            for ($j = 0; $j < $bs_count; $j++) {
                $url_array[] = $url . $bs[$j]['size'] . "/" . $seats[$i]['_id']."\n";
            }
        }

        File::put('./url.txt',$url_array);
</code>```

bash script to run multiple bench test :

```<code>while read LINE; do
   cmnd="./ab -n10000 -c100 "
   cmnd=${cmnd}"$LINE"
   eval $cmnd
   cmnd=''
done < urls.txt
</code>```

Body:
I want to bench test my website with 1M requests with different urls using siege, I need to know can I create a bash script to do a random loop or php script to read urls from database and create dynamic urls and give this urls to siege command to perform bench test ?

for example I have this type of banner_sizes :

[
    {
        "id": 1,
        "size": "normal_x970h90",
    },
    {
        "id": 2,
        "size": "normal_x234h60",
    },
    {
        "id": 3,
        "size": "normal_x468h60",
    },
    {
        "id": 4,
        "size": "normal_x300h600",
    },
    {
        "id": 5,
        "size": "normal_x120h600",
    },
    {
        "id": 6,
        "size": "normal_x160h600",
    },
    {
        "id": 7,
        "size": "normal_x120h240",
    },
    {
        "id": 8,
        "size": "normal_x300h250",
    },
    {
        "id": 9,
        "size": "normal_x250h250",
    },
    {
        "id": 10,
        "size": "normal_x600h300",
    },
    {
        "id": 11,
        "size": "normal_x728h90",
    },
    {
        "id": 12,
        "size": "normal_x300h100",
    },
    {
        "id": 13,
        "size": "normal_x125h125",
    }
]

And also I have these id's :

 [
  0 => array:1 [
    "_id" => MongoDB\BSON\ObjectID {#915}
  ]
  1 => array:1 [
    "_id" => MongoDB\BSON\ObjectID {#926}
  ]
  2 => array:1 [
    "_id" => MongoDB\BSON\ObjectID {#924}
  ]
  3 => array:1 [
    "_id" => MongoDB\BSON\ObjectID {#913}
  ]
  4 => array:1 [
    "_id" => MongoDB\BSON\ObjectID {#929}
  ]
  5 => array:1 [
    "_id" => MongoDB\BSON\ObjectID {#862}
  ]
  6 => array:1 [
    "_id" => MongoDB\BSON\ObjectID {#863}
  ]
  7 => array:1 [
    "_id" => MongoDB\BSON\ObjectID {#864}
  ]
  8 => array:1 [
    "_id" => MongoDB\BSON\ObjectID {#865}
  ]
  9 => array:1 [
    "_id" => MongoDB\BSON\ObjectID {#928}
  ]
  10 => array:1 [
    "_id" => MongoDB\BSON\ObjectID {#927}
  ]
  11 => array:1 [
    "_id" => MongoDB\BSON\ObjectID {#917}
  ]
  12 => array:1 [
    "_id" => MongoDB\BSON\ObjectID {#918}
  ]
  13 => array:1 [
    "_id" => MongoDB\BSON\ObjectID {#899}
  ]
  14 => array:1 [
    "_id" => MongoDB\BSON\ObjectID {#898}
  ]
]

I need to create these type of url using above info :

www.example.come/api/is/normal_x234h60/899
www.example.com/api/is/normal_x600h300/898

and more like this.

Is there a way to create this urls and put them in txt file and then run my siege command :

   siege -c10000 -b -t30m -f urls.txt

Or using apache ab bench test ?

Body:
I've found a solution for this matter, I've created a php file which it connects to mysql and mongodb database and read the data, then in a nested for loop I created those urls I needed and stored them in txt file.
then I just needed to run the siege command :

siege -c10000 -b -t30m -f urls.txt

but because of siege issue with big size requests I created a bash script which will read each line of urls.txt file and runs an apache ab test using each url to stress test with dynamic urls my application.

php code to create urls :

        $seats = Seat::where('status', 'ACTIVE')->get();
        $s_count = Seat::where('status', 'ACTIVE')->count();

        $bs = Banners::where('status', 'enable')->get();
        $bs_count = Banners::where('status', 'enable')->count();

        $url = Config('conf.APP_PATH') . "/api/is/";
        $url_array = array();

        for ($i = 0; $i < $s_count; $i++) {
            for ($j = 0; $j < $bs_count; $j++) {
                $url_array[] = $url . $bs[$j]['size'] . "/" . $seats[$i]['_id']."\n";
            }
        }

        File::put('./url.txt',$url_array);

bash script to run multiple bench test :

while read LINE; do
   cmnd="./ab -n10000 -c100 "
   cmnd=${cmnd}"$LINE"
   eval $cmnd
   cmnd=''
done < urls.txt


问:
How to write a service which consumes 2 different types of objects but have a single endpoint?
How to write a service which consumes 2 different types of objects but have a single endpoint ?

/hello is the endpoint I should be able to handle Class Hello1 and Class Hello2 in that...both having different parameters.

```<code>@CrossOrigin
@ResponseStatus(HttpStatus.OK)
@RequestMapping(value = "/hello", method = RequestMethod.POST)
public BaseResponseDTO geteula(@RequestBody Hello1 request) {}

@CrossOrigin
@ResponseStatus(HttpStatus.OK)
@RequestMapping(value = "/hello", method = RequestMethod.POST)
public BaseResponseDTO geteula(@RequestBody Hello2 request) {}
</code>```

Above is what I need actually...but it needs to be a single endpoint.

答:
Please learn how to format code; I did it for you.

What is @CrossOrigin - AFAIK, Spring doesn't have any such annotation.

Don't do this: Create separate methods.

If for some reason, your life depends on writing convoluted code, you can inject the HttpServletRequest as a parameter to your method and convert the request body into one of the 2 types. You'll have to figure out what type the body is based on something in the request.

Edit:
I see that Spring has, in fact, introduced a @CrossOrigin annotation. I stand corrected on #2.

Body:
How to write a service which consumes 2 different types of objects but have a single endpoint ?

/hello is the endpoint I should be able to handle Class Hello1 and Class Hello2 in that...both having different parameters.

@CrossOrigin
@ResponseStatus(HttpStatus.OK)
@RequestMapping(value = "/hello", method = RequestMethod.POST)
public BaseResponseDTO geteula(@RequestBody Hello1 request) {}

@CrossOrigin
@ResponseStatus(HttpStatus.OK)
@RequestMapping(value = "/hello", method = RequestMethod.POST)
public BaseResponseDTO geteula(@RequestBody Hello2 request) {}

Above is what I need actually...but it needs to be a single endpoint.


问:
Project taking too long to build and run after adding complex query
I have integrated SQLite.swift framework in one of my swift project and everything was working fine until i added the below query. After adding the below query project is taking too long to build. I waited for 30 mins but still project is n't complied.

```<code>do
{
let stmt = try DB!.prepare ("SELECT e." + ENDPOINT_ID + " as _id, lk." + HUB_ID + ", e." + X_ENDPOINT_ID + ", e." + ENDPOINT_DESC + ", e." + ENDPOINT_TYPE_ID +", et." + ENDPOINT_STATUS_MIN + ", et." + ENDPOINT_STATUS_MAX + ", e." + ENDPOINT_STATUS + " FROM " + TABLE_ENDPOINT + " as e INNER JOIN " + TABLE_ENDPOINT_TYPE + " as et " +
" ON e." + ENDPOINT_TYPE_ID + " = et." + ENDPOINT_TYPE_ID +
" INNER JOIN " + TABLE_LINKING + " as lk " +
" ON e." + ENDPOINT_ID + " = lk." + ENDPOINT_ID +
" INNER JOIN " + TABLE_NODE + " as n " +
" ON lk." + NODE_ID + " = n." + NODE_ID +
" INNER JOIN " + TABLE_NODE_TYPE + " as nt " +
" ON n." + NODE_TYPE_ID + " = nt." + NODE_TYPE_ID +
" WHERE lk." + SECTION_ID + "=" + section_Id +
" AND nt." + NODE_CATEGORY + " = "S" " +
" ORDER BY e." + ENDPOINT_ID + " ASC")

        let arr = Array(try stmt.run)

        print("\(arr)")
        return arr
    } catch {
        print("failed: \(error)")
        return []
    }
</code>```

If i comment the above code and try to run the project it takes hardly a minute to run the project but after adding this code, it's taking hell lot of time. I have waited for almost 30 mins but still the project is not compiled nor it's throwing any error.
Thanks in advance for help

答:
The Swift compiler has difficulties to deal with big string literals. See also this question for further hints.

I would recommend to split up the sql and to build a string variable in small steps:

```<code>var sql = "SELECT e." + ENDPOINT_ID
sql = sql + HUB_ID + ", e."
sql = sql + X_ENDPOINT_ID + ", e."
...
let stmt = try DB!.prepare(sql)
</code>```

Body:
I have integrated SQLite.swift framework in one of my swift project and everything was working fine until i added the below query. After adding the below query project is taking too long to build. I waited for 30 mins but still project is n't complied.

do
{
let stmt = try DB!.prepare ("SELECT e." + ENDPOINT_ID + " as _id, lk." + HUB_ID + ", e." + X_ENDPOINT_ID + ", e." + ENDPOINT_DESC + ", e." + ENDPOINT_TYPE_ID +", et." + ENDPOINT_STATUS_MIN + ", et." + ENDPOINT_STATUS_MAX + ", e." + ENDPOINT_STATUS + " FROM " + TABLE_ENDPOINT + " as e INNER JOIN " + TABLE_ENDPOINT_TYPE + " as et " +
" ON e." + ENDPOINT_TYPE_ID + " = et." + ENDPOINT_TYPE_ID +
" INNER JOIN " + TABLE_LINKING + " as lk " +
" ON e." + ENDPOINT_ID + " = lk." + ENDPOINT_ID +
" INNER JOIN " + TABLE_NODE + " as n " +
" ON lk." + NODE_ID + " = n." + NODE_ID +
" INNER JOIN " + TABLE_NODE_TYPE + " as nt " +
" ON n." + NODE_TYPE_ID + " = nt." + NODE_TYPE_ID +
" WHERE lk." + SECTION_ID + "=" + section_Id +
" AND nt." + NODE_CATEGORY + " = "S" " +
" ORDER BY e." + ENDPOINT_ID + " ASC")

        let arr = Array(try stmt.run)

        print("\(arr)")
        return arr
    } catch {
        print("failed: \(error)")
        return []
    }

If i comment the above code and try to run the project it takes hardly a minute to run the project but after adding this code, it's taking hell lot of time. I have waited for almost 30 mins but still the project is not compiled nor it's throwing any error.
Thanks in advance for help

Body:
The Swift compiler has difficulties to deal with big string literals. See also this question for further hints.

I would recommend to split up the sql and to build a string variable in small steps:

var sql = "SELECT e." + ENDPOINT_ID
sql = sql + HUB_ID + ", e."
sql = sql + X_ENDPOINT_ID + ", e."
...
let stmt = try DB!.prepare(sql)


问:
Stable cycle time
I'm trying to execute a method with a stable cycle time (e.g. 20ms). My current approach is to create a thread using std::thread. Inside this thread I do the following (pseudocode):

```<code>while(true)
{
  tStart = GetCurrentTime();
  ExecuteMethod();
  tEnd = GetCurrentTime();

  actualCycleTime = tEnd - tStart;
  SleepFor(DesiredCycleTime - actualCycleTime);
}
</code>```

For time measurement and sleeping I use std::chrono (std::steady_clock and std::thread::sleep_for).

The problem is that my loop does not run at the expected stable 20ms. Instead, I get cycle times between 20 and 60ms. My guess is that this is caused by the Windows scheduler.

Is there a better way to achieve a stable cycle time (busy waiting, etc.)?

答:
You could use a timer event.  If you need a really solid clock, you need to raise your priority level to the max.  This code will give you the best possible performance for a user-mode application. I've omitted the usual error checking, for clarity, but I've marked the calls that should be checked.  If in doubt, consult MSDN.

Windows timer resolution is limited to a global time-slice Windows uses to switch between threads.  On modern CPUs, that value is usuallu 2-5ms. on older CPUs this value is 10-15ms.  You can control this global setting
by calling timeBeginPeriod(). This will affect the precision of the interrupts.

```<code>// use this event to exit the loop, by calling SetEvent(hExitEvent).
HANDLE hExitEvent = CreateEvent(NULL, NULL, FALSE, NULL);

void RealTimeLoop()
{
    // You may want to raise the process priority...
    HANDLE hProcess = GetCurrentProcess();                       // never fails
    SetPriorityClass(hProcess, REALTIME_PRIORITY_CLASS);

    // setting the priority is critical.
    HANDLE hThread = GetCurrentThread();                         // never fails
    SetThreadPriority(hThread, THREAD_PRIORITY_TIME_CRITICAL);   // could fail

    timeBeginPeriod(1);                                          // could fail

    HANDLE hTimer = CreateWaitableTimer(NULL, FALSE, NULL);      // could fail

    // could also set a call back here, but I've never tried it.
    LARGE_INTEGER dueTime = {};
    SetWaitableTimer(hTimer, &dueTime, 20, NULL, NULL, FALSE);   // could fail

    HANDLE ah[2] = { hExitEvent, hTimer };
    bool exitLoop = false;

    while(!exitLoop)
    {
        switch (WaitForMultipleObjects(2, ah, FALSE, INFINITE))
        {
            default:  // error would arrive here
            case 0:  exitLoop = true; break;
            case 1:  ExecuteMethod(); break;
        }
   }
   timeEndPeriod(1);
   CloseHandle(hTimer);
   CloseHandle(hThread);
   CloseHandle(hProcess);
}
</code>```

Title: Stable cycle time

Body:
I'm trying to execute a method with a stable cycle time (e.g. 20ms). My current approach is to create a thread using std::thread. Inside this thread I do the following (pseudocode):

while(true)
{
  tStart = GetCurrentTime();
  ExecuteMethod();
  tEnd = GetCurrentTime();

  actualCycleTime = tEnd - tStart;
  SleepFor(DesiredCycleTime - actualCycleTime);
}

For time measurement and sleeping I use std::chrono (std::steady_clock and std::thread::sleep_for).

The problem is that my loop does not run at the expected stable 20ms. Instead, I get cycle times between 20 and 60ms. My guess is that this is caused by the Windows scheduler.

Is there a better way to achieve a stable cycle time (busy waiting, etc.)?

Body:
You could use a timer event.  If you need a really solid clock, you need to raise your priority level to the max.  This code will give you the best possible performance for a user-mode application. I've omitted the usual error checking, for clarity, but I've marked the calls that should be checked.  If in doubt, consult MSDN.

Windows timer resolution is limited to a global time-slice Windows uses to switch between threads.  On modern CPUs, that value is usuallu 2-5ms. on older CPUs this value is 10-15ms.  You can control this global setting
by calling timeBeginPeriod(). This will affect the precision of the interrupts.

// use this event to exit the loop, by calling SetEvent(hExitEvent).
HANDLE hExitEvent = CreateEvent(NULL, NULL, FALSE, NULL);

void RealTimeLoop()
{
    // You may want to raise the process priority...
    HANDLE hProcess = GetCurrentProcess();                       // never fails
    SetPriorityClass(hProcess, REALTIME_PRIORITY_CLASS);

    // setting the priority is critical.
    HANDLE hThread = GetCurrentThread();                         // never fails
    SetThreadPriority(hThread, THREAD_PRIORITY_TIME_CRITICAL);   // could fail

    timeBeginPeriod(1);                                          // could fail

    HANDLE hTimer = CreateWaitableTimer(NULL, FALSE, NULL);      // could fail

    // could also set a call back here, but I've never tried it.
    LARGE_INTEGER dueTime = {};
    SetWaitableTimer(hTimer, &dueTime, 20, NULL, NULL, FALSE);   // could fail

    HANDLE ah[2] = { hExitEvent, hTimer };
    bool exitLoop = false;

    while(!exitLoop)
    {
        switch (WaitForMultipleObjects(2, ah, FALSE, INFINITE))
        {
            default:  // error would arrive here
            case 0:  exitLoop = true; break;
            case 1:  ExecuteMethod(); break;
        }
   }
   timeEndPeriod(1);
   CloseHandle(hTimer);
   CloseHandle(hThread);
   CloseHandle(hProcess);
}


问:
Exclude rows from data.frame depending on a subset of the data.frame
I have the following simulated data.frame:

(please note that I have re-written large portions of the question, reflecting akrun's answer to my initial question)

```<code>set.seed(22)
df <- data.frame(f1 = rep("a", 20), f2 = factor(sample(c("yes", "no", "maybe", "maybenot"), 20, replace = T)), f3 = factor(sample(c("yes", "no"), 20, replace = T)), f4 = factor(sample(c("yes", "no"), 20, replace = T)))

   f1       f2  f3  f4
1   a    maybe yes yes
2   a       no yes yes
3   a      yes  no  no
4   a    maybe yes  no
5   a    maybe  no yes
6   a maybenot  no yes
...
</code>```

I would like to exclude all rows that do not show a yes in df$f2, and show a noin either df$f3, or df$f4. If I would manually transform the values into 0s and 1 (0 for everything except yesin df$f2), I could use rowSums as suggested by akrun. My current solution is to introduce a dummy column called df$exclude as follows and then to subset on df$exclude:

```<code>df$exclude <- "no"
df[df$f2 != "yes" | df$f3 == "no" | df$f4 == "no",]$exclude <- "yes"
df <- subset(df, exclude == "no")
</code>```

Can't this be accomplished more concisely, e.g. without a prior transformation of the columns f2, f3, and f3, or by using lapply (somehow combined with subset, and possibly an anonymous function)?

Thanks in advance for your answers.

答:
If we need to exclude rows that have 0 values for 'f2', 'f3' and 'f4', just do a rowSums to create a logical vector and subset the dataset

```<code>subset(df, rowSums(df[2:4]!=0) != 0)
</code>```

Update

Based on the update in the OP's post

```<code>df[!rowSums(df[2:4] != "yes"),]
</code>```

Body:
I have the following simulated data.frame:

(please note that I have re-written large portions of the question, reflecting akrun's answer to my initial question)

set.seed(22)
df <- data.frame(f1 = rep("a", 20), f2 = factor(sample(c("yes", "no", "maybe", "maybenot"), 20, replace = T)), f3 = factor(sample(c("yes", "no"), 20, replace = T)), f4 = factor(sample(c("yes", "no"), 20, replace = T)))

   f1       f2  f3  f4
1   a    maybe yes yes
2   a       no yes yes
3   a      yes  no  no
4   a    maybe yes  no
5   a    maybe  no yes
6   a maybenot  no yes
...

I would like to exclude all rows that do not show a yes in df$f2, and show a noin either df$f3, or df$f4. If I would manually transform the values into 0s and 1 (0 for everything except yesin df$f2), I could use rowSums as suggested by akrun. My current solution is to introduce a dummy column called df$exclude as follows and then to subset on df$exclude:

df$exclude <- "no"
df[df$f2 != "yes" | df$f3 == "no" | df$f4 == "no",]$exclude <- "yes"
df <- subset(df, exclude == "no")

Can't this be accomplished more concisely, e.g. without a prior transformation of the columns f2, f3, and f3, or by using lapply (somehow combined with subset, and possibly an anonymous function)?

Thanks in advance for your answers.

Body:
If we need to exclude rows that have 0 values for 'f2', 'f3' and 'f4', just do a rowSums to create a logical vector and subset the dataset

subset(df, rowSums(df[2:4]!=0) != 0)

Update

Based on the update in the OP's post

df[!rowSums(df[2:4] != "yes"),]


问:
Field error while using redux form in React js
I was trying to do some form validations in react js , while Using redux form am facing one error Field must be inside a component decorated with reduxForm() .
i just searched for this error on web but didn't get any solution for that .
Reference Link : http://redux-form.com/6.8.0/examples/simple/ .
Here is my code ,

import React, { Component } from 'react';
import { Field, reduxForm } from 'redux-form';

export class EditProfile extends Component {
  render() {
    console.log("hello welcome");
    const { handleSubmit, pristine, reset, submitting } = this.props;
    return (
      <form onSubmit={handleSubmit}>

          First Name
          <Field name="firstName" component="input" type="text"/>

      </form>
    );
  }
}

export default reduxForm({
  form: 'editForm'
})(EditProfile)```

What i did wrong in my code , can someone clarify me .

答:
You have both default export (which is decorated with reduxForm) and named export (not decorated).

I'm assuming you're importing your form like this:

```<code>import { EditProfile } from 'EditForm'; // Using named export
</code>```

Instead you need to import the default one:

```<code>import EditProfile from 'EditForm'; // Default export
</code>```

Technically there's no error, and babel doesn't complain as you're exporting both from the same file. And in some cases it makes sense to export both (e.g. export undecorated one for testing purposes). But in my work I prefer to have only one default export to prevent shooting myself in the foot.

Body:
I was trying to do some form validations in react js , while Using redux form am facing one error Field must be inside a component decorated with reduxForm() .
i just searched for this error on web but didn't get any solution for that .
Reference Link : http://redux-form.com/6.8.0/examples/simple/ .
Here is my code ,

import React, { Component } from 'react';
import { Field, reduxForm } from 'redux-form';

export class EditProfile extends Component {
  render() {
    console.log("hello welcome");
    const { handleSubmit, pristine, reset, submitting } = this.props;
    return (
      <form onSubmit={handleSubmit}>

          First Name
          <Field name="firstName" component="input" type="text"/>

      </form>
    );
  }
}

export default reduxForm({
  form: 'editForm'
})(EditProfile)

What i did wrong in my code , can someone clarify me .

Body:
You have both default export (which is decorated with reduxForm) and named export (not decorated).

I'm assuming you're importing your form like this:

import { EditProfile } from 'EditForm'; // Using named export

Instead you need to import the default one:

import EditProfile from 'EditForm'; // Default export

Technically there's no error, and babel doesn't complain as you're exporting both from the same file. And in some cases it makes sense to export both (e.g. export undecorated one for testing purposes). But in my work I prefer to have only one default export to prevent shooting myself in the foot.


问:
High FPS Camera for OpenCV
I'm tracking an object which I expect to move at a maximum speed of 10m/s using its colour.

I'm having a hard time finding a camera which will work at around 200fps. I'll be using a very low resolution (640x360) for faster processing. Can someone point me in the right direction?

Edit: This is the only one I've found so far and I'm not convinced it supports live streaming. Sony Action Cam AS100V (H.264 - 800 x 480 - 240 fps) - https://www.cnet.com/products/sony-action-cam-as100v/specs/

答:
This is more of a hardware problem, and, probably, it is somewhat misfit to StackOverflow (meaning that you could probably get more answers somewhere like Photography SE). Unfortunately, you didn't mention your requirements for tracking accuracy, the scale of the scene and so on, so it is hard to suggest an algorithmic workaround (e.g. usage of a low-fps camera and interpolating the object's location between the frame gaps).

Having said that, you could consider Basler industrial cameras. Namely, take a look at their ace series which include cameras with crazy framerates like 203 fps, 376 fps, 511 fps, and even 751 fps. Note the interfaces they use (USB 3.0, GigE, Camera Link). You will also need to buy lens for them separately. There is a tool on their website to select the right focal length of lenses based on camera and shooting distance.

While the acquired camera solution will be solid, you will need to take care of the hardware issues (such as interfaces), and, surely, pay a higher price than for a common webcam.  On the other hand, I don't think the required fps can be found among common webcams.

Title: High FPS Camera for OpenCV


问:
How to easily import multiple sql files into a MySQL database?
I have several sql files and I want to import all of them at once into a MySQL database.

I go to PHPMyAdmin, access the database, click import, select a file and import it. When I have more than a couple of files it takes a long time.

I would like to know if there is a better way to import multiple files, something like one file which will import the other files or similar.

I'm using WAMP and I would like a solution that does not require installing additional programs on my computer.

答:
Save this file as .bat and run it  , change variables inside parenthesis ...

```<code>@echo off
title Mysql Import Script
cd (Folder Name)
 for %%a in (*) do (
     echo Importing File  : %%a
     mysql -u(username) -p(password)  %%~na < %%a
)
pause
</code>```

if it's only one database modify (%%~na) with the database name .

ContentLicense: CC BY-SA 4.0

Body:
Save this file as .bat and run it  , change variables inside parenthesis ...

@echo off
title Mysql Import Script
cd (Folder Name)
 for %%a in (*) do (
     echo Importing File  : %%a
     mysql -u(username) -p(password)  %%~na < %%a
)
pause

if it's only one database modify (%%~na) with the database name .


问:
When I git commit some code, it prompts some errors as follows, what's wrong?

And the code management system that I used is Gerrit.

答:
Your $EDITOR is set to mate -w and, apparently, it can't be found at this time. Git tries to open your editor so that you can provide the commit message.

You can pass the message using -m option, as is mentioned in the error message.

```<code> git commit --amend -a -m "my message"
</code>```

Body:
Your $EDITOR is set to mate -w and, apparently, it can't be found at this time. Git tries to open your editor so that you can provide the commit message.

You can pass the message using -m option, as is mentioned in the error message.

 git commit --amend -a -m "my message"


问:
Creating Table from dictionary in SQLAlchemy
I'm trying to create a table from dictionary values in SQLAlchemy. I'm using Flask, and currently my class looks like this:

```<code>class Machine(db.Model):
    """Template for the Machine Info table"""
    __tablename__ = 'machine'
    id = db.Column(db.Integer, primary_key=True)
    machine_name = db.Column(db.String(32))
    date = db.Column(db.String(32))
    time = db.Column(db.String(32))
    sensor1 = db.Column(db.String(32))
    sensor2 = db.Column(db.String(32))
</code>```

This works fine, but my issue is that I will eventually have many columns in this table, possibly +100. I would rather not fill up my models.py file with 100 lines of this kind of stuff. I wanted to have it in its own dictionary in its own file, the dictionary looks like this:

```<code>SENSOR_LOOKUP_DICT = {
    "machine_name":"machine_name",
    "date":"date",
    "time":"time",
    "sensor1":"sensor1",
    "sensor2":"sensor2"
}
</code>```

A list would probably work here too.

I was thinking I could use some kind of loop, like this:

```<code>class Machine(db.Model):
    """Template for the Machine Info table"""
    __tablename__ = 'machine'
    id = db.Column(db.Integer, primary_key=True)
    for sensor in SENSOR_LOOKUP_DICT:
        sensor = db.Column(db.String(32))
</code>```

But this just gives me a column called sensor. I found a couple sort of relevant questions with sqlalchemy but they didn't use this structure for creating tables. I would very much prefer a method if possible that continues to use the db.Model structure, rather than a structure that uses create_engine, due to some JSON serialization later which is easier with this structure (as well as some app structure stuff). Is there any way to do this?

答:
Instead of cramming all the sensor values in to a single row of hundred or more columns, you could split your design to machine and sensor tables:

```<code>from datetime import datetime

from sqlalchemy.orm.collections import attribute_mapped_collection
from sqlalchemy.ext.associationproxy import association_proxy

class Machine(db.Model):
    """The Machine Info table"""
    __tablename__ = 'machine'
    id = db.Column(db.Integer, primary_key=True)
    machine_name = db.Column(db.String(32))
    datetime = db.Column(db.DateTime, default=datetime.utcnow)
    sensors = db.relationship(
        'Sensor',
        collection_class=attribute_mapped_collection('name'),
        cascade='all, delete-orphan')
    sensor_values = association_proxy(
        'sensors', 'value',
        creator=lambda k, v: Sensor(name=k, value=v))

class Sensor(db.Model):
    """The Sensor table"""
    __tablename__ = 'sensor'
    machine_id = db.Column(db.Integer, db.ForeignKey('machine.id'),
                           primary_key=True)
    # Note that this could be a numeric ID as well
    name = db.Column(db.String(16), primary_key=True)
    value = db.Column(db.String(32))
</code>```

The dictionary collection relationship combined with the association proxy allow you to handle the sensor values like so:

```<code>In [10]: m = Machine(machine_name='Steam Machine')

In [11]: m.sensor_values['sensor1'] = 'some interesting value'

In [12]: db.session.add(m)

In [13]: db.session.commit()

In [14]: m.sensor_values
Out[14]: {'sensor1': 'some interesting value'}

In [16]: m.sensor_values['sensor1']
Out[16]: 'some interesting value'
</code>```

An added benefit of having separate tables instead of a fixed schema is that if you add sensors later in life, you don't need to migrate your schema to accommodate that – in other words no need to alter the table to add columns. Just add the new sensor values to the sensor table like before.

Finally, some RDBMS support different kinds of document types, such as Postgresql's hstore, json, and jsonb columns that you could use, since the sensor table is essentially a key/value store.

Body:
I'm trying to create a table from dictionary values in SQLAlchemy. I'm using Flask, and currently my class looks like this:

class Machine(db.Model):
    """Template for the Machine Info table"""
    __tablename__ = 'machine'
    id = db.Column(db.Integer, primary_key=True)
    machine_name = db.Column(db.String(32))
    date = db.Column(db.String(32))
    time = db.Column(db.String(32))
    sensor1 = db.Column(db.String(32))
    sensor2 = db.Column(db.String(32))

This works fine, but my issue is that I will eventually have many columns in this table, possibly +100. I would rather not fill up my models.py file with 100 lines of this kind of stuff. I wanted to have it in its own dictionary in its own file, the dictionary looks like this:

SENSOR_LOOKUP_DICT = {
    "machine_name":"machine_name",
    "date":"date",
    "time":"time",
    "sensor1":"sensor1",
    "sensor2":"sensor2"
}

A list would probably work here too.

I was thinking I could use some kind of loop, like this:

class Machine(db.Model):
    """Template for the Machine Info table"""
    __tablename__ = 'machine'
    id = db.Column(db.Integer, primary_key=True)
    for sensor in SENSOR_LOOKUP_DICT:
        sensor = db.Column(db.String(32))

But this just gives me a column called sensor. I found a couple sort of relevant questions with sqlalchemy but they didn't use this structure for creating tables. I would very much prefer a method if possible that continues to use the db.Model structure, rather than a structure that uses create_engine, due to some JSON serialization later which is easier with this structure (as well as some app structure stuff). Is there any way to do this?

Body:
Instead of cramming all the sensor values in to a single row of hundred or more columns, you could split your design to machine and sensor tables:

from datetime import datetime

from sqlalchemy.orm.collections import attribute_mapped_collection
from sqlalchemy.ext.associationproxy import association_proxy

class Machine(db.Model):
    """The Machine Info table"""
    __tablename__ = 'machine'
    id = db.Column(db.Integer, primary_key=True)
    machine_name = db.Column(db.String(32))
    datetime = db.Column(db.DateTime, default=datetime.utcnow)
    sensors = db.relationship(
        'Sensor',
        collection_class=attribute_mapped_collection('name'),
        cascade='all, delete-orphan')
    sensor_values = association_proxy(
        'sensors', 'value',
        creator=lambda k, v: Sensor(name=k, value=v))

class Sensor(db.Model):
    """The Sensor table"""
    __tablename__ = 'sensor'
    machine_id = db.Column(db.Integer, db.ForeignKey('machine.id'),
                           primary_key=True)
    # Note that this could be a numeric ID as well
    name = db.Column(db.String(16), primary_key=True)
    value = db.Column(db.String(32))

The dictionary collection relationship combined with the association proxy allow you to handle the sensor values like so:

In [10]: m = Machine(machine_name='Steam Machine')

In [11]: m.sensor_values['sensor1'] = 'some interesting value'

In [12]: db.session.add(m)

In [13]: db.session.commit()

In [14]: m.sensor_values
Out[14]: {'sensor1': 'some interesting value'}

In [16]: m.sensor_values['sensor1']
Out[16]: 'some interesting value'

An added benefit of having separate tables instead of a fixed schema is that if you add sensors later in life, you don't need to migrate your schema to accommodate that – in other words no need to alter the table to add columns. Just add the new sensor values to the sensor table like before.

Finally, some RDBMS support different kinds of document types, such as Postgresql's hstore, json, and jsonb columns that you could use, since the sensor table is essentially a key/value store.


问:
RegEx to close an unclosed tag
I have received some invalid XML data from a poll provider and would like to clean up several unclosed tags before processing.

The data currently looks like this:

```<code><questions>
<question number="1">
<title>What is your name?</title>
<answer>John Doe<answer> <!-- this is the problem -->
</question>
<question number="2">
...
</question>
</code>```

Is there a way with regular expressions to clean this and go ahead and close that <answer> tag?

I have this: "<answer>.*?(?<closingtag><answer>)" to find the occurrences, but how do I do a specific replacement on that <closingtag> named group?

Sorry for this very basic question, but I am struggling a bit with my regex expression.

Thanks,

Hal

答:
Programatic repair of human error in XML validation is asking for trouble.  In the extreme, you might as well undo all XML validation.  Take just one example:

```<code><questions>
<question number="1">
<title>What is your name?</title>
<answer>John Doe<answer>
<!-- this is the problem --> </question> <question number="2"> ... </question>
</code>```

Repair...

```<code><answer>John Doe</answer>
</code>```

Or...

```<code><answer>John</answer><answer> Doe</answer>
</code>```

Or...

```<code><answer>John Doe</answer><answer> </answer>
</code>```

Can you see where this is headed?

Title: RegEx to close an unclosed tag

Body:
I have received some invalid XML data from a poll provider and would like to clean up several unclosed tags before processing.

The data currently looks like this:

<questions>
<question number="1">
<title>What is your name?</title>
<answer>John Doe<answer>
</question>
<question number="2">
...
</question>

Is there a way with regular expressions to clean this and go ahead and close that <answer> tag?

I have this: "<answer>.*?(?<closingtag><answer>)" to find the occurrences, but how do I do a specific replacement on that <closingtag> named group?

Sorry for this very basic question, but I am struggling a bit with my regex expression.

Thanks,

Hal

Body:
Programatic repair of human error in XML validation is asking for trouble.  In the extreme, you might as well undo all XML validation.  Take just one example:

<questions>
<question number="1">
<title>What is your name?</title>
<answer>John Doe<answer>
<!-- this is the problem --> </question> <question number="2"> ... </question>

Repair...

<answer>John Doe</answer>

Or...

<answer>John</answer><answer> Doe</answer>

Or...

<answer>John Doe</answer><answer> </answer>

Can you see where this is headed?


问:
Messages not loading on clicking Firebase notification
I have a created a Firebase application using the tutorial given here. As I am a beginner to Android, please help me solving this. My app has a only one activity.

When I send a message from my Firebase console, I am able to see the message and the toast on screen when the app is open. However, if the app is not running, I am able to see the notification from Firebase in Notifications Bar but on clicking it neither the toast comes or the message gets shown on the screen.
Everything works well only for the very first time the app is installed.
How can I solve this problem? Kindly help. Below are my codes:

Activity_main.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.unss.pramod.firebasetest.activity.MainActivity">

    <TextView
        android:id="@+id/txt_push_message"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="40dp"
        android:gravity="center_horizontal"
        android:textColor="@color/colorPrimary"
        android:textSize="26dp" />

    <TextView
        android:id="@+id/txt_reg_id"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true" />
</RelativeLayout>
</code>```

Main Activity.java

```<code>public class MainActivity extends AppCompatActivity {

    private static final String TAG = MainActivity.class.getSimpleName();
    private BroadcastReceiver mRegistrationBroadcastReceiver;
    private TextView txtRegId, txtMessage;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        txtRegId = (TextView) findViewById(R.id.txt_reg_id);
        txtMessage = (TextView) findViewById(R.id.txt_push_message);

        mRegistrationBroadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {

                // checking for type intent filter
                if (intent.getAction().equals(Config.REGISTRATION_COMPLETE)) {
                    // gcm successfully registered
                    // now subscribe to `global` topic to receive app wide notifications
                    FirebaseMessaging.getInstance().subscribeToTopic(Config.TOPIC_GLOBAL);

                    displayFirebaseRegId();

                } else if (intent.getAction().equals(Config.PUSH_NOTIFICATION)) {
                    // new push notification is received

                    String message = intent.getStringExtra("message");

                    Toast.makeText(getApplicationContext(), "Push notification: " + message, Toast.LENGTH_LONG).show();

                    txtMessage.setText(message);
                }
            }
        };

        displayFirebaseRegId();
    }

    // Fetches reg id from shared preferences
    // and displays on the screen
    private void displayFirebaseRegId() {
        SharedPreferences pref = getApplicationContext().getSharedPreferences(Config.SHARED_PREF, 0);
        String regId = pref.getString("regId", null);

        Log.e(TAG, "Firebase reg id: " + regId);

        if (!TextUtils.isEmpty(regId))
            txtRegId.setText("Firebase Reg Id: " + regId);
        else
            txtRegId.setText("Firebase Reg Id is not received yet!");
    }

    @Override
    protected void onResume() {
        super.onResume();

        // register GCM registration complete receiver
        LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
                new IntentFilter(Config.REGISTRATION_COMPLETE));

        // register new push message receiver
        // by doing this, the activity will be notified each time a new message arrives
        LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
                new IntentFilter(Config.PUSH_NOTIFICATION));

        // clear the notification area when the app is opened
        NotificationUtils.clearNotifications(getApplicationContext());
    }

    @Override
    protected void onPause() {
        LocalBroadcastManager.getInstance(this).unregisterReceiver(mRegistrationBroadcastReceiver);
        super.onPause();
    }
}
</code>```

Firebase Instance ID service.java

```<code>public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
    private static final String TAG = MyFirebaseInstanceIDService.class.getSimpleName();

    @Override
    public void onTokenRefresh() {
        super.onTokenRefresh();
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();

        // Saving reg id to shared preferences
        storeRegIdInPref(refreshedToken);

        // sending reg id to your server
        sendRegistrationToServer(refreshedToken);

        // Notify UI that registration has completed, so the progress indicator can be hidden.
        Intent registrationComplete = new Intent(Config.REGISTRATION_COMPLETE);
        registrationComplete.putExtra("token", refreshedToken);
        LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete);
    }

    private void sendRegistrationToServer(final String token) {
        // sending gcm token to server
        Log.e(TAG, "sendRegistrationToServer: " + token);
    }

    private void storeRegIdInPref(String token) {
        SharedPreferences pref = getApplicationContext().getSharedPreferences(Config.SHARED_PREF, 0);
        SharedPreferences.Editor editor = pref.edit();
        editor.putString("regId", token);
        editor.commit();
    }
}
</code>```

Firebase messaging service.java

```<code>public class MyFirebaseMessagingService extends FirebaseMessagingService {

    private static final String TAG = MyFirebaseMessagingService.class.getSimpleName();

    private NotificationUtils notificationUtils;

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        Log.e(TAG, "From: " + remoteMessage.getFrom());

        if (remoteMessage == null)
            return;

        // Check if message contains a notification payload.
        if (remoteMessage.getNotification() != null) {
            Log.e(TAG, "Notification Body: " + remoteMessage.getNotification().getBody());
            handleNotification(remoteMessage.getNotification().getBody());
        }

        // Check if message contains a data payload.
        if (remoteMessage.getData().size() > 0) {
            Log.e(TAG, "Data Payload: " + remoteMessage.getData().toString());

            try {
                JSONObject json = new JSONObject(remoteMessage.getData().toString());
                handleDataMessage(json);
            } catch (Exception e) {
                Log.e(TAG, "Exception: " + e.getMessage());
            }
        }
    }

    private void handleNotification(String message) {
        if (!NotificationUtils.isAppIsInBackground(getApplicationContext())) {
            // app is in foreground, broadcast the push message
            Intent pushNotification = new Intent(Config.PUSH_NOTIFICATION);
            pushNotification.putExtra("message", message);
            LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);

            // play notification sound
            NotificationUtils notificationUtils = new NotificationUtils(getApplicationContext());
            notificationUtils.playNotificationSound();
        }else{
            // If the app is in background, firebase itself handles the notification
        }
    }

    private void handleDataMessage(JSONObject json) {
        Log.e(TAG, "push json: " + json.toString());

        try {
            JSONObject data = json.getJSONObject("data");

            String title = data.getString("title");
            String message = data.getString("message");
            boolean isBackground = data.getBoolean("is_background");
            String imageUrl = data.getString("image");
            String timestamp = data.getString("timestamp");
            JSONObject payload = data.getJSONObject("payload");

            Log.e(TAG, "title: " + title);
            Log.e(TAG, "message: " + message);
            Log.e(TAG, "isBackground: " + isBackground);
            Log.e(TAG, "payload: " + payload.toString());
            Log.e(TAG, "imageUrl: " + imageUrl);
            Log.e(TAG, "timestamp: " + timestamp);

            if (!NotificationUtils.isAppIsInBackground(getApplicationContext())) {
                // app is in foreground, broadcast the push message
                Intent pushNotification = new Intent(Config.PUSH_NOTIFICATION);
                pushNotification.putExtra("message", message);
                LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);

                // play notification sound
                NotificationUtils notificationUtils = new NotificationUtils(getApplicationContext());
                notificationUtils.playNotificationSound();
            } else {
                // app is in background, show the notification in notification tray
                Intent resultIntent = new Intent(getApplicationContext(), MainActivity.class);
                resultIntent.putExtra("message", message);

                // check for image attachment
                if (TextUtils.isEmpty(imageUrl)) {
                    showNotificationMessage(getApplicationContext(), title, message, timestamp, resultIntent);
                } else {
                    // image is present, show notification with image
                    showNotificationMessageWithBigImage(getApplicationContext(), title, message, timestamp, resultIntent, imageUrl);
                }
            }
        } catch (JSONException e) {
            Log.e(TAG, "Json Exception: " + e.getMessage());
        } catch (Exception e) {
            Log.e(TAG, "Exception: " + e.getMessage());
        }
    }

    /**
     * Showing notification with text only
     */
    private void showNotificationMessage(Context context, String title, String message, String timeStamp, Intent intent) {
        notificationUtils = new NotificationUtils(context);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        notificationUtils.showNotificationMessage(title, message, timeStamp, intent);
    }

    /**
     * Showing notification with text and image
     */
    private void showNotificationMessageWithBigImage(Context context, String title, String message, String timeStamp, Intent intent, String imageUrl) {
        notificationUtils = new NotificationUtils(context);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        notificationUtils.showNotificationMessage(title, message, timeStamp, intent, imageUrl);
    }
}
</code>```

Config.java

```<code>public class Config {

    // global topic to receive app wide push notifications
    public static final String TOPIC_GLOBAL = "global";

    // broadcast receiver intent filters
    public static final String REGISTRATION_COMPLETE = "registrationComplete";
    public static final String PUSH_NOTIFICATION = "pushNotification";

    // id to handle the notification in the notification tray
    public static final int NOTIFICATION_ID = 100;
    public static final int NOTIFICATION_ID_BIG_IMAGE = 101;

    public static final String SHARED_PREF = "ah_firebase";
}
</code>```

Kindly help in solving this problem.

答:
For notifications to be clickable when your app is in the background, you need the click_action attribute in your notification payload.

Please check this section of the Firebase docs.

Also, when you define the click_action attribute, you will also need a corresponding <action> attribute in the <intent-filter> of the activity that you wish to launch.

This video explains it in quite a detailed manner.

Though, please note that you can not set the click__action attribute if you're sending notifications from the Firebase Console. You can only do so if you send a notification from your own Admin server or using Firebase Cloud Functions.

Lastly, in the activity that is launched, you can set additional Data using the data attribute ( also shown in the same doc that I linked above ). And when you launch your app by clicking on a notification, you can  obtain the notification data using getIntent(). Check out this answer for more details on how to do that.

Body:
I have a created a Firebase application using the tutorial given here. As I am a beginner to Android, please help me solving this. My app has a only one activity.

When I send a message from my Firebase console, I am able to see the message and the toast on screen when the app is open. However, if the app is not running, I am able to see the notification from Firebase in Notifications Bar but on clicking it neither the toast comes or the message gets shown on the screen.
Everything works well only for the very first time the app is installed.
How can I solve this problem? Kindly help. Below are my codes:

Activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.unss.pramod.firebasetest.activity.MainActivity">

    <TextView
        android:id="@+id/txt_push_message"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="40dp"
        android:gravity="center_horizontal"
        android:textColor="@color/colorPrimary"
        android:textSize="26dp" />

    <TextView
        android:id="@+id/txt_reg_id"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true" />
</RelativeLayout>

Main Activity.java

public class MainActivity extends AppCompatActivity {

    private static final String TAG = MainActivity.class.getSimpleName();
    private BroadcastReceiver mRegistrationBroadcastReceiver;
    private TextView txtRegId, txtMessage;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        txtRegId = (TextView) findViewById(R.id.txt_reg_id);
        txtMessage = (TextView) findViewById(R.id.txt_push_message);

        mRegistrationBroadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {

                // checking for type intent filter
                if (intent.getAction().equals(Config.REGISTRATION_COMPLETE)) {
                    // gcm successfully registered
                    // now subscribe to `global` topic to receive app wide notifications
                    FirebaseMessaging.getInstance().subscribeToTopic(Config.TOPIC_GLOBAL);

                    displayFirebaseRegId();

                } else if (intent.getAction().equals(Config.PUSH_NOTIFICATION)) {
                    // new push notification is received

                    String message = intent.getStringExtra("message");

                    Toast.makeText(getApplicationContext(), "Push notification: " + message, Toast.LENGTH_LONG).show();

                    txtMessage.setText(message);
                }
            }
        };

        displayFirebaseRegId();
    }

    // Fetches reg id from shared preferences
    // and displays on the screen
    private void displayFirebaseRegId() {
        SharedPreferences pref = getApplicationContext().getSharedPreferences(Config.SHARED_PREF, 0);
        String regId = pref.getString("regId", null);

        Log.e(TAG, "Firebase reg id: " + regId);

        if (!TextUtils.isEmpty(regId))
            txtRegId.setText("Firebase Reg Id: " + regId);
        else
            txtRegId.setText("Firebase Reg Id is not received yet!");
    }

    @Override
    protected void onResume() {
        super.onResume();

        // register GCM registration complete receiver
        LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
                new IntentFilter(Config.REGISTRATION_COMPLETE));

        // register new push message receiver
        // by doing this, the activity will be notified each time a new message arrives
        LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
                new IntentFilter(Config.PUSH_NOTIFICATION));

        // clear the notification area when the app is opened
        NotificationUtils.clearNotifications(getApplicationContext());
    }

    @Override
    protected void onPause() {
        LocalBroadcastManager.getInstance(this).unregisterReceiver(mRegistrationBroadcastReceiver);
        super.onPause();
    }
}

Firebase Instance ID service.java

public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
    private static final String TAG = MyFirebaseInstanceIDService.class.getSimpleName();

    @Override
    public void onTokenRefresh() {
        super.onTokenRefresh();
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();

        // Saving reg id to shared preferences
        storeRegIdInPref(refreshedToken);

        // sending reg id to your server
        sendRegistrationToServer(refreshedToken);

        // Notify UI that registration has completed, so the progress indicator can be hidden.
        Intent registrationComplete = new Intent(Config.REGISTRATION_COMPLETE);
        registrationComplete.putExtra("token", refreshedToken);
        LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete);
    }

    private void sendRegistrationToServer(final String token) {
        // sending gcm token to server
        Log.e(TAG, "sendRegistrationToServer: " + token);
    }

    private void storeRegIdInPref(String token) {
        SharedPreferences pref = getApplicationContext().getSharedPreferences(Config.SHARED_PREF, 0);
        SharedPreferences.Editor editor = pref.edit();
        editor.putString("regId", token);
        editor.commit();
    }
}

Firebase messaging service.java

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    private static final String TAG = MyFirebaseMessagingService.class.getSimpleName();

    private NotificationUtils notificationUtils;

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        Log.e(TAG, "From: " + remoteMessage.getFrom());

        if (remoteMessage == null)
            return;

        // Check if message contains a notification payload.
        if (remoteMessage.getNotification() != null) {
            Log.e(TAG, "Notification Body: " + remoteMessage.getNotification().getBody());
            handleNotification(remoteMessage.getNotification().getBody());
        }

        // Check if message contains a data payload.
        if (remoteMessage.getData().size() > 0) {
            Log.e(TAG, "Data Payload: " + remoteMessage.getData().toString());

            try {
                JSONObject json = new JSONObject(remoteMessage.getData().toString());
                handleDataMessage(json);
            } catch (Exception e) {
                Log.e(TAG, "Exception: " + e.getMessage());
            }
        }
    }

    private void handleNotification(String message) {
        if (!NotificationUtils.isAppIsInBackground(getApplicationContext())) {
            // app is in foreground, broadcast the push message
            Intent pushNotification = new Intent(Config.PUSH_NOTIFICATION);
            pushNotification.putExtra("message", message);
            LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);

            // play notification sound
            NotificationUtils notificationUtils = new NotificationUtils(getApplicationContext());
            notificationUtils.playNotificationSound();
        }else{
            // If the app is in background, firebase itself handles the notification
        }
    }

    private void handleDataMessage(JSONObject json) {
        Log.e(TAG, "push json: " + json.toString());

        try {
            JSONObject data = json.getJSONObject("data");

            String title = data.getString("title");
            String message = data.getString("message");
            boolean isBackground = data.getBoolean("is_background");
            String imageUrl = data.getString("image");
            String timestamp = data.getString("timestamp");
            JSONObject payload = data.getJSONObject("payload");

            Log.e(TAG, "title: " + title);
            Log.e(TAG, "message: " + message);
            Log.e(TAG, "isBackground: " + isBackground);
            Log.e(TAG, "payload: " + payload.toString());
            Log.e(TAG, "imageUrl: " + imageUrl);
            Log.e(TAG, "timestamp: " + timestamp);

            if (!NotificationUtils.isAppIsInBackground(getApplicationContext())) {
                // app is in foreground, broadcast the push message
                Intent pushNotification = new Intent(Config.PUSH_NOTIFICATION);
                pushNotification.putExtra("message", message);
                LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);

                // play notification sound
                NotificationUtils notificationUtils = new NotificationUtils(getApplicationContext());
                notificationUtils.playNotificationSound();
            } else {
                // app is in background, show the notification in notification tray
                Intent resultIntent = new Intent(getApplicationContext(), MainActivity.class);
                resultIntent.putExtra("message", message);

                // check for image attachment
                if (TextUtils.isEmpty(imageUrl)) {
                    showNotificationMessage(getApplicationContext(), title, message, timestamp, resultIntent);
                } else {
                    // image is present, show notification with image
                    showNotificationMessageWithBigImage(getApplicationContext(), title, message, timestamp, resultIntent, imageUrl);
                }
            }
        } catch (JSONException e) {
            Log.e(TAG, "Json Exception: " + e.getMessage());
        } catch (Exception e) {
            Log.e(TAG, "Exception: " + e.getMessage());
        }
    }

    /**
     * Showing notification with text only
     */
    private void showNotificationMessage(Context context, String title, String message, String timeStamp, Intent intent) {
        notificationUtils = new NotificationUtils(context);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        notificationUtils.showNotificationMessage(title, message, timeStamp, intent);
    }

    /**
     * Showing notification with text and image
     */
    private void showNotificationMessageWithBigImage(Context context, String title, String message, String timeStamp, Intent intent, String imageUrl) {
        notificationUtils = new NotificationUtils(context);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        notificationUtils.showNotificationMessage(title, message, timeStamp, intent, imageUrl);
    }
}

Config.java

public class Config {

    // global topic to receive app wide push notifications
    public static final String TOPIC_GLOBAL = "global";

    // broadcast receiver intent filters
    public static final String REGISTRATION_COMPLETE = "registrationComplete";
    public static final String PUSH_NOTIFICATION = "pushNotification";

    // id to handle the notification in the notification tray
    public static final int NOTIFICATION_ID = 100;
    public static final int NOTIFICATION_ID_BIG_IMAGE = 101;

    public static final String SHARED_PREF = "ah_firebase";
}

Kindly help in solving this problem.


问:
Predicate inside a Where<> query not hit?
I need to call the method for each item in the list. So, I have used Where<> query as follows,

```<code>List<string> list = new List<string>();
list.Add("Name1");
list.Add("Name2");
list.Add("Name3");

var name = list.Where(n =>
{
    return CheckName(n);
});
</code>```

But in the above case, CheckName() is not hit. The same method is triggered if I use FirstOrDefault<>. I don't know whether it is a framework break or I am going in a wrong way.

As additional info, I am using.NET Framework 4.5.

Has anyone experienced this error? If so, is there any solution to overcome this issue?

答:
You are understanding incorrectly the result of the Where condition. As linq is deffered executed it will only enter the where condition when materialized (by a ToList/FirstOrDefault/Sum and such).

The Where is never actually materialized in your current code (It did as you experienced when using FirstOrDefault) and as such it will never enter the CheckName method. Then, as Where will never return null but "worst case" an empty collection, which is not null, the result is true.

If you debug you will see that name equals true at the end of this. To "overcome" this depends on what is your desired output:

If you want to know if you have any item that matched the predicate then:

```<code>var result = list.Any(CheckName);
</code>```

If you want to retrieve those that match the predicate:

```<code>var result = list.Where(CheckName);
</code>```

If later you want to query and check if results contains anything then:

```<code>if(result.Any()) { /* ... */ }
</code>```

If you only want the results (and thus materializing the query):

```<code>list.Where(CheckName).ToList();
</code>```

Read more about linq being deffered executed here:

Linq and deffered execution

What are the benefits of a Deferred Execution in LINQ?

Just as a side note see how you can change your current code from:

```<code>var name = list.Where(n =>
{
    return CheckName(n);
})
</code>```

To:

```<code>var name = list.Where(n => CheckName(n));
</code>```

And eventually to:

```<code>var name = list.Where(CheckName);
</code>```

Body:
I need to call the method for each item in the list. So, I have used Where<> query as follows,

List<string> list = new List<string>();
list.Add("Name1");
list.Add("Name2");
list.Add("Name3");

var name = list.Where(n =>
{
    return CheckName(n);
});

But in the above case, CheckName() is not hit. The same method is triggered if I use FirstOrDefault<>. I don't know whether it is a framework break or I am going in a wrong way.

As additional info, I am using.NET Framework 4.5.

Has anyone experienced this error? If so, is there any solution to overcome this issue?

Body:
You are understanding incorrectly the result of the Where condition. As linq is deffered executed it will only enter the where condition when materialized (by a ToList/FirstOrDefault/Sum and such).

The Where is never actually materialized in your current code (It did as you experienced when using FirstOrDefault) and as such it will never enter the CheckName method. Then, as Where will never return null but "worst case" an empty collection, which is not null, the result is true.

If you debug you will see that name equals true at the end of this. To "overcome" this depends on what is your desired output:

If you want to know if you have any item that matched the predicate then:

var result = list.Any(CheckName);

If you want to retrieve those that match the predicate:

var result = list.Where(CheckName);

If later you want to query and check if results contains anything then:

if(result.Any()) { /* ... */ }

If you only want the results (and thus materializing the query):

list.Where(CheckName).ToList();

Read more about linq being deffered executed here:

Linq and deffered execution

What are the benefits of a Deferred Execution in LINQ?

Just as a side note see how you can change your current code from:

var name = list.Where(n =>
{
    return CheckName(n);
})

To:

var name = list.Where(n => CheckName(n));

And eventually to:

var name = list.Where(CheckName);