问:
Portable SQL upsert (insert+update) solution needed
I need to perform a very simple operation on the database - put some values into the table by key, if the row exists - update it, if not - create a new one. The problem is that I need to do it in a portable way - i.e. the same query must work on MySQL, SQL Server, Oracle and preferably also DB2, Postgres, etc. So while I could use REPLACE or INSERT ... ON DUPLICATE KEY UPDATE in MySQL, I'm not sure that these would support such syntax. And I really want to avoid if's by database type, because this would be unmaintainable. I also don't want to actually query the value before updating, because I suspect it would slow down the process significantly (I need to do it multiple times).

So far the best I came up with is just doing:

```<code>  UPDATE table SET data='data' WHERE key='key';
  INSERT INTO table(key, data) VALUES ('key', 'data');
</code>```

one of those would always succeed and another fail, but I don't care that one of the queries fails. It looks kind of inelegant though. Any suggestions how to make it better?

答:
Execute the UPDATE first.  Your client code will be informed as to the number of rows updated.  If the updated row count is zero, then execute the INSERT.

The exact way that the updated row count is returned to your client code depends upon which database access library you are using.  For example, in Java it is the return value of PreparedStatement.executeUpdate() and in the Python DB-API it is accessed using cursor.rowcount.

You will need to make sure that the whole process takes place within a serializable transaction to avoid conflicts with concurrent writers.

Body:
I need to perform a very simple operation on the database - put some values into the table by key, if the row exists - update it, if not - create a new one. The problem is that I need to do it in a portable way - i.e. the same query must work on MySQL, SQL Server, Oracle and preferably also DB2, Postgres, etc. So while I could use REPLACE or INSERT ... ON DUPLICATE KEY UPDATE in MySQL, I'm not sure that these would support such syntax. And I really want to avoid if's by database type, because this would be unmaintainable. I also don't want to actually query the value before updating, because I suspect it would slow down the process significantly (I need to do it multiple times).

So far the best I came up with is just doing:

  UPDATE table SET data='data' WHERE key='key';
  INSERT INTO table(key, data) VALUES ('key', 'data');

one of those would always succeed and another fail, but I don't care that one of the queries fails. It looks kind of inelegant though. Any suggestions how to make it better?


来源: stackexchange

问:
Navigation bar hidden after initialize ViewController with identifier
I'm ultimating a chat into my app but i still have this issue. As you can see i have a ChatListTableViewController with the list of all the active chats(picture 1, top-left view). When i click on a cell i successfully open che ChatViewController with the NavBar displaying the name of the person whom i chat with ,the back arrow and a trash button to delete the chat. However, in the ChatListTableViewController i have  a "+" button (picture 1, top-left) which opens a PopUpViewController: this one allows you to start a new chat with a user,chosen from a TableView. The issue as you can see from picture 1 ,is that when i click on a cell in the PopUpChatListViewController, i try to initialize a ChatViewController and it opens but the NavigationBar is hidden.This is done by using the function "didSelectRowAt" of the TableView. I post you the code of the PopUpChatListViewController. In the viewDidLoad of the ChatViewController i tryied to put set "navigationBar.isHidden = false " but nothing. Can you explain me what's happening here ?

```<code>import UIKit

class PopUpChatListViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    @IBOutlet var tableView: UITableView!

    public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        return userName.count
    }

    public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
        let cell = tableView.dequeueReusableCell(withIdentifier: "cellPopUp", for: indexPath)
        cell.textLabel?.text = userName[indexPath.row]
        return cell
    }

    public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        UserDefaults.standard.set(userID[indexPath.row], forKey: "chatID")
        let vc = self.storyboard?.instantiateViewController(withIdentifier: "ChatActivity") as! ChatViewController
        self.present(vc, animated: true, completion: nil)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.black.withAlphaComponent(0.6)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}
</code>```

VIEW OF THE SCREENSHOTS RUNNING APP:

MAIN STORYBOARD SCHEME:

答:
If you want to use push segue, check the answer of @Leo Valentim. And my answer is for you if you still want to use modal segue.

Change this code:

```<code>public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    UserDefaults.standard.set(userID[indexPath.row], forKey: "chatID")

    let vc = self.storyboard?.instantiateViewController(withIdentifier: "ChatActivity") as! ChatViewController

    self.present(vc, animated: true, completion: nil)
}
</code>```

To:

```<code>public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    UserDefaults.standard.set(userID[indexPath.row], forKey: "chatID")

    let vc = self.storyboard?.instantiateViewController(withIdentifier: "ChatActivity") as! ChatViewController
    let navigationController = UINavigationController()
    navigationController.viewControllers = [vc]

    self.present(navigationController, animated: true, completion: nil)
}
</code>```

You can refer to this question: Modal segue, navigation bar disappears

And here: Using Segues (Pay attention to Table 9-1 Adaptive segue types, it includes the segue types and behavior of each type)

ContentLicense: CC BY-SA 3.0

Body:
I'm ultimating a chat into my app but i still have this issue. As you can see i have a ChatListTableViewController with the list of all the active chats(picture 1, top-left view). When i click on a cell i successfully open che ChatViewController with the NavBar displaying the name of the person whom i chat with ,the back arrow and a trash button to delete the chat. However, in the ChatListTableViewController i have  a "+" button (picture 1, top-left) which opens a PopUpViewController: this one allows you to start a new chat with a user,chosen from a TableView. The issue as you can see from picture 1 ,is that when i click on a cell in the PopUpChatListViewController, i try to initialize a ChatViewController and it opens but the NavigationBar is hidden.This is done by using the function "didSelectRowAt" of the TableView. I post you the code of the PopUpChatListViewController. In the viewDidLoad of the ChatViewController i tryied to put set "navigationBar.isHidden = false " but nothing. Can you explain me what's happening here ?

import UIKit

class PopUpChatListViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    @IBOutlet var tableView: UITableView!

    public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        return userName.count
    }

    public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
        let cell = tableView.dequeueReusableCell(withIdentifier: "cellPopUp", for: indexPath)
        cell.textLabel?.text = userName[indexPath.row]
        return cell
    }

    public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        UserDefaults.standard.set(userID[indexPath.row], forKey: "chatID")
        let vc = self.storyboard?.instantiateViewController(withIdentifier: "ChatActivity") as! ChatViewController
        self.present(vc, animated: true, completion: nil)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.black.withAlphaComponent(0.6)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

VIEW OF THE SCREENSHOTS RUNNING APP:

MAIN STORYBOARD SCHEME:

Body:
If you want to use push segue, check the answer of @Leo Valentim. And my answer is for you if you still want to use modal segue.

Change this code:

public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    UserDefaults.standard.set(userID[indexPath.row], forKey: "chatID")

    let vc = self.storyboard?.instantiateViewController(withIdentifier: "ChatActivity") as! ChatViewController

    self.present(vc, animated: true, completion: nil)
}

To:

public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    UserDefaults.standard.set(userID[indexPath.row], forKey: "chatID")

    let vc = self.storyboard?.instantiateViewController(withIdentifier: "ChatActivity") as! ChatViewController
    let navigationController = UINavigationController()
    navigationController.viewControllers = [vc]

    self.present(navigationController, animated: true, completion: nil)
}

You can refer to this question: Modal segue, navigation bar disappears

And here: Using Segues (Pay attention to Table 9-1 Adaptive segue types, it includes the segue types and behavior of each type)


问:
Context menu with list view
My code is not showing any Toast.When i long push it shows three menu but when i select any menu like "delete" it does not show Toast, What can I do so that it work. I have tried with answer on this site but not get success. Here is my code.

```<code> package com.example.avinashkumaryadav.menutwo;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Adapter;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
ListView lview;
String[] contact={"Avinash","Golu","Sam","Tom","Ram","Yam"};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    lview=(ListView)findViewById(R.id.linearId) ;
    ArrayAdapter Array=new ArrayAdapter<String>(this,R.layout.linear_view,R.id.linearView,contact);
    lview.setAdapter(Array);
    registerForContextMenu(lview);
}

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);

    menu.setHeaderTitle("Select Action");
    menu.add(0,v.getId(),0,"Love");
    menu.add(0,v.getId(),0,"Edit");
    menu.add(0,v.getId(),0,"delete");
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if(item.getTitle()=="Love") {
        Toast.makeText(MainActivity.this, "Love u too dear", Toast.LENGTH_LONG).show();
    }
    else if(item.getTitle()=="Edit")
    {
        Toast.makeText(getApplicationContext(),"Editable",Toast.LENGTH_SHORT).show();
    }
    else if(item.getTitle()=="delete")
    {
        Toast.makeText(getApplicationContext(),"Can be Deleted",Toast.LENGTH_SHORT).show();
    }
  else
       {
          Toast.makeText(this,"Not clicked right",Toast.LENGTH_SHORT);
       }
       return true;

   }
 }
</code>```

Cany anyone help me please?

答:
Try this :</p>

```<code>@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if(item.getTitle().equals("Love")) {
        Toast.makeText(this, "Love u too dear", Toast.LENGTH_LONG).show();
    }
    else if(item.getTitle().equals("Edit"))
    {
        Toast.makeText(ghis,"Editable",Toast.LENGTH_SHORT).show();
    }
    else if(item.getTitle().equals("delete"))
    {
        Toast.makeText(this,"Can be Deleted",Toast.LENGTH_SHORT).show();
    }
  else
       {
          Toast.makeText(this,"Not clicked right",Toast.LENGTH_SHORT);
       }
       return super.onOptionsItemSelected(item);

   }
</code>```

Title: Context menu with list view

Body:
My code is not showing any Toast.When i long push it shows three menu but when i select any menu like "delete" it does not show Toast, What can I do so that it work. I have tried with answer on this site but not get success. Here is my code.

 package com.example.avinashkumaryadav.menutwo;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Adapter;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
ListView lview;
String[] contact={"Avinash","Golu","Sam","Tom","Ram","Yam"};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    lview=(ListView)findViewById(R.id.linearId) ;
    ArrayAdapter Array=new ArrayAdapter<String>(this,R.layout.linear_view,R.id.linearView,contact);
    lview.setAdapter(Array);
    registerForContextMenu(lview);
}

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);

    menu.setHeaderTitle("Select Action");
    menu.add(0,v.getId(),0,"Love");
    menu.add(0,v.getId(),0,"Edit");
    menu.add(0,v.getId(),0,"delete");
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if(item.getTitle()=="Love") {
        Toast.makeText(MainActivity.this, "Love u too dear", Toast.LENGTH_LONG).show();
    }
    else if(item.getTitle()=="Edit")
    {
        Toast.makeText(getApplicationContext(),"Editable",Toast.LENGTH_SHORT).show();
    }
    else if(item.getTitle()=="delete")
    {
        Toast.makeText(getApplicationContext(),"Can be Deleted",Toast.LENGTH_SHORT).show();
    }
  else
       {
          Toast.makeText(this,"Not clicked right",Toast.LENGTH_SHORT);
       }
       return true;

   }
 }

Cany anyone help me please?

Body:
Try this :

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if(item.getTitle().equals("Love")) {
        Toast.makeText(this, "Love u too dear", Toast.LENGTH_LONG).show();
    }
    else if(item.getTitle().equals("Edit"))
    {
        Toast.makeText(ghis,"Editable",Toast.LENGTH_SHORT).show();
    }
    else if(item.getTitle().equals("delete"))
    {
        Toast.makeText(this,"Can be Deleted",Toast.LENGTH_SHORT).show();
    }
  else
       {
          Toast.makeText(this,"Not clicked right",Toast.LENGTH_SHORT);
       }
       return super.onOptionsItemSelected(item);

   }


问:
Official Filebeat docker running on windows not allowing application to rotate the log
I am using filebeat image - docker.elastic.co/beats/filebeat:5.4.1 to setup filebeat container locally on windows to read logs from an application and send data to logstash. The application which generate logs will rotate it after '1MB' size.

I have set close_inactive = 2M. So that filebeat release the handle after 2 minutes.

When application stops writing data and all the data is read from the file, file handle is released. This is as expected.

My concern is,
- While filebeat container is reading the file, application is not able to rotate the log file after 1MB size.

If i run filebeat as a service (Not inside docker) it works as expected i.e logs are rotated after 1MB.

How can I avoid this ?

Edit: Just for info if it helps, I don't see this issue in linux. Docker filebeat container allow application to rotate the file.

答:
I come to this answer based on the discussion I had with elastic team member at - https://discuss.elastic.co/t/filebeat-docker-running-on-windows-not-allowing-application-to-rotate-the-log/89616/11

This is the response - " VBoxHeadless.exe has the log file open with RW-, I'd say that the shared filesystem used by VirtualBox is to blame. It is not opening the file with FILE_SHARE_DELETE so other applications cannot delete or rename the file."

So its the VirtualBox which is holding the filehandler for the file and not filebeat which is holding the handle.

One suggestion I got is to try Hyper-V driver instead of VirtualBox driver while creating the docker VM on windows.

As i mentioned in my query, it won't happen on linux docker as there is no VM there.


问:
Why is Angularjs responseError interceptor returning a status code of -1
I'd like to be able to handle the 401 status code in my angularjs project. I've attempted several different variations of response interceptors, but all of them return a code of -1. I'd like to understand why this is happening. Using Angularjs v1.5.8.</p>

```<code>myApp.factory('httpResponseInterceptor', function () {
  return {
    responseError: function (config) {
      console.log(config.status);
      //The above prints out -1 to the console
      return config;
    }
  };
});

myApp.config(function ($httpProvider) {
  $httpProvider.interceptors.push('httpResponseInterceptor');
});
</code>```

答:
It is CORS issue, CORS is Cross-Origin Resource Sharing.
You must enable CORS from server side.</p>

Body:
I'd like to be able to handle the 401 status code in my angularjs project. I've attempted several different variations of response interceptors, but all of them return a code of -1. I'd like to understand why this is happening. Using Angularjs v1.5.8.

myApp.factory('httpResponseInterceptor', function () {
  return {
    responseError: function (config) {
      console.log(config.status);
      //The above prints out -1 to the console
      return config;
    }
  };
});

myApp.config(function ($httpProvider) {
  $httpProvider.interceptors.push('httpResponseInterceptor');
});


问:
iPhone: how to connect social networking sites and retrieving user info
hi how to connect to social networking sites(twitter) and retrieving user credencials and posting tweet and viewing number of follower, following etc.can u suggest me.</p>

答:
Here's a tutorial describing how to connect to Twitter in an iPhone app using an existing third party library:

http://mobile.tutsplus.com/tutorials/iphone/twitter-api-iphone/

I found this with a quick Google search, so you may have already come across it. I've used the library referenced in this tutorial, and it's worked fine in the past.

I agree with Robert. Your question doesn't offer many details. I suggest googling around, trying this tutorial and other ones you come across, and then coming back to SO with more specific questions.

Good luck!

ContentLicense: CC BY-SA 2.5


问:
If state is immutable, is the whole state replaced on any change?
If state is immutable wouldn't the whole state need to be replaced on any change? Otherwise, you're mutating the state. Are top-level keys held as separate immutable objects?

By definition wouldn't any change need to replace the whole thing? How is this handled by Redux? Wouldn't replacing the full state break PureComponents?

Thanks for any clarification.

答:
Let's break it down step by step:

There is an initial redux store of { color: 'red' }

The user clicks a button

An action is generated, say CHANGE_COLOR

Redux calls your reducer with the store (from step 1) and the action. The reducer returns a new store, say { color: 'blue' }

Then, let's say you had a class Square extends PureComponent with mapStateToProps as (store) => { color: store.color }

What happens now is that when the store changes, redux-react runs the mapStateToProps every time. It then generates new props. These props get sent to react.

If you're with me so far the TL;DR of how redux and react work together is that whenever the redux store changes, every single mapStateToProps runs and this generates new props for your react components.

From this point on, it's standard React. When the props of a React component change, it runs componentWillReceiveProps followed by shouldComponentUpdate.

For a PureComponent, basically that means shouldComponentUpdate just does a shallow equality check on your new props, and goes from there.

Okay, with this base understanding out of the way, nested objects behave similarly.

Instead of a store of {color: 'red'} what if we had a store like this:

```<code>{
  allMyData: {
    color: 'red'
    key1: 'someData',
    key2: 'lotsMoreData',
    bigData: {
     nestedKey: 'EvenMoreNestedData',
    }

}
</code>```

Then, your reducer might look something like this:

```<code>const reducer = (store, action) => {
  if (action == CHANGE_COLOR) {
    let newStore = Object.assign({}, store);
    newStore.allMyData = Object.assign({}, newStore.allMyData, { color: 'blue' });

  }
}
</code>```

Note that there are better tools to do deep immutable merges. One main point I want to show here is that although the newStore is a different object, both store and newStore BOTH point to the SAME bigData key and the other values that are unchanged. The immutability part allows for this kind of thing to work.

After this, the steps are basically the same. After every store change, mapStateToProps runs and generates a new props object. Redux-react then passes that new prop object to React and in this case, a PureComponent wouldn't render if the prop values have the same identity (===)

Note that redux-react has some perf optimizations where it will avoid calling into react with new props but for the purposes of this discussion I'm omitting that step.

Hope this helps clear up your questions.

TL;DR: Every redux action returns a new store. Every time a new store is generated, mapStateToProps generates new props for every connected react component. If the react component is a pureComponent, it won't re-render because the props haven't changed.

The crux for your question is that because your store is immutable, you can re-use the same inner objects across different stores, and even pass those into your react components via mapStateToProps.

Body:
Let's break it down step by step:

There is an initial redux store of { color: 'red' }

The user clicks a button

An action is generated, say CHANGE_COLOR

Redux calls your reducer with the store (from step 1) and the action. The reducer returns a new store, say { color: 'blue' }

Then, let's say you had a class Square extends PureComponent with mapStateToProps as (store) => { color: store.color }

What happens now is that when the store changes, redux-react runs the mapStateToProps every time. It then generates new props. These props get sent to react.

If you're with me so far the TL;DR of how redux and react work together is that whenever the redux store changes, every single mapStateToProps runs and this generates new props for your react components.

From this point on, it's standard React. When the props of a React component change, it runs componentWillReceiveProps followed by shouldComponentUpdate.

For a PureComponent, basically that means shouldComponentUpdate just does a shallow equality check on your new props, and goes from there.

Okay, with this base understanding out of the way, nested objects behave similarly.

Instead of a store of {color: 'red'} what if we had a store like this:

{
  allMyData: {
    color: 'red'
    key1: 'someData',
    key2: 'lotsMoreData',
    bigData: {
     nestedKey: 'EvenMoreNestedData',
    }

}

Then, your reducer might look something like this:

const reducer = (store, action) => {
  if (action == CHANGE_COLOR) {
    let newStore = Object.assign({}, store);
    newStore.allMyData = Object.assign({}, newStore.allMyData, { color: 'blue' });

  }
}

Note that there are better tools to do deep immutable merges. One main point I want to show here is that although the newStore is a different object, both store and newStore BOTH point to the SAME bigData key and the other values that are unchanged. The immutability part allows for this kind of thing to work.

After this, the steps are basically the same. After every store change, mapStateToProps runs and generates a new props object. Redux-react then passes that new prop object to React and in this case, a PureComponent wouldn't render if the prop values have the same identity (===)

Note that redux-react has some perf optimizations where it will avoid calling into react with new props but for the purposes of this discussion I'm omitting that step.

Hope this helps clear up your questions.

TL;DR: Every redux action returns a new store. Every time a new store is generated, mapStateToProps generates new props for every connected react component. If the react component is a pureComponent, it won't re-render because the props haven't changed.

The crux for your question is that because your store is immutable, you can re-use the same inner objects across different stores, and even pass those into your react components via mapStateToProps.


问:
Javascript / Regex: strip first
 if it matches a critheria
So I am getting a HTML content from the API and sometimes it would come in this format

```<code><p>::type/12</p>
<p>Some content</p>
<p>Some more content</p>
</code>```

and sometimes will not have the first paragraph...

what I would like is to parse that html snippet and extract relevant information as an object with following properties
type, time, content

so in the previous example it should translate to:

```<code>data = {
    type: 'type',
    time: 12,
    content: '<p>Some content</p><p>Some more content</p>'
}
</code>```

I also have the array of expected types (no more than 10)
allowedTypes = ['type1', 'type2', ...];

so if the first p contains ::type2/ than it's a valid object needing parsing, otherwise just do

```<code>data = {
    type: undefined,
    time: undefined,
    content: '.... all content here'
}
</code>```

I have no experience with regex, how would I approach this?
Also worth mentioning I am working with angular, so no jQuery functionality

Any ideas?

答:
This is how I would do it without using a regualar expression to parse the HTML

function getObject(str) {

  var temp = document.createElement("div")
  temp.innerHTML = str

  var data = {
    type: undefined,
    time: undefined
  };

  var elems = temp.getElementsByTagName("p")
  var match = elems[0].textContent.match(/::([^\/]+)\/(.+)/);
  if (match) {
    data.type = match[1]
    data.time = match[2]
    elems[0].remove()
  }

  data.content = temp.innerHTML;

  console.log(data)
  return data
}

var str1 = "
::type/12

Some content

Some more content
"
var str2 = "
Some content

Some more content
"
getObject(str1)
getObject(str2)```

Title: Javascript / Regex: strip first <p> if it matches a critheria

Body:
So I am getting a HTML content from the API and sometimes it would come in this format

::type/12

Some content

Some more content

and sometimes will not have the first paragraph...

what I would like is to parse that html snippet and extract relevant information as an object with following properties
type, time, content

so in the previous example it should translate to:

data = {
    type: 'type',
    time: 12,
    content: '
Some content

Some more content
'
}

I also have the array of expected types (no more than 10)
allowedTypes = ['type1', 'type2', ...];

so if the first p contains ::type2/ than it's a valid object needing parsing, otherwise just do

data = {
    type: undefined,
    time: undefined,
    content: '.... all content here'
}

I have no experience with regex, how would I approach this?
Also worth mentioning I am working with angular, so no jQuery functionality

Any ideas?

Body:
This is how I would do it without using a regualar expression to parse the HTML

function getObject(str) {

  var temp = document.createElement("div")
  temp.innerHTML = str

  var data = {
    type: undefined,
    time: undefined
  };

  var elems = temp.getElementsByTagName("p")
  var match = elems[0].textContent.match(/::([^\/]+)\/(.+)/);
  if (match) {
    data.type = match[1]
    data.time = match[2]
    elems[0].remove()
  }

  data.content = temp.innerHTML;

  console.log(data)
  return data
}

var str1 = "<p>::type/12</p><p>Some content</p><p>Some more content</p>"
var str2 = "<p>Some content</p><p>Some more content</p>"
getObject(str1)
getObject(str2)


问:
How to generate groovydoc from jenkins global library
I have a jenkins global library and I want to document it. I want to use groovydoc.

The library contains classes and global vars

```<code>src/<package-name>
vars
</code>```

Generating documentation for the classes is no problem:

```<code>groovydoc -sourcepath src -d doc 'main.pipeline' '*.groovy'
</code>```

But how can I generate documentation for the vars?

答:
Had the same problem at work today and sadly can't try my solution now, but try using the directory containing both src and vars as sourcepath. Then you can reference your src and vars subdirectories in your command like this:

```<code>groovydoc -sourcepath [PATH_TO_YOUR_LIB] -d doc src\ vars\
</code>```

If that doesnt work, try referencing each package seperately somewhat like this:

```<code>groovydoc -sourcepath [PATH_TO_YOUR_LIB] -d doc src\org.foo.some_package src\org.foo.some_other_package vars\
</code>```

Alternatively, or as a workaround, you could use the IntelliJ IDE and its "Generate GroovyDoc..."-Tool:

Start IntelliJ and open any Groovy project (create a new one if there isnt an existing one)

From the menu bar Tools > Generate GroovyDoc...

Choose your source path containing your jenkins pipeline library as Input directory (containing both src and vars) and any path as Output directory

Press Start

GroovyDoc should be in the specified Output directory

Body:
I have a jenkins global library and I want to document it. I want to use groovydoc.

The library contains classes and global vars

src/<package-name>
vars

Generating documentation for the classes is no problem:

groovydoc -sourcepath src -d doc 'main.pipeline' '*.groovy'

But how can I generate documentation for the vars?

Body:
Had the same problem at work today and sadly can't try my solution now, but try using the directory containing both src and vars as sourcepath. Then you can reference your src and vars subdirectories in your command like this:

groovydoc -sourcepath [PATH_TO_YOUR_LIB] -d doc src\ vars\

If that doesnt work, try referencing each package seperately somewhat like this:

groovydoc -sourcepath [PATH_TO_YOUR_LIB] -d doc src\org.foo.some_package src\org.foo.some_other_package vars\

Alternatively, or as a workaround, you could use the IntelliJ IDE and its "Generate GroovyDoc..."-Tool:

Start IntelliJ and open any Groovy project (create a new one if there isnt an existing one)

From the menu bar Tools > Generate GroovyDoc...

Choose your source path containing your jenkins pipeline library as Input directory (containing both src and vars) and any path as Output directory

Press Start

GroovyDoc should be in the specified Output directory


问:
JSONObject not response
How do I check if this text appears or not

{"cod":"404","message":"city not found"}

url : http://api.openweathermap.org/data/2.5/weather?q=fddfgdfgdfgdfg&units=metric&appid=efb8013262db1b77b0431909b8b173e1

My try

```<code>public void btn_search(View view) {
        CheckInternet checkInternet = new CheckInternet(MainActivity.this);
        boolean ci = checkInternet.isconnecting();
        if(ci)
        {
            EditText ed_Search = (EditText)findViewById(R.id.ed_Search);
            if(ed_Search.getText().length() > 0)
            {
                String urlOpenWeatherMap =  "http://api.openweathermap.org/data/2.5/weather?q=fddfgdfgdfgdfg&units=metric&appid=efb8013262db1b77b0431909b8b173e1";
                progressBar = (ProgressBar)findViewById(R.id.progressBar);
                btn_search = (ImageView)findViewById(R.id.btn_search);
                btn_search.setVisibility(View.INVISIBLE);
                progressBar.setVisibility(View.VISIBLE);
                RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
                JsonObjectRequest jsonobjectrequest = new JsonObjectRequest(Request.Method.GET, urlOpenWeatherMap, null,
                        new Response.Listener<JSONObject>() {
                            @Override
                            public void onResponse(JSONObject response) {
                                try {
                                    String x = response.getString("message");
                                    if(x.contains("404") || x.contains("city not found") )
                                    {
                                        Toast.makeText(MainActivity.this, "error", Toast.LENGTH_SHORT).show();
                                    }
                                    else
                                    {
                                        Toast.makeText(MainActivity.this, "welcome", Toast.LENGTH_SHORT).show();
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                });
                requestQueue.add(jsonobjectrequest);

            }
            else
            {
            Toast.makeText(MainActivity.this, "", Toast.LENGTH_SHORT).show();
            }
        }
        else
        {
            Toast.makeText(MainActivity.this, "no Internet", Toast.LENGTH_SHORT).show();
        }
    }
</code>```

I am trying to solve the problem 4 hours ago but no use

I think the problem here

```<code>String x = response.getString("message");
</code>```

I need help please

答:
You are getting json text in the response body, but the server is responding with 404 code which is an error, therefore the logic needs to be inside the overridden method:

```<code>@Override
public void onErrorResponse(VolleyError error) {
   String body;
   String statusCode = String.valueOf(error.networkResponse.statusCode);
   if(statusCode == "400") {
       // do your thing
   }
   // do something else
</code>```

}

Title: JSONObject not response

Body:
How do I check if this text appears or not

{"cod":"404","message":"city not found"}

url : http://api.openweathermap.org/data/2.5/weather?q=fddfgdfgdfgdfg&units=metric&appid=efb8013262db1b77b0431909b8b173e1

My try

public void btn_search(View view) {
        CheckInternet checkInternet = new CheckInternet(MainActivity.this);
        boolean ci = checkInternet.isconnecting();
        if(ci)
        {
            EditText ed_Search = (EditText)findViewById(R.id.ed_Search);
            if(ed_Search.getText().length() > 0)
            {
                String urlOpenWeatherMap =  "http://api.openweathermap.org/data/2.5/weather?q=fddfgdfgdfgdfg&units=metric&appid=efb8013262db1b77b0431909b8b173e1";
                progressBar = (ProgressBar)findViewById(R.id.progressBar);
                btn_search = (ImageView)findViewById(R.id.btn_search);
                btn_search.setVisibility(View.INVISIBLE);
                progressBar.setVisibility(View.VISIBLE);
                RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
                JsonObjectRequest jsonobjectrequest = new JsonObjectRequest(Request.Method.GET, urlOpenWeatherMap, null,
                        new Response.Listener<JSONObject>() {
                            @Override
                            public void onResponse(JSONObject response) {
                                try {
                                    String x = response.getString("message");
                                    if(x.contains("404") || x.contains("city not found") )
                                    {
                                        Toast.makeText(MainActivity.this, "error", Toast.LENGTH_SHORT).show();
                                    }
                                    else
                                    {
                                        Toast.makeText(MainActivity.this, "welcome", Toast.LENGTH_SHORT).show();
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                });
                requestQueue.add(jsonobjectrequest);

            }
            else
            {
            Toast.makeText(MainActivity.this, "", Toast.LENGTH_SHORT).show();
            }
        }
        else
        {
            Toast.makeText(MainActivity.this, "no Internet", Toast.LENGTH_SHORT).show();
        }
    }

I am trying to solve the problem 4 hours ago but no use

I think the problem here

String x = response.getString("message");

I need help please

Body:
You are getting json text in the response body, but the server is responding with 404 code which is an error, therefore the logic needs to be inside the overridden method:

@Override
public void onErrorResponse(VolleyError error) {
   String body;
   String statusCode = String.valueOf(error.networkResponse.statusCode);
   if(statusCode == "400") {
       // do your thing
   }
   // do something else

}


问:
Laravel: Form with files sent via Ajax
Im trying to send a form to my php server but my Laravel validation says that my forms are empty. I am trying to upload photo albums. My form consists of a title(text), cover(image), and photos(image). I receive a 422 error (Unprocessable Entity). Below is the code

HTML

```<code><form class="lajax" action="{{ action('AlbumController@store') }}" method="POST">
    <div class="form-group">
        <label>Album Name</label>
        <input type="text" name="name" class="form-control">
    </div>

    <div class="form-group">
        <label for="coverFile">Album Cover Image</label>
        <input  name="cover" type="file" id="coverFile">
        <p class="help-block">Example block-level help text here.</p>
    </div>

    <div class="form-group">
        <label for="albumFiles">Album Images</label>
        <input type="file" name="photos[]" multiple>
    </div>

    <button type="submit" class="btn btn-primary">Create Album</button>
</form>
</code>```

The Jquery responsible for the ajax
//object that will be fed into jquerys ajax method

```<code>            var ajax_options={
                    url: url,
                    method: method,
                    beforeSend: function(jqXHR,settings){
                        console.log(jqXHR);
                        console.log(settings);
                        if(optns.debug)
                            console.log('executing beforeSend function');
                        optns.lajaxBeforeSend($form,formData,jqXHR,settings);
                    },
                    success: function(data,textStatus,jqXHR){
                        if(optns.debug)
                            console.log('executing success function');
                        optns.lajaxSuccess($form,formData,data,textStatus,jqXHR)
                    },
                    error: function(jqXHR,textStatus,errorThrown){
                        if(optns.debug)
                            console.log('error encountered. ajax error function procked');
                        optns.lajaxError($form,formData,jqXHR,textStatus,errorThrown);

                        var errors = jqXHR.responseJSON;
                        console.log(errors);
                    },
                }

                //check if files are included in the submitted form if the method is not GET
                if($form.find('input:file').length && method!='GET'){
                    ajax_options.processData=false;
                    ajax_options.contentType=false;
                    ajax_options.cache=false;
                    ajax_options.data=formData;
                }

                if(optns.debug)
                    console.log('About to send ajax request');

                //sending request here
                $.ajax(ajax_options);
</code>```

the laravel php file

```<code>    public function store(Request $request)
    {
      //request input verification rules
      $rules=[
        'name'=>'required',
        'cover'=>'required|image',
        'photos'=>'required|array',
        'photos.*'=>'image'
      ];

      //perform validation
      $this->validate($request,$rules);

      //rest of code
    }
</code>```

答:
Try adding
        enctype="multipart/form-data" files=true
to your form tag

Title: Laravel: Form with files sent via Ajax

Body:
Im trying to send a form to my php server but my Laravel validation says that my forms are empty. I am trying to upload photo albums. My form consists of a title(text), cover(image), and photos(image). I receive a 422 error (Unprocessable Entity). Below is the code

HTML

<form class="lajax" action="{{ action('AlbumController@store') }}" method="POST">

        Album Name
        <input type="text" name="name" class="form-control">

        Album Cover Image
        <input  name="cover" type="file" id="coverFile">

Example block-level help text here.

        Album Images
        <input type="file" name="photos[]" multiple>

    <button type="submit" class="btn btn-primary">Create Album</button>
</form>

The Jquery responsible for the ajax
//object that will be fed into jquerys ajax method

            var ajax_options={
                    url: url,
                    method: method,
                    beforeSend: function(jqXHR,settings){
                        console.log(jqXHR);
                        console.log(settings);
                        if(optns.debug)
                            console.log('executing beforeSend function');
                        optns.lajaxBeforeSend($form,formData,jqXHR,settings);
                    },
                    success: function(data,textStatus,jqXHR){
                        if(optns.debug)
                            console.log('executing success function');
                        optns.lajaxSuccess($form,formData,data,textStatus,jqXHR)
                    },
                    error: function(jqXHR,textStatus,errorThrown){
                        if(optns.debug)
                            console.log('error encountered. ajax error function procked');
                        optns.lajaxError($form,formData,jqXHR,textStatus,errorThrown);

                        var errors = jqXHR.responseJSON;
                        console.log(errors);
                    },
                }

                //check if files are included in the submitted form if the method is not GET
                if($form.find('input:file').length && method!='GET'){
                    ajax_options.processData=false;
                    ajax_options.contentType=false;
                    ajax_options.cache=false;
                    ajax_options.data=formData;
                }

                if(optns.debug)
                    console.log('About to send ajax request');

                //sending request here
                $.ajax(ajax_options);

the laravel php file

    public function store(Request $request)
    {
      //request input verification rules
      $rules=[
        'name'=>'required',
        'cover'=>'required|image',
        'photos'=>'required|array',
        'photos.*'=>'image'
      ];

      //perform validation
      $this->validate($request,$rules);

      //rest of code
    }


问:
Spark can not get elements from 'MapType'
I'm writing a udaf with the following buffer schema:

```<code>bufferSchema: StructType = StructType(
    StructField("grades", MapType(StructType(StructField("subject", StringType) :: StructField("subject_type", StringType) :: Nil),
      ArrayType(StructType(StructField("date", LongType) :: StructField("grade", IntegerType) :: Nil)))) :: Nil)
</code>```

It looks like internally spark interprets the key type to be of GenericRowWithSchema instead of simple (String,String).
so Whenever I try to pull from the map :

```<code>  override def update(buffer: MutableAggregationBuffer, input: Row): Unit = {

var buffer_scoresMap = buffer.getAs[Map[(String,String), Array[..]](0)
</code>```

buffer_scoresMap.get(("k1","k2")) returns None even though that this key is definitely in the map, I even see it in debug.
I tried to mutate the keys to GenericRowWithSchema and then back to (String,String) and then get from the map, with no luck.

Any idea?

答:
Indeed, tuples are converted into Structs and not converted back into tuples when they are part of a deeply-nested column. In other words, buffer_scoresMap actually has the type Map[Row, Array[..]], so you can create a Row to fetch items from it:

```<code>var buffer_scoresMap = buffer.getAs[Map[Row, Array[..]](0)
buffer_scoresMap.get(Row("k1","k2")) // should not be None if key exists
</code>```

Here's a short example that proves this:

```<code>// create a simple DF with similar schema:
case class Record(grades: Map[(String, String), Array[Int]])
val df = sc.parallelize(Seq(Record(Map(("a", "b") -> Array(1, 2))))).toDF("grades")

// this indeed fails:
df.rdd.map(r => r.getAs[Map[(String, String), Array[Int]]](0).get(("a", "b"))).first() // None

// but this works:
df.rdd.map(r => r.getAs[Map[Row, Array[Int]]](0).get(Row("a", "b"))).first() // Some(WrappedArray(1, 2))
</code>```

Body:
I'm writing a udaf with the following buffer schema:

bufferSchema: StructType = StructType(
    StructField("grades", MapType(StructType(StructField("subject", StringType) :: StructField("subject_type", StringType) :: Nil),
      ArrayType(StructType(StructField("date", LongType) :: StructField("grade", IntegerType) :: Nil)))) :: Nil)

It looks like internally spark interprets the key type to be of GenericRowWithSchema instead of simple (String,String).
so Whenever I try to pull from the map :

  override def update(buffer: MutableAggregationBuffer, input: Row): Unit = {

var buffer_scoresMap = buffer.getAs[Map[(String,String), Array[..]](0)

buffer_scoresMap.get(("k1","k2")) returns None even though that this key is definitely in the map, I even see it in debug.
I tried to mutate the keys to GenericRowWithSchema and then back to (String,String) and then get from the map, with no luck.

Any idea?

Body:
Indeed, tuples are converted into Structs and not converted back into tuples when they are part of a deeply-nested column. In other words, buffer_scoresMap actually has the type Map[Row, Array[..]], so you can create a Row to fetch items from it:

var buffer_scoresMap = buffer.getAs[Map[Row, Array[..]](0)
buffer_scoresMap.get(Row("k1","k2")) // should not be None if key exists

Here's a short example that proves this:

// create a simple DF with similar schema:
case class Record(grades: Map[(String, String), Array[Int]])
val df = sc.parallelize(Seq(Record(Map(("a", "b") -> Array(1, 2))))).toDF("grades")

// this indeed fails:
df.rdd.map(r => r.getAs[Map[(String, String), Array[Int]]](0).get(("a", "b"))).first() // None

// but this works:
df.rdd.map(r => r.getAs[Map[Row, Array[Int]]](0).get(Row("a", "b"))).first() // Some(WrappedArray(1, 2))


问:
How do i access an object in validation.xml in bean validation framework
My class:

```<code>public class Employee {

private String firstName;
private String lastName;
private Department department;
//with getters and setters
}
</code>```

My employee-validation.xml

```<code><?xml version="1.0" encoding="ISO-8859-1"?>
<validation xmlns="http://www.springmodules.org/validation/bean" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://localhost:8080/BVF http://localhost:8080/BVF/validation.xsd">

<class name="Employee">
<validator class="EmployeeValidator"/>

<property name="firstName">
<not-blank message="FirstName cannot be left blank"/>
<length min="5" max="20" message="First Name Length cannot be less than 5 or more than 20"/>
</property>

<property name="lastName">
<not-blank message="LastName cannot be left balnk"/>
<length min="5" max="20" message="Last Name Length cannot be less than 5 or more than 20"/>
</property>

<property name="department.name">
<not-blank message="Name cannot be blank"/>
<length min="5" max="20" message="Name Length cannot be less than 5 or more than 20"/>
</property>

<property name="department.pinCode">
<not-blank message="Pin Code cannot be left blank"/>
<regexp expression="^[A-Z\d{1}]\d{4}[\s\-]*\d*$" message="PinCode is invalid"/>
<length min="5" max="10" message="Pincode length should be between 5 and 10"/>

</property>

</class>

</validation>
</code>```

can someone tell me how i can access the elements of department object, i.e. this part

```<code><property name="department.pinCode">
</code>```

答: i have found the solution, which is to use the cascade attribute.</p>

Body:
My class:

public class Employee {

private String firstName;
private String lastName;
private Department department;
//with getters and setters
}

My employee-validation.xml

<?xml version="1.0" encoding="ISO-8859-1"?>
<validation xmlns="http://www.springmodules.org/validation/bean" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://localhost:8080/BVF http://localhost:8080/BVF/validation.xsd">

<class name="Employee">
<validator class="EmployeeValidator"/>

<property name="firstName">
<not-blank message="FirstName cannot be left blank"/>
<length min="5" max="20" message="First Name Length cannot be less than 5 or more than 20"/>
</property>

<property name="lastName">
<not-blank message="LastName cannot be left balnk"/>
<length min="5" max="20" message="Last Name Length cannot be less than 5 or more than 20"/>
</property>

<property name="department.name">
<not-blank message="Name cannot be blank"/>
<length min="5" max="20" message="Name Length cannot be less than 5 or more than 20"/>
</property>

<property name="department.pinCode">
<not-blank message="Pin Code cannot be left blank"/>
<regexp expression="^[A-Z\d{1}]\d{4}[\s\-]*\d*$" message="PinCode is invalid"/>
<length min="5" max="10" message="Pincode length should be between 5 and 10"/>

</property>

</class>

</validation>

can someone tell me how i can access the elements of department object, i.e. this part

<property name="department.pinCode">


问:
Building typescript with Node vs. Visual Studio and an outDir
I have a typescript project that I can build with Visual Studio, and I can also build with node. But they both seem to behave slightly differently. My project looks like this (simplified):

```<code>.
+-- app
|   +-- app.component.ts
|   +-- app.module.ts
|   +-- main.ts
+-- dist
+-- system.config.js
+-- tsconfig.json
+-- packages.json
</code>```

Now when I build, I want to output all the files into the dist folder. Therefore my tsconfig.json is set up with an outDir as follows:

```<code>{
  "compileOnSave": true,
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": [ "es2015", "dom" ],
    "noImplicitAny": true,
    "suppressImplicitAnyIndexErrors": true,
    "outDir": "dist"

  },
  "exclude": [
    "node_modules/*",
    "packages/*",
    "**/*-aot.ts"
  ]
}
</code>```

Now when I build with node, using npm run tsc the dist folder looks like this:

```<code>+-- dist
|   +-- app
|   |   +-- main.js
|   |   +-- app.module.js
|   |   +-- app.component.js
</code>```

And when building with visual studio:

```<code>+-- dist
|   +-- main.js
|   +-- app.module.js
|   +-- app.component.js
</code>```

As you can see, the Visual Studio build doesn't place all the files inside the app folder. But the node build does.

Why is this not the same for both, given they are using the same configuration?

答:
Why is this not the same for both, given they are using the same configuration?

Your assumption is wrong. VS is not using this tsconfig.json.

Quick Fix

Create a new TypeScript project in visual studio and copy the files over.

Hard Fix

Figure out what Visual studio is using by editing the project file.

Body:
I have a typescript project that I can build with Visual Studio, and I can also build with node. But they both seem to behave slightly differently. My project looks like this (simplified):

.
+-- app
|   +-- app.component.ts
|   +-- app.module.ts
|   +-- main.ts
+-- dist
+-- system.config.js
+-- tsconfig.json
+-- packages.json

Now when I build, I want to output all the files into the dist folder. Therefore my tsconfig.json is set up with an outDir as follows:

{
  "compileOnSave": true,
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": [ "es2015", "dom" ],
    "noImplicitAny": true,
    "suppressImplicitAnyIndexErrors": true,
    "outDir": "dist"

  },
  "exclude": [
    "node_modules/*",
    "packages/*",
    "**/*-aot.ts"
  ]
}

Now when I build with node, using npm run tsc the dist folder looks like this:

+-- dist
|   +-- app
|   |   +-- main.js
|   |   +-- app.module.js
|   |   +-- app.component.js

And when building with visual studio:

+-- dist
|   +-- main.js
|   +-- app.module.js
|   +-- app.component.js

As you can see, the Visual Studio build doesn't place all the files inside the app folder. But the node build does.

Why is this not the same for both, given they are using the same configuration?


问:
How can I do custom JWT validation with Flask and flask_jwt_extended?
I want to add additional verification to the token when @jwt_required is called. I want to verify one of the claims. Is there away I can do this with JWTManager?

Currently my code just calls:

```<code>jwt = JWTManager(app)
</code>```

And I decorate the functions with: @jwt_required

答:
Posted this in your other question, but I'll post it here too just in case others stumble upon this.

Author here. For what it's worth, flask-jwt doesn't support requiring claims either (even though it says it does). https://github.com/mattupstate/flask-jwt/issues/98

EDIT: This is now available in flask-jwt-extended. https://github.com/vimalloc/flask-jwt-extended/issues/64#issuecomment-318800617

Cheers

Body:
I want to add additional verification to the token when @jwt_required is called. I want to verify one of the claims. Is there away I can do this with JWTManager?

Currently my code just calls:

jwt = JWTManager(app)

And I decorate the functions with: @jwt_required


问:
Not all components see the same state sequence?
See the example code:
https://codesandbox.io/s/G5A04RB23

State is simple, contains only a single value. Both Sub and App is connected to redux. When click the dispatch button, value incremented. And App will clear the state in componentWillReceiveProps when the value reaches 3.

But from the console log, it appears Sub never sees the 3 state.

VM220:80 action
VM220:21 reducer
VM220:83 dispatch: 0.525146484375ms
VM220:52 app prop 1
VM220:58 app render 1
VM220:32 sub prop 1
VM220:35 sub render 1
VM220:80 action
VM220:21 reducer
VM220:83 dispatch: 0.485107421875ms
VM220:52 app prop 2
VM220:58 app render 2
VM220:32 sub prop 2
VM220:35 sub render 2
VM220:80 action
VM220:21 reducer
VM220:83 dispatch: 0.4931640625ms
VM220:52 app prop 3 <<< app see 3
VM220:58 app render 3

VM220:32 sub prop 0 <<< sub never see 3
VM220:35 sub render 0
VM220:52 app prop 0
VM220:58 app render 0

I thought with redux, state should be consistent to all the components and every component should see the same state all the time. Is this the expected behavior or what am I doing wrong here?

EDIT1

Also tried with raw redux (instead of react-redux): https://codesandbox.io/s/Jq6gBoGzK

This time we do see both app and sub see the state value=3

So it appears to be a react-redux behavior. But it's a bit surprising behavior to me, I still expect all the components see every state change (thus props change). See my graph below:

Expect:

state1 -> (update props of comp1 ... compN) -> state2

Actual:

state1 -> (update props of comp1) -> state2 -> (update props of comp2)

Any reason why react-redux doing this instead of my expecting?

sub listener 1
app listener 1
sub listener 2
app listener 2
sub listener 3
app listener 3
sub listener 0
app listener 0

答:
Here's what's happening behind the scenes when you're rendering your app:

Get props from Redux for the App component

Call App::componentWillReceiveProps() with props from step #1

Call App::render() with props from step #1

App::render() tells React to render the Sub component

Get props from Redux for the Sub component

Call Sub::componentWillReceiveProps() with props from step #5

Call Sub::render() with props from step #5

When you dispatch the clearAction() event in App::componetWillReceiveProps() (between steps #2 and #3), Redux immediately changes the value property in the store from 3 to 0, so by the time you get to step #5, the Redux store contains value=0, which is why it appears that the Sub component never sees the value=3.

You can see this by tweaking your code and calling store.dispatch(clearAction()); after a timeout:

```<code>if (nextProps.value == 3) {
  setTimeout(function() {
    store.dispatch(clearAction());
  }, 1000); // dispatch the clearAction() after one second
}
</code>```

With that change you should see the value=3 render all the way down to the Sub component, and then automatically change to value=0 one second after your click when the clearAction() event gets dispatched.

Body:
Here's what's happening behind the scenes when you're rendering your app:

Get props from Redux for the App component

Call App::componentWillReceiveProps() with props from step #1

Call App::render() with props from step #1

App::render() tells React to render the Sub component

Get props from Redux for the Sub component

Call Sub::componentWillReceiveProps() with props from step #5

Call Sub::render() with props from step #5

When you dispatch the clearAction() event in App::componetWillReceiveProps() (between steps #2 and #3), Redux immediately changes the value property in the store from 3 to 0, so by the time you get to step #5, the Redux store contains value=0, which is why it appears that the Sub component never sees the value=3.

You can see this by tweaking your code and calling store.dispatch(clearAction()); after a timeout:

if (nextProps.value == 3) {
  setTimeout(function() {
    store.dispatch(clearAction());
  }, 1000); // dispatch the clearAction() after one second
}

With that change you should see the value=3 render all the way down to the Sub component, and then automatically change to value=0 one second after your click when the clearAction() event gets dispatched.


答:
Json Might be look like

```<code>{"loginNodes":[{"message":"Welcome To Alamofire","name":Enamul Haque,"errorCode":"0","photo":null}]}
</code>```

Your code should be ..

```<code> StringRequest stringRequest = new StringRequest(Request.Method.POST, "http://api.openweathermap.org/data/2.5/weather",
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    //pDialog.dismiss();

                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        JSONArray loginNodes = jsonObject.getJSONArray("loginNodes");
                        pDialog.dismiss();
                        for (int i = 0; i < loginNodes.length(); i++) {
                            JSONObject jo = loginNodes.getJSONObject(i);
                         String message=  jo.getString("message");
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    pDialog.dismiss();
                    try {

                    } catch (Exception e) {

                    }
                }
            }) {
        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<>();
            params.put("q", "fddfgdfgdfgdfg");
            params.put("units", "metric");
            params.put("appid", "efb8013262db1b77b0431909b8b173e1");

            return params;
        }
    };

    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(stringRequest);
</code>```

Check response from GET OR Post.You can debug the error onErrorResponse

```<code>try {

                        if (error instanceof TimeoutError ) {

                        }else if(error instanceof NoConnectionError){

                        } else if (error instanceof AuthFailureError) {

                        } else if (error instanceof ServerError) {
                            //TODO
                        } else if (error instanceof NetworkError) {
                            //TODO
                        } else if (error instanceof ParseError) {
                            //TODO
                        }

                    } catch (Exception e) {
                    }
</code>```

Title: JSONObject not response

Body:
Json Might be look like

{"loginNodes":[{"message":"Welcome To Alamofire","name":Enamul Haque,"errorCode":"0","photo":null}]}

Your code should be ..

 StringRequest stringRequest = new StringRequest(Request.Method.POST, "http://api.openweathermap.org/data/2.5/weather",
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    //pDialog.dismiss();

                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        JSONArray loginNodes = jsonObject.getJSONArray("loginNodes");
                        pDialog.dismiss();
                        for (int i = 0; i < loginNodes.length(); i++) {
                            JSONObject jo = loginNodes.getJSONObject(i);
                         String message=  jo.getString("message");
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    pDialog.dismiss();
                    try {

                    } catch (Exception e) {

                    }
                }
            }) {
        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<>();
            params.put("q", "fddfgdfgdfgdfg");
            params.put("units", "metric");
            params.put("appid", "efb8013262db1b77b0431909b8b173e1");

            return params;
        }
    };

    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(stringRequest);

Check response from GET OR Post.You can debug the error onErrorResponse

try {

                        if (error instanceof TimeoutError ) {

                        }else if(error instanceof NoConnectionError){

                        } else if (error instanceof AuthFailureError) {

                        } else if (error instanceof ServerError) {
                            //TODO
                        } else if (error instanceof NetworkError) {
                            //TODO
                        } else if (error instanceof ParseError) {
                            //TODO
                        }

                    } catch (Exception e) {
                    }


答:
You could use a regex fetching the type and time if the structure of the first paragraph is consistent between all results. Based on your example, I would say this regex should work:

/
::([a-z]+)\/([0-9]+)<\/p>/

It captures the letters after
:: and before / and also captures the numbers between / and

You can find the matches with the exec method:

```<code>var results = /<p>::([a-z]+)\/([0-9]+)<\/p>/.exec(text);
var type = results[1];
var time = results[2];
</code>```

For the content, you could use this regex in replace as well

```<code>var content = text.replace(/<p>::([a-z]+)\/([0-9]+)<\/p>/, '');
</code>```

Note: this will only work if all results are formatted like you provided. If some result is different, you need to take care of that as well...

Body:
You could use a regex fetching the type and time if the structure of the first paragraph is consistent between all results. Based on your example, I would say this regex should work:

/<p>::([a-z]+)\/([0-9]+)<\/p>/

It captures the letters after <p>:: and before / and also captures the numbers between / and </p>

You can find the matches with the exec method:

var results = /<p>::([a-z]+)\/([0-9]+)<\/p>/.exec(text);
var type = results[1];
var time = results[2];

For the content, you could use this regex in replace as well

var content = text.replace(/<p>::([a-z]+)\/([0-9]+)<\/p>/, '');

Note: this will only work if all results are formatted like you provided. If some result is different, you need to take care of that as well...


答:
String compares use the equals method and you can also  simplify your code to one toast statement:</p>

```<code>@Override
public boolean onOptionsItemSelected(MenuItem item) {
    String message = "Not clicked right";
    int length = Toast.LENGTH_SHORT;
    String title = item.getTitle().toString();
    if ("Love".equals(title)) {
        message = "Love u too dear";
        length = Toast.LENGTH_LONG;
    } else if ("Edit".equals(title)) {
        message = "Editable";
    } else if ("delete".equals(title)) {
        message = "Can be Deleted";
    }
    Toast.makeText(this, message, length).show();
    return true;
}
</code>```

Title: Context menu with list view

Body:
My code is not showing any Toast.When i long push it shows three menu but when i select any menu like "delete" it does not show Toast, What can I do so that it work. I have tried with answer on this site but not get success. Here is my code.

 package com.example.avinashkumaryadav.menutwo;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Adapter;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
ListView lview;
String[] contact={"Avinash","Golu","Sam","Tom","Ram","Yam"};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    lview=(ListView)findViewById(R.id.linearId) ;
    ArrayAdapter Array=new ArrayAdapter<String>(this,R.layout.linear_view,R.id.linearView,contact);
    lview.setAdapter(Array);
    registerForContextMenu(lview);
}

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);

    menu.setHeaderTitle("Select Action");
    menu.add(0,v.getId(),0,"Love");
    menu.add(0,v.getId(),0,"Edit");
    menu.add(0,v.getId(),0,"delete");
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if(item.getTitle()=="Love") {
        Toast.makeText(MainActivity.this, "Love u too dear", Toast.LENGTH_LONG).show();
    }
    else if(item.getTitle()=="Edit")
    {
        Toast.makeText(getApplicationContext(),"Editable",Toast.LENGTH_SHORT).show();
    }
    else if(item.getTitle()=="delete")
    {
        Toast.makeText(getApplicationContext(),"Can be Deleted",Toast.LENGTH_SHORT).show();
    }
  else
       {
          Toast.makeText(this,"Not clicked right",Toast.LENGTH_SHORT);
       }
       return true;

   }
 }

Cany anyone help me please?

Body:
String compares use the equals method and you can also  simplify your code to one toast statement:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    String message = "Not clicked right";
    int length = Toast.LENGTH_SHORT;
    String title = item.getTitle().toString();
    if ("Love".equals(title)) {
        message = "Love u too dear";
        length = Toast.LENGTH_LONG;
    } else if ("Edit".equals(title)) {
        message = "Editable";
    } else if ("delete".equals(title)) {
        message = "Can be Deleted";
    }
    Toast.makeText(this, message, length).show();
    return true;
}


问:
android.util.Config.DEBUG always false even when developing and debugging in eclipse. Why?
When developing in eclipse, the android.util.Config.DEBUG constant is always false even when I debug the project.

The javadoc for this constant says that "If this is a debug build, this field will be true." What am I doing wrong?

答:
http://groups.google.com/group/android-developers/browse_thread/thread/be329298953aa8bd

I think given the above link that the answer lies with the device and not only your app.

Have you gone into your devices settings and turned on debugging?

Go to Settings>Application settings>Development and ensure USB debugging is on.

[Edit]
And ensure that in your manifest file you've put debuggable="true"

```<code><manifest>
...
<application android:debuggable="true" >
</code>```

Body:
http://groups.google.com/group/android-developers/browse_thread/thread/be329298953aa8bd

I think given the above link that the answer lies with the device and not only your app.

Have you gone into your devices settings and turned on debugging?

Go to Settings>Application settings>Development and ensure USB debugging is on.

[Edit]
And ensure that in your manifest file you've put debuggable="true"

<manifest>
...
<application android:debuggable="true" >


问:
CuBlas Matrix Addition using axpy
I'm trying to do matrix addition using Alea CuBlas axpy, but it seems to only add the top row</p>

```<code>let matrixAddition (a:float[,]) (b: float[,]) =
     use mA = gpu.AllocateDevice(a)
     use mB = gpu.AllocateDevice(b)
     blas.Axpy(a.Length,1.,mA.Ptr,1,mB.Ptr,1)
     Gpu.Copy2DToHost(mB)
</code>```

答:
I took your example and it runs fine.

Code:

```<code>        var gpu = Gpu.Default;
        var blas = Blas.Get(Gpu.Default);

        var hostA = new float[,]
        {
            {1, 2, 3},
            {4, 5, 6},
            {7, 8, 9},
        };

        var hostB = new float[,]
        {
            {10, 20, 30},
            {40, 50, 60},
            {70, 80, 90},
        };

        PrintArray(hostA);
        PrintArray(hostB);

        var deviceA = gpu.AllocateDevice(hostA);
        var deviceB = gpu.AllocateDevice(hostB);

        blas.Axpy(deviceA.Length, 1f, deviceA.Ptr, 1, deviceB.Ptr, 1);

        var hostC = Gpu.Copy2DToHost(deviceB);

        PrintArray(hostC);
</code>```

Print Helper:

```<code>    private static void PrintArray(float[,] array)
    {
        for (var i = 0; i < array.GetLength(0); i++)
        {
            for (var k = 0; k < array.GetLength(1); k++)
            {
                Console.Write("{0} ", array[i, k]);
            }

            Console.WriteLine();
        }

        Console.WriteLine(new string('-', 10));
    }
</code>```

This is what I get:

Two questions:
 - What version of AleaGpu are you using?
 - What version of the CUDA Toolkit are you using?

I coded my sample against: Alea 3.0.4-beta2 and I have CudaToolkit 8.0.

Just to be sure I tried to code your example in F#.
(I'm not fluent in F#)

Code:

```<code>let gpu = Gpu.Default;
let blas = Blas.Get(Gpu.Default);

let hostA: float[,] = array2D [[  1.0;  2.0;  3.0 ]; [  4.0;  5.0;  6.0 ]; [  7.0;  8.0;  9.0 ]]
let hostB: float[,] = array2D [[ 10.0; 20.0; 30.0 ]; [ 40.0; 50.0; 60.0 ]; [ 70.0; 80.0; 90.0 ]]

PrintArray(hostA)
PrintArray(hostB)

use deviceA = gpu.AllocateDevice(hostA);
use deviceB = gpu.AllocateDevice(hostB);

blas.Axpy(deviceA.Length, 1.0, deviceA.Ptr, 1, deviceB.Ptr, 1);

let hostC = Gpu.Copy2DToHost(deviceB);

PrintArray(hostC)
</code>```

Print Helper:

```<code>let PrintArray(array: float[,]): unit =
    for i in 0 .. array.GetLength(0) - 1 do
        for k in 0 .. array.GetLength(1) - 1 do
            Console.Write("{0} ", array.[i, k]);
        Console.WriteLine();

    Console.WriteLine(new string('-', 10));
</code>```

Title: CuBlas Matrix Addition using axpy

Body:
I'm trying to do matrix addition using Alea CuBlas axpy, but it seems to only add the top row

let matrixAddition (a:float[,]) (b: float[,]) =
     use mA = gpu.AllocateDevice(a)
     use mB = gpu.AllocateDevice(b)
     blas.Axpy(a.Length,1.,mA.Ptr,1,mB.Ptr,1)
     Gpu.Copy2DToHost(mB)

Body:
I took your example and it runs fine.

Code:

        var gpu = Gpu.Default;
        var blas = Blas.Get(Gpu.Default);

        var hostA = new float[,]
        {
            {1, 2, 3},
            {4, 5, 6},
            {7, 8, 9},
        };

        var hostB = new float[,]
        {
            {10, 20, 30},
            {40, 50, 60},
            {70, 80, 90},
        };

        PrintArray(hostA);
        PrintArray(hostB);

        var deviceA = gpu.AllocateDevice(hostA);
        var deviceB = gpu.AllocateDevice(hostB);

        blas.Axpy(deviceA.Length, 1f, deviceA.Ptr, 1, deviceB.Ptr, 1);

        var hostC = Gpu.Copy2DToHost(deviceB);

        PrintArray(hostC);

Print Helper:

    private static void PrintArray(float[,] array)
    {
        for (var i = 0; i < array.GetLength(0); i++)
        {
            for (var k = 0; k < array.GetLength(1); k++)
            {
                Console.Write("{0} ", array[i, k]);
            }

            Console.WriteLine();
        }

        Console.WriteLine(new string('-', 10));
    }

This is what I get:

Two questions:
 - What version of AleaGpu are you using?
 - What version of the CUDA Toolkit are you using?

I coded my sample against: Alea 3.0.4-beta2 and I have CudaToolkit 8.0.

Just to be sure I tried to code your example in F#.
(I'm not fluent in F#)

Code:

let gpu = Gpu.Default;
let blas = Blas.Get(Gpu.Default);

let hostA: float[,] = array2D [[  1.0;  2.0;  3.0 ]; [  4.0;  5.0;  6.0 ]; [  7.0;  8.0;  9.0 ]]
let hostB: float[,] = array2D [[ 10.0; 20.0; 30.0 ]; [ 40.0; 50.0; 60.0 ]; [ 70.0; 80.0; 90.0 ]]

PrintArray(hostA)
PrintArray(hostB)

use deviceA = gpu.AllocateDevice(hostA);
use deviceB = gpu.AllocateDevice(hostB);

blas.Axpy(deviceA.Length, 1.0, deviceA.Ptr, 1, deviceB.Ptr, 1);

let hostC = Gpu.Copy2DToHost(deviceB);

PrintArray(hostC)

Print Helper:

let PrintArray(array: float[,]): unit =
    for i in 0 .. array.GetLength(0) - 1 do
        for k in 0 .. array.GetLength(1) - 1 do
            Console.Write("{0} ", array.[i, k]);
        Console.WriteLine();

    Console.WriteLine(new string('-', 10));


问:
How to create a summary using dictionaries based on an excel with empty cells using python? (vlookup with python)
I have an Excel spreadsheet. In column A I have an ID, column B I have the description.

The same ID and same text repeats x times, but the final row of that ID has no description. And then the ID changes.

Here is a screenshot of the file:

I want with Python to read downwards. When it finds a new ID, append it to a dictionary with its description, and then go to the next ID with its description.

It´s like the vlookup formula, but with Python.

答:
You can try this if you like using pandas:

in case you don't know how to read excel files with pd it's done with pandas.read_excel:

```<code>import pandas as pd
# header = None in case you don't have any header rows in your excel
# names are the columns names
df = pd.read_excel(file_dir,sheetName,header=None,names=['A','B','C'])
</code>```

for this case i used this data set:

```<code>     A      B      C
0  ID1  Desc1  stuff
1  ID1  Desc1  stuff
2  ID1  Desc1  stuff
3  ID1    NaN    NaN    # NaN are empty cells ( missing values )
4  ID2  Desc2  stuff
5  ID2  Desc2  stuff
6  ID2    NaN    NaN
</code>```

so once you have your dataframe, all you need to create your dicts are pandas.drop_duplicates and zip built-in function:

```<code>df.drop_duplicates(['A'],keep='first',inplace=True)
d = {k:v for k,v in zip(df['A'],df['B'])}
</code>```

that will give you d:

```<code>{'ID1': 'Desc1', 'ID2': 'Desc2'}
</code>```

Hope that was helpful.

Body:
You can try this if you like using pandas:

in case you don't know how to read excel files with pd it's done with pandas.read_excel:

import pandas as pd
# header = None in case you don't have any header rows in your excel
# names are the columns names
df = pd.read_excel(file_dir,sheetName,header=None,names=['A','B','C'])

for this case i used this data set:

     A      B      C
0  ID1  Desc1  stuff
1  ID1  Desc1  stuff
2  ID1  Desc1  stuff
3  ID1    NaN    NaN    # NaN are empty cells ( missing values )
4  ID2  Desc2  stuff
5  ID2  Desc2  stuff
6  ID2    NaN    NaN

so once you have your dataframe, all you need to create your dicts are pandas.drop_duplicates and zip built-in function:

df.drop_duplicates(['A'],keep='first',inplace=True)
d = {k:v for k,v in zip(df['A'],df['B'])}

that will give you d:

{'ID1': 'Desc1', 'ID2': 'Desc2'}

Hope that was helpful.


问:
How to start Spyder IDE on Windows
I downloaded spyder using the

pip install spyder

in my windows 10 32-bit operating system, but i dont see any desktop icons or exe files to start running the IDE. I downloaded spyder 3, any my python is 3.6.
I even tried creating a shortcut of spyder.exe from the Python3.6/Scripts folder, but it won't open.

答: Open a command prompt. Enter the command spyder. Does anything appear? If an exception is preventing it from opening, you would be able to see the reason here. If the command is not found, update your environment variables to point to the Python3.6/Scripts folder, and run spyder again (in a new cmd prompt).

ContentLicense: CC BY-SA 4.0

Title: How to start Spyder IDE on Windows


问:
Is it possible to wrap table rows responsively?
Is it possible to wrap a table row and its contents (tds) so that the table stays responsive? For example:

```<code><table>
<tr>
<td><!---content---></td>
<td><!---content---></td>
<td><!---content---></td>
<td><!---content---></td>
<td><!---content---></td>
</tr>
<tr>
<td><!---content---></td>
<td><!---content---></td>
<td><!---content---></td>
<td><!---content---></td>
<td><!---content---></td>
</tr>
</table>
</code>```

Can those two rows of 5 become two rows of 4 and a row of 2 for some screen sizes, or three rows of 3 and one row of 1 for others, and so on?

Have tried floats and inline styling but the rows are always on the next line, and never flush next to one another so the td areas look seamless. I have no access to the html of the table structure, so I'm trying to target it with CSS or even Javascript/jQuery.

Any ideas?

答:
table elements are not designed to work the way you are asking. What you are asking is generally referred as Responsive UI and we have many ready-made solutions for that. I would strongly recommend Bootstrap library/framework for that purpose.

Bootstraps grid system will allow you to do what you are asking for. In case you rare interested in this approach, you can read about other options (other frameworks other than Bootstrap)as well here.

Body:
Is it possible to wrap a table row and its contents (tds) so that the table stays responsive? For example:

Can those two rows of 5 become two rows of 4 and a row of 2 for some screen sizes, or three rows of 3 and one row of 1 for others, and so on?

Have tried floats and inline styling but the rows are always on the next line, and never flush next to one another so the td areas look seamless. I have no access to the html of the table structure, so I'm trying to target it with CSS or even Javascript/jQuery.

Any ideas?


答:
I always do this:

CSS:

```<code>.row {
    width: 100%;
}
.row > div {
    float: left;
}
.w25 {
    width: 25%;
}
.w33 {
    width: 33.333333%;
}
.w50 {
    width: 50%;
}
</code>```

add more if you wish. After this css, you can simply call wherever you want.

```<code><div class="row">
    <div class="w50">1</div>
    <div class="w50">2</div>
</div>
</code>```

In your case (5 cells) you could add .w20 {width:20%;} to the css, to use

" in the html.

There is only one minor disadvantage of using this method. Whenever you create tables, rows and cells, the cells are divided according to there content. But with my method, they will always be 20%, 50% or whatever.

Another alternative would be to use flex, but as you can see here, not all browsers support this.

Title: Is it possible to wrap table rows responsively?

Body:
I always do this:

CSS:

.row {
    width: 100%;
}
.row > div {
    float: left;
}
.w25 {
    width: 25%;
}
.w33 {
    width: 33.333333%;
}
.w50 {
    width: 50%;
}

add more if you wish. After this css, you can simply call wherever you want.

<div class="row">
    <div class="w50">1</div>
    <div class="w50">2</div>
</div>

In your case (5 cells) you could add .w20 {width:20%;} to the css, to use <div class="w20></div>" in the html.

There is only one minor disadvantage of using this method. Whenever you create tables, rows and cells, the cells are divided according to there content. But with my method, they will always be 20%, 50% or whatever.

Another alternative would be to use flex, but as you can see here, not all browsers support this.


问:
Explicit explanation as to what a return type is, why void is necessary
I'm sorry to ask a question that is conceptual but I am having a very hard time visualizing the idea of 'returning a value' from a method. I am still a beginner, sorry about this.

Take this code snippet for example:

```<code>public static NameGenerator(string x)
{
    Random r = new Random();
    string[] randomNamePossibilities = new string[15]
    {
        "John", "Billy", "Tommy", "Kyle", "Jackson", "George", "Paco",
        "Sruy", "Mateus", "Matt",
        "Jared", "Sage", "Kai", "Trent", "Dillon"
    };
    int randomNumberPicker = r.Next(15);
    return randomNamePossibilities[randomNumberPicker];
}
</code>```

notice how it returns the one-dimensional string array, randomNamePossibilities[15].  The intention is for this method to generate a randomized number with Random r (that has a maximum value of 15), and then for the method to return one of these randomized names from the array as a string.

The error I'm getting is with NameGenerator() & return randomNamePossibilities[randomnumberPicker]; Giving me the errors 'Method must have a return type', and 'Since Person.NameGenerator(string) returns void, a return keyword must not be followed by an object expression.'

So my question is this: In explicitly simple terms, what does return do inside of a method like this? In what case is it used properly? Why is it that this code snippet gives me an error if I use void? How can I rewrite this to function well?

答:
The return value indicates what a method returns as a value to the caller.

This can be a value, a reference, an adress (with unsafe code) or nothing at all.

Think of this simple function:

```<code>f(x) = m*x+n
</code>```

when you use it in another context you go:

```<code>g(x) = f(x)*2+10^x
</code>```

In this case, f(x) returns the value of itself into the other function.

This is the same way that programming languages treat methods (and thats why they are often called functions aswell).

But in the case you do not want to return anything, you use void to indicate that no return value is given.

This doesn't mean that the return keyword is without use.

return always exits the method when it is called no matter where within a method.

See this example:

```<code>public int Foo()
{
    int x = 0;
    return 2; //Exits the method
    return 0; //Will never be hit at all
}
</code>```

You can use return in void methods without any value behind it to exit your method at any given location.

Body:
I'm sorry to ask a question that is conceptual but I am having a very hard time visualizing the idea of 'returning a value' from a method. I am still a beginner, sorry about this.

Take this code snippet for example:

public static NameGenerator(string x)
{
    Random r = new Random();
    string[] randomNamePossibilities = new string[15]
    {
        "John", "Billy", "Tommy", "Kyle", "Jackson", "George", "Paco",
        "Sruy", "Mateus", "Matt",
        "Jared", "Sage", "Kai", "Trent", "Dillon"
    };
    int randomNumberPicker = r.Next(15);
    return randomNamePossibilities[randomNumberPicker];
}

notice how it returns the one-dimensional string array, randomNamePossibilities[15].  The intention is for this method to generate a randomized number with Random r (that has a maximum value of 15), and then for the method to return one of these randomized names from the array as a string.

The error I'm getting is with NameGenerator() & return randomNamePossibilities[randomnumberPicker]; Giving me the errors 'Method must have a return type', and 'Since Person.NameGenerator(string) returns void, a return keyword must not be followed by an object expression.'

So my question is this: In explicitly simple terms, what does return do inside of a method like this? In what case is it used properly? Why is it that this code snippet gives me an error if I use void? How can I rewrite this to function well?

Body:
The return value indicates what a method returns as a value to the caller.

This can be a value, a reference, an adress (with unsafe code) or nothing at all.

Think of this simple function:

f(x) = m*x+n

when you use it in another context you go:

g(x) = f(x)*2+10^x

In this case, f(x) returns the value of itself into the other function.

This is the same way that programming languages treat methods (and thats why they are often called functions aswell).

But in the case you do not want to return anything, you use void to indicate that no return value is given.

This doesn't mean that the return keyword is without use.

return always exits the method when it is called no matter where within a method.

See this example:

public int Foo()
{
    int x = 0;
    return 2; //Exits the method
    return 0; //Will never be hit at all
}

You can use return in void methods without any value behind it to exit your method at any given location.


问:
How to write a file to a directory?
I am trying to write a file to a specific directory in Java. I have looked at many of the already answered questions relating to this in the Stack Overflow forums. Yet, every method I try just ends up with this error:

```<code>java.io.IOException: No such file or directory
at java.io.UnixFileSystem.createFileExclusively(Native Method)
at java.io.File.createNewFile(File.java:1012)
at mainFiles.fileManagers.NewCSV.nJSON(NewCSV.java:40)
at mainFiles.appWindows.UserDashboard$1.run(UserDashboard.java:30)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:756)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:709)
at java.awt.EventQueue$3.run(EventQueue.java:703)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:726)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
</code>```

Code:

```<code>public static void nJSON(String username) {

    File file = new File("src/jsonFiles/" +  username + ".json");

    try {
        if (file.exists() && file.isDirectory()) {
            System.out.println(username + ".json exist.");
        } else {
            json.put("Username", username);
            json.put("Password", mainFiles.windowsSrc.UserInfo.password);

            file.createNewFile();
            FileWriter writer = new FileWriter(file);
            FileOutputStream os = new FileOutputStream(file);

            writer.write(json.toJSONString());
            writer.flush();
            os.close();
            writer.close();

            System.out.println(username + ".json created.");

        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}
</code>```

Any suggestions on how I can write my file to a certain directory?

答:
Try to run this code:

    package com.test;

```<code>import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;

public class WriteFile {

    public static void main(String[] args) {
        nJSON("test");
    }

    public static void nJSON(String username) {
        File file = new File("/home/ivan/Downloads/" + username + ".json");
        try {
            if (file.exists() && file.isDirectory()) {
                System.out.println(username + ".json exist.");
            } else {
                String content = "testing";
                file.createNewFile();
                FileWriter writer = new FileWriter(file);
                FileOutputStream os = new FileOutputStream(file);
                writer.write(content);
                writer.flush();
                os.close();
                writer.close();

                System.out.println(username + ".json created.");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
</code>```

Just replace home/ivan/Downloads/ with a valid directory path. It is basically your code with out simple json. It works on my machine so I suspect you are trying to write to directory that does not exists.

Title: How to write a file to a directory?

Body:
I am trying to write a file to a specific directory in Java. I have looked at many of the already answered questions relating to this in the Stack Overflow forums. Yet, every method I try just ends up with this error:

java.io.IOException: No such file or directory
at java.io.UnixFileSystem.createFileExclusively(Native Method)
at java.io.File.createNewFile(File.java:1012)
at mainFiles.fileManagers.NewCSV.nJSON(NewCSV.java:40)
at mainFiles.appWindows.UserDashboard$1.run(UserDashboard.java:30)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:756)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:709)
at java.awt.EventQueue$3.run(EventQueue.java:703)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:726)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

Code:

public static void nJSON(String username) {

    File file = new File("src/jsonFiles/" +  username + ".json");

    try {
        if (file.exists() && file.isDirectory()) {
            System.out.println(username + ".json exist.");
        } else {
            json.put("Username", username);
            json.put("Password", mainFiles.windowsSrc.UserInfo.password);

            file.createNewFile();
            FileWriter writer = new FileWriter(file);
            FileOutputStream os = new FileOutputStream(file);

            writer.write(json.toJSONString());
            writer.flush();
            os.close();
            writer.close();

            System.out.println(username + ".json created.");

        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Any suggestions on how I can write my file to a certain directory?

Body:
Try to run this code:

    package com.test;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;

public class WriteFile {

    public static void main(String[] args) {
        nJSON("test");
    }

    public static void nJSON(String username) {
        File file = new File("/home/ivan/Downloads/" + username + ".json");
        try {
            if (file.exists() && file.isDirectory()) {
                System.out.println(username + ".json exist.");
            } else {
                String content = "testing";
                file.createNewFile();
                FileWriter writer = new FileWriter(file);
                FileOutputStream os = new FileOutputStream(file);
                writer.write(content);
                writer.flush();
                os.close();
                writer.close();

                System.out.println(username + ".json created.");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Just replace home/ivan/Downloads/ with a valid directory path. It is basically your code with out simple json. It works on my machine so I suspect you are trying to write to directory that does not exists.


问:
Memory allocation Primitive Stream vs primitive type table
My problem: I'm downloading huge data from the database for JFreeChart. I want to optimize data memory usage without using a primitive table.

Working with collections requires objects usage.
I'm wondering if I can optimize memory usage using primitive Stream like IntStream  instead of for example LinkedList<Integer>.

I don't know how to make a reliable benchmark.

答:
If your starting point is a LinkedList<Integer>, just replacing it with ArrayList<Integer> will reduce the memory consumption significantly, as explained in When to use LinkedList over ArrayList?. Since boxed integers are small objects and some of them will even be reused when boxing the same value, the graphs of this answer have significance.

If you want to have it simpler, just use int[]. If you need something you can fill incrementally, the Stream API has indeed an option. Use IntStream.builder() to get an IntStream.Builder to which you can repeatedly add new int values. Once it contains all values, you can call build().toArray() on it to get an int[] array containing all values or you can directly perform filtering and aggregate operations on the IntStream returned by build() (if you can express the aggregate operation as reduction).


答:
A return type is just that: it indicates what type you want to return from the method.

The method string Hello() { return "Hello"; } has the return type of string, and returns a string.

Your method declaration:

```<code>public static NameGenerator(string x)
</code>```

Lacks a return type. The compiler forgives you for that insofar that it won't immediately stop evaluating the code in that method, but a return type is required for class methods in C#.

Note that the compiler first noticed your lack of a declared return type ("Method must have a return type"), and then assumes you want a void method. You cannot return something; from a void method ("Since Person.NameGenerator(string) returns void, a return keyword must not be followed by an object expression").

If you don't want to return anything from a method, you declare its return type as void:

```<code>public void SayHello()
{
    Console.WriteLine("Hello");
}
</code>```

You can use the return keyword to (prematurely) exit a method, and for a non-void method, you'll have to return something at that point.

To fix your method, you need to add a return type:

```<code>public static string NameGenerator(string x)
{
    // ...
    int randomNumberPicker = r.Next(15);
    return randomNamePossibilities[randomNumberPicker];
}
</code>```

Now if you'd have a method that doesn't return anything, but you still want to return from it, you just use the return keyword:

```<code>public void HotDog()
{
    if (DateTime.Now.Hour < 12)
    {
        Console.WriteLine("Morning");
        return;
    }

    Console.WriteLine("Not morning");
}
</code>```

Here, return makes execution leave the method at that point.

Title: Explicit explanation as to what a return type is, why void is necessary

Body:
A return type is just that: it indicates what type you want to return from the method.

The method string Hello() { return "Hello"; } has the return type of string, and returns a string.

Your method declaration:

public static NameGenerator(string x)

Lacks a return type. The compiler forgives you for that insofar that it won't immediately stop evaluating the code in that method, but a return type is required for class methods in C#.

Note that the compiler first noticed your lack of a declared return type ("Method must have a return type"), and then assumes you want a void method. You cannot return something; from a void method ("Since Person.NameGenerator(string) returns void, a return keyword must not be followed by an object expression").

If you don't want to return anything from a method, you declare its return type as void:

public void SayHello()
{
    Console.WriteLine("Hello");
}

You can use the return keyword to (prematurely) exit a method, and for a non-void method, you'll have to return something at that point.

To fix your method, you need to add a return type:

public static string NameGenerator(string x)
{
    // ...
    int randomNumberPicker = r.Next(15);
    return randomNamePossibilities[randomNumberPicker];
}

Now if you'd have a method that doesn't return anything, but you still want to return from it, you just use the return keyword:

public void HotDog()
{
    if (DateTime.Now.Hour < 12)
    {
        Console.WriteLine("Morning");
        return;
    }

    Console.WriteLine("Not morning");
}

Here, return makes execution leave the method at that point.