问:
How to make return in function correctly?
```<code>function checkAnswer(id, answer) {
    answer = answer.trim();
    var xhr = new XmlHttpRequest();
    xhr.open('POST', './c.php', true);
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && xhr.status == 200) {
            console.log("FROM xhr: "+xhr.responseText);
             return xhr.responseText;
        }
                }
    xhr.send();

}
</code>```

This function can't return in right way. console.log("FROM xhr: "+xhr.responseText) is work, but not a return statement (return undefined). Why?

In c.php I have just echo "OK";

I also tried to paste return statement after xhr.send() , but it's also return undefined.

答: Your code execute asynchronous (function do not wait for AJAX response) so your function return undefined. Read about promises.

Body:
function checkAnswer(id, answer) {
    answer = answer.trim();
    var xhr = new XmlHttpRequest();
    xhr.open('POST', './c.php', true);
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && xhr.status == 200) {
            console.log("FROM xhr: "+xhr.responseText);
             return xhr.responseText;
        }
                }
    xhr.send();

}

This function can't return in right way. console.log("FROM xhr: "+xhr.responseText) is work, but not a return statement (return undefined). Why?

In c.php I have just echo "OK";

I also tried to paste return statement after xhr.send() , but it's also return undefined.


来源: stackexchange

问:
Is it possible to create an application WITHOUT a framework?
I was just thinking. C# has Winforms/WPF, Java has Swing and other frameworks, C++ has QT and so on; is it possible to create an application without using a Framework?

Putting aside the practicality of it, I'm just curious. How would one create an application that Just Works(tm) without needing external frameworks?

答:
C# needs .NET Framework, not WinForms (which is an optional library used by some application). The same with Java. </p>

<p>Unmanaged (native) applications usually use some runtime library - the library of common functions. You can write a native application without any library - the compiler lets you do this, but you will need to (re)write lots of common functions, eg. for string manipulation etc..  </p>

OwnerDisplayName: delete

ContentLicense: CC BY-SA 2.5

Body:
C# needs .NET Framework, not WinForms (which is an optional library used by some application). The same with Java.

Unmanaged (native) applications usually use some runtime library - the library of common functions. You can write a native application without any library - the compiler lets you do this, but you will need to (re)write lots of common functions, eg. for string manipulation etc..


问:
Installing TensorFlow on Windows (Python 3.6.x)
I'm trying to install TensorFlow on Windows.

I tried to install it with pip, but I always get the same error message:

```<code>... is not a supported wheel on this platform.
</code>```

I first tried it with Python 3.5.1, now I upgraded to 3.6.0b4, but it makes no difference.

Python:

```<code>Python 3.6.0b4 (default, Nov 22 2016, 05:30:12) [MSC v.1900 64 bit (AMD64)] on win32
</code>```

pip:

```<code>pip 9.0.1 from ...\python\lib\site-packages (python 3.6)
</code>```

To be exact, I tried the following two commands:

```<code>pip install --upgrade https://storage.googleapis.com/tensorflow/windows/cpu/tensorflow-0.12.0rc0-cp35-cp35m-win_amd64.whl
pip install --upgrade https://storage.googleapis.com/tensorflow/windows/gpu/tensorflow_gpu-0.12.0rc0-cp35-cp35m-win_amd64.whl
</code>```

they output the following:

```<code>> tensorflow-0.12.0rc0-cp35-cp35m-win_amd64.whl is not a supported wheel on this platform.
> tensorflow_gpu-0.12.0rc0-cp35-cp35m-win_amd64.whl is not a supported wheel on this platform.
</code>```

Does anyone know how to solve this problem? I'm not sure where I'm making a mistake.

Thanks!

Edit 1

Btw, I also tried pip install tensorflow and pip install tensorflow-gpu like suggested here. I got the following output:

```<code>> Could not find a version that satisfies the requirement tensorflow (from versions: ) No matching distribution found for tensorflow
> Could not find a version that satisfies the requirement tensorflow-gpu (from versions: ) No matching distribution found for tensorflow-gpu
</code>```

答:
At the time of this writing, there is no official support for TensorFlow with Python 3.6 on Windows. The recommendation is to build TensorFlow yourself.

Some people have already done this and provide *.whl files that you can directly install with pip. These are unofficial, so use at your own risk:

http://www.lfd.uci.edu/%7Egohlke/pythonlibs/#tensorflow

You can simply download them and install them with pip install <filename>.whl.

See also this GitHub comment.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to install TensorFlow on Windows.

I tried to install it with pip, but I always get the same error message:

... is not a supported wheel on this platform.

I first tried it with Python 3.5.1, now I upgraded to 3.6.0b4, but it makes no difference.

Python:

Python 3.6.0b4 (default, Nov 22 2016, 05:30:12) [MSC v.1900 64 bit (AMD64)] on win32

pip:

pip 9.0.1 from ...\python\lib\site-packages (python 3.6)

To be exact, I tried the following two commands:

pip install --upgrade https://storage.googleapis.com/tensorflow/windows/cpu/tensorflow-0.12.0rc0-cp35-cp35m-win_amd64.whl
pip install --upgrade https://storage.googleapis.com/tensorflow/windows/gpu/tensorflow_gpu-0.12.0rc0-cp35-cp35m-win_amd64.whl

they output the following:

> tensorflow-0.12.0rc0-cp35-cp35m-win_amd64.whl is not a supported wheel on this platform.
> tensorflow_gpu-0.12.0rc0-cp35-cp35m-win_amd64.whl is not a supported wheel on this platform.

Does anyone know how to solve this problem? I'm not sure where I'm making a mistake.

Thanks!

Edit 1

Btw, I also tried pip install tensorflow and pip install tensorflow-gpu like suggested here. I got the following output:

> Could not find a version that satisfies the requirement tensorflow (from versions: ) No matching distribution found for tensorflow
> Could not find a version that satisfies the requirement tensorflow-gpu (from versions: ) No matching distribution found for tensorflow-gpu


问:
Javascript Array to MySQL "In" list of values
I have an array where each element corresponds to an alphanumeric string, lets say :

userIds : ['Ab526', 'shvx23', '23636dsd']

I want to convert it into such a format so that I can pass this list of strings to IN clause of mySQL query as something like :

Select * from Users where userIds in '(...)';

I tried using array.join() and many other methods, suggested somewhere or the other but all in vain.

var userIds = ['Ab526', 'shvx23', '23636dsd']
var ids    = userIds.join(',');
var query  = 'Select * from Users where userIds in (' + ids + ')';
console.log(query);```

which results in :

Select * from Users where userIds in ('Ab526, shvx23, 23636dsd');

If anyone could suggest a solution as how can I achieve what I want to, it would be of great help.

答:
You could use reduce on the array:

var userIds = ['Ab526', 'shvx23', '23636dsd'];
    var clause = userIds.reduce(
                 function (cl , a, currIndex, arr)
                     {
                     return cl +
                      (currIndex == 0 ? "" : ",")
                     +"'"+ a + "'"+
                     (currIndex == arr.length-1 ? ")" : "") ; } , "(" );

    console.log(clause );```

ContentLicense: CC BY-SA 4.0

Body:
I have an array where each element corresponds to an alphanumeric string, lets say :

userIds : ['Ab526', 'shvx23', '23636dsd']

I want to convert it into such a format so that I can pass this list of strings to IN clause of mySQL query as something like :

Select * from Users where userIds in '(...)';

I tried using array.join() and many other methods, suggested somewhere or the other but all in vain.

var userIds = ['Ab526', 'shvx23', '23636dsd']
var ids    = userIds.join(',');
var query  = 'Select * from Users where userIds in (' + ids + ')';
console.log(query);

which results in :

Select * from Users where userIds in ('Ab526, shvx23, 23636dsd');

If anyone could suggest a solution as how can I achieve what I want to, it would be of great help.


问:
React: Higher Order Components: Can you can childs state
I'm trying to refactor from mixins to HOCs so I can upgrade to the newest React (I'm currently using React 13/ES5). When my component loads, the mixin is able to access a data object, this.data, that has a query property with a route.

```<code>React.createClass({
  mixins: [myMixin],
  data: {
    query: "/api/foo"
  },
  componentDidUpdate(): function(){
  }
  ...
}
</code>```

On componentDidMount inside the mixin, it would query that route, get back the data and put it on state.

```<code>var myMixin = React.createClass({
  componentDidMount(): function(){
    this.fetchData(this.data.query)
  }
  fetchData(query) {
    // fetch the data
  }
  ...
}
</code>```

This extracts a lot of boilerplate from my components. I don't have to run a componentDidMount on every component, just have the data object.

I have this mixin scattered all over the project. It actually does a lot more than this but I'm just trying to dumb it down for example sake.

In comes HOCs. I took the all the stuff from data and put in into getInitialState. Now that I have data on the now wrapped component's state, how do I access it? Like my mixin, I want my HOC to handle my componentDidMount, get access to data.query and fetch the data. I don't want to have to rewrite every component to have a componentDidMount.

PS-
I normally use the newest version of React and ES6, if anyone can tell me why the mixin could do this.data and my component couldn't that would be very helpful. In the newest version of React you can't define an object outside of render() like that.

答:
React doesn't encourage to change the state from outside of the component. The state is owned by component and so only the component has control over it.

From React documentation:

State is similar to props, but it is private and fully controlled by
  the component.

So what you can do is use props instead of state. For the given example you can write Higher Order Component as follows. But your Child component should be altered to render data from props instead of state.

```<code>function HOC(WrappedComponent){

  return React.createClass({

    getInitialState: function() {
      return { data: null };
    },

    componentDidMount: function(){
      this.fetchData(WrappedComponent.prototype.data.query)
    },

    fetchData: function(query){
     // Fetching data first
     // Then set the state with data
     this.setState({data:data});
    },

    render: function() {
      var props = Object.assign({}, this.props, this.state);
      return React.createElement(WrappedComponent, props);
    }

  });

}

var HOCChild = HOC(Child);
</code>```

PS- I normally use the newest version of React and ES6, if anyone can
  tell me why the mixin could do this.data and my component couldn't
  that would be very helpful. In the newest version of React you can't
  define an object outside of render() like that.

Usually, React Component define as an ES6 class. ES6 classes don't support static or instance properties. But you can define instance properties inside the contractor like this.

```<code>class A{
  constructor(){
    this.foo = "foo"
  }
}
</code>```

Body:
I'm trying to refactor from mixins to HOCs so I can upgrade to the newest React (I'm currently using React 13/ES5). When my component loads, the mixin is able to access a data object, this.data, that has a query property with a route.

React.createClass({
  mixins: [myMixin],
  data: {
    query: "/api/foo"
  },
  componentDidUpdate(): function(){
  }
  ...
}

On componentDidMount inside the mixin, it would query that route, get back the data and put it on state.

var myMixin = React.createClass({
  componentDidMount(): function(){
    this.fetchData(this.data.query)
  }
  fetchData(query) {
    // fetch the data
  }
  ...
}

This extracts a lot of boilerplate from my components. I don't have to run a componentDidMount on every component, just have the data object.

I have this mixin scattered all over the project. It actually does a lot more than this but I'm just trying to dumb it down for example sake.

In comes HOCs. I took the all the stuff from data and put in into getInitialState. Now that I have data on the now wrapped component's state, how do I access it? Like my mixin, I want my HOC to handle my componentDidMount, get access to data.query and fetch the data. I don't want to have to rewrite every component to have a componentDidMount.

PS-
I normally use the newest version of React and ES6, if anyone can tell me why the mixin could do this.data and my component couldn't that would be very helpful. In the newest version of React you can't define an object outside of render() like that.

Body:
React doesn't encourage to change the state from outside of the component. The state is owned by component and so only the component has control over it.

From React documentation:

State is similar to props, but it is private and fully controlled by
  the component.

So what you can do is use props instead of state. For the given example you can write Higher Order Component as follows. But your Child component should be altered to render data from props instead of state.

function HOC(WrappedComponent){

  return React.createClass({

    getInitialState: function() {
      return { data: null };
    },

    componentDidMount: function(){
      this.fetchData(WrappedComponent.prototype.data.query)
    },

    fetchData: function(query){
     // Fetching data first
     // Then set the state with data
     this.setState({data:data});
    },

    render: function() {
      var props = Object.assign({}, this.props, this.state);
      return React.createElement(WrappedComponent, props);
    }

  });

}

var HOCChild = HOC(Child);

PS- I normally use the newest version of React and ES6, if anyone can
  tell me why the mixin could do this.data and my component couldn't
  that would be very helpful. In the newest version of React you can't
  define an object outside of render() like that.

Usually, React Component define as an ES6 class. ES6 classes don't support static or instance properties. But you can define instance properties inside the contractor like this.

class A{
  constructor(){
    this.foo = "foo"
  }
}


问:
NSImage release in AppleScriptObjC
I have a small AppleScriptObjC app that I use for processing photos. I need to fix a memory leak that I've discovered which seems to be caused by the photos being cached and not being released. This occurs every time I process (initWithContentsOfFile_) which causes the memory usage to increase with each process. The relevant section of my code is:

```<code>on applicationWillFinishLaunching_(aNotification)
    set inputPath to (choose folder with prompt "Select The Input Directory" default location (path to desktop folder))
    tell application "finder"
    set imageNames to get name of files of inputPath
    end tell
    set imagesRemaining to (number of items of imageNames) as string
    my errorAlert(imagesRemaining & " photos remaining.")
    if (number of items of imageNames) = 0
    my errorAlert("There are no items in the directory.")
    else
    set numberOfImages to number of items of imageNames
    set currentPath to inputPath & (item 1 of imageNames) as string
    set theImage to initWithContentsOfFile_(POSIX path of currentPath) of alloc() of class "NSImage" of current application
    setImage_(theImage) of imageView
    set theImage to missing value
end if
end applicationWillFinishLaunching_
</code>```

This part of the script assigns the first photo, the other processing functions are pretty much identical.

I'm either trying to figure out how to correctly release each photo or, alternatively, use the setCacheMode:NSImageCacheNever to disable the caching function. Despite trying for a long time to figure out the proper syntax in ApplescriptObjC, I can't seem to fix the memory leak. Thanks!

For reference, here's the button action which causes the memory to increase every time executed:

```<code>    on photoOutput1_(sender)
        if output1 = ""
        set output1 to (choose folder with prompt "Select The Output Path #1" default location (path to desktop folder))
        else
    end if
tell application "Finder"
set ProcessedPhoto to quoted form of (POSIX path of CurrentPath)
set photoNumber to photoNumber + 1
set DateAppend to do shell script "date +%m-%d_%H.%M"
set DateAppend to DateAppend & "_" & photoNumber
set OutputPath to quoted form of ((POSIX path of output1) & DateAppend & ".jpg")
try
    do shell script "mv -n " & ProcessedPhoto & " " & OutputPath
    on error
    my errorAlert("Unable to move the photo. Please try again.")
    return
end try
            set imageNames to get name of files of inputPath
        end tell
set imagesRemaining to (number of items of imageNames) as string
my errorAlert(imagesRemaining & " photos remaining.")
        if (number of items of imageNames) = 0
        imageView's setImage_(missing value)
        my errorAlert("There are no more photos in the directory.")
        else
        set numberOfImages to number of items of imageNames
        set currentPath to inputPath & (item 1 of imageNames) as string
set theImage to missing value
imageView's setImage_(theImage)
set theImage to initWithContentsOfFile_(POSIX path of currentPath) of alloc() of class "NSImage" of current application
        setImage_(theImage) of imageView
tell application "Finder"
        set OutputImageNames to number of files in folder output1
        end tell
        buttonA's setTitle_("A (" & OutputImageNames & ")")
        end if
    end photoOutput1_
</code>```

答:
You may try to both release the image variable and the image because in Applescript the contents are copied and not pointers:

```<code>set theImage to missing value
imageView's setImage_(theImage)
</code>```

Also check twice that there's nothing else causing your leaks. Did you use instruments? Check the allocations

Title: NSImage release in AppleScriptObjC

Body:
I have a small AppleScriptObjC app that I use for processing photos. I need to fix a memory leak that I've discovered which seems to be caused by the photos being cached and not being released. This occurs every time I process (initWithContentsOfFile_) which causes the memory usage to increase with each process. The relevant section of my code is:

on applicationWillFinishLaunching_(aNotification)
    set inputPath to (choose folder with prompt "Select The Input Directory" default location (path to desktop folder))
    tell application "finder"
    set imageNames to get name of files of inputPath
    end tell
    set imagesRemaining to (number of items of imageNames) as string
    my errorAlert(imagesRemaining & " photos remaining.")
    if (number of items of imageNames) = 0
    my errorAlert("There are no items in the directory.")
    else
    set numberOfImages to number of items of imageNames
    set currentPath to inputPath & (item 1 of imageNames) as string
    set theImage to initWithContentsOfFile_(POSIX path of currentPath) of alloc() of class "NSImage" of current application
    setImage_(theImage) of imageView
    set theImage to missing value
end if
end applicationWillFinishLaunching_

This part of the script assigns the first photo, the other processing functions are pretty much identical.

I'm either trying to figure out how to correctly release each photo or, alternatively, use the setCacheMode:NSImageCacheNever to disable the caching function. Despite trying for a long time to figure out the proper syntax in ApplescriptObjC, I can't seem to fix the memory leak. Thanks!

For reference, here's the button action which causes the memory to increase every time executed:

    on photoOutput1_(sender)
        if output1 = ""
        set output1 to (choose folder with prompt "Select The Output Path #1" default location (path to desktop folder))
        else
    end if
tell application "Finder"
set ProcessedPhoto to quoted form of (POSIX path of CurrentPath)
set photoNumber to photoNumber + 1
set DateAppend to do shell script "date +%m-%d_%H.%M"
set DateAppend to DateAppend & "_" & photoNumber
set OutputPath to quoted form of ((POSIX path of output1) & DateAppend & ".jpg")
try
    do shell script "mv -n " & ProcessedPhoto & " " & OutputPath
    on error
    my errorAlert("Unable to move the photo. Please try again.")
    return
end try
            set imageNames to get name of files of inputPath
        end tell
set imagesRemaining to (number of items of imageNames) as string
my errorAlert(imagesRemaining & " photos remaining.")
        if (number of items of imageNames) = 0
        imageView's setImage_(missing value)
        my errorAlert("There are no more photos in the directory.")
        else
        set numberOfImages to number of items of imageNames
        set currentPath to inputPath & (item 1 of imageNames) as string
set theImage to missing value
imageView's setImage_(theImage)
set theImage to initWithContentsOfFile_(POSIX path of currentPath) of alloc() of class "NSImage" of current application
        setImage_(theImage) of imageView
tell application "Finder"
        set OutputImageNames to number of files in folder output1
        end tell
        buttonA's setTitle_("A (" & OutputImageNames & ")")
        end if
    end photoOutput1_

Body:
You may try to both release the image variable and the image because in Applescript the contents are copied and not pointers:

set theImage to missing value
imageView's setImage_(theImage)

Also check twice that there's nothing else causing your leaks. Did you use instruments? Check the allocations


问:
OpenFigi API curl to java POST
i  am trying to convert the following curl to java  and i get the error 400

400     Request body must be an array.  The request body is not an array.

curl -v -X POST 'https://api.openfigi.com/v1/mapping'

     --header 'Content-Type: text/json'

     --data '[{"idType":"ID_WERTPAPIER","idValue":"851399","exchCode":"US"}]'

public void r2() throws MalformedURLException, IOException {

```<code>    //String str = "https://www.openfigi.com/search#!?marketSector=Comdty";
    String str = "https://api.openfigi.com/v1/mapping";
    URL url = new URL(str);

    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoOutput(true);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "text/json");

    String input = "'[{\"idType\":\"ID_WERTPAPIER\",\"idValue\":\"851399\",\"exchCode\":\"US\"}]'";
    OutputStream os = conn.getOutputStream();
    os.write(input.getBytes());
    os.flush();
    /*
    if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
        throw new RuntimeException("Failed : HTTP error code : "
                + conn.getResponseCode());
    }*/

    BufferedReader br = new BufferedReader(new InputStreamReader(
            (conn.getInputStream())));

    String output;
    System.out.println("Output from Server .... \n");
    while ((output = br.readLine()) != null) {
        System.out.println(output);
    }

    conn.disconnect();
}
</code>```

thanks

答:
The program work as expected after removing the ' character in the beginning and ending of input.

```<code>String input = "[{\"idType\":\"ID_WERTPAPIER\",\"idValue\":\"851399\",\"exchCode\":\"US\"}]";
OutputStream os = conn.getOutputStream();
os.write(input.getBytes());
os.flush();
</code>```

Title: OpenFigi API curl to java POST

Body:
i  am trying to convert the following curl to java  and i get the error 400

400     Request body must be an array.  The request body is not an array.

curl -v -X POST 'https://api.openfigi.com/v1/mapping'

     --header 'Content-Type: text/json'

     --data '[{"idType":"ID_WERTPAPIER","idValue":"851399","exchCode":"US"}]'

public void r2() throws MalformedURLException, IOException {

    //String str = "https://www.openfigi.com/search#!?marketSector=Comdty";
    String str = "https://api.openfigi.com/v1/mapping";
    URL url = new URL(str);

    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoOutput(true);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "text/json");

    String input = "'[{\"idType\":\"ID_WERTPAPIER\",\"idValue\":\"851399\",\"exchCode\":\"US\"}]'";
    OutputStream os = conn.getOutputStream();
    os.write(input.getBytes());
    os.flush();
    /*
    if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
        throw new RuntimeException("Failed : HTTP error code : "
                + conn.getResponseCode());
    }*/

    BufferedReader br = new BufferedReader(new InputStreamReader(
            (conn.getInputStream())));

    String output;
    System.out.println("Output from Server .... \n");
    while ((output = br.readLine()) != null) {
        System.out.println(output);
    }

    conn.disconnect();
}

thanks

Body:
The program work as expected after removing the ' character in the beginning and ending of input.

String input = "[{\"idType\":\"ID_WERTPAPIER\",\"idValue\":\"851399\",\"exchCode\":\"US\"}]";
OutputStream os = conn.getOutputStream();
os.write(input.getBytes());
os.flush();


问:
Removing special characters VBA Excel
I'm using VBA to read some titles and then copy that information to a PowerPoint presentation.

The problem is that the titles have special characters, but image files that I am also coping over do not.

The title forms part of a path to load a JPEG into a picture container, for example P k.jpg, but the title is called p.k.

I want to be able to ignore the special characters in the title and just get it to see a space instead so it picks up the right JPG file.

How can I do this?

答:
Here is how removed special characters.

I simply applied regex

```<code>Dim strPattern As String: strPattern = "[^a-zA-Z0-9]" 'The regex pattern to find special characters
Dim strReplace As String: strReplace = "" 'The replacement for the special characters
Set regEx = CreateObject("vbscript.regexp") 'Initialize the regex object
Dim GCID As String: GCID = "Text #N/A" 'The text to be stripped of special characters

' Configure the regex object
With regEx
    .Global = True
    .MultiLine = True
    .IgnoreCase = False
    .Pattern = strPattern
End With

' Perform the regex replacement
GCID = regEx.Replace(GCID, strReplace)
</code>```

Title: Removing special characters VBA Excel

Body:
Here is how removed special characters.

I simply applied regex

Dim strPattern As String: strPattern = "[^a-zA-Z0-9]" 'The regex pattern to find special characters
Dim strReplace As String: strReplace = "" 'The replacement for the special characters
Set regEx = CreateObject("vbscript.regexp") 'Initialize the regex object
Dim GCID As String: GCID = "Text #N/A" 'The text to be stripped of special characters

' Configure the regex object
With regEx
    .Global = True
    .MultiLine = True
    .IgnoreCase = False
    .Pattern = strPattern
End With

' Perform the regex replacement
GCID = regEx.Replace(GCID, strReplace)


问:
Writting a file with german letters like ü ,ä, ö and ß in python
I am creating files with this function in python 2

```<code> with io.FileIO(station_data['name']+".pls", "w") as file:
       file.write("[playlist] " + \n + "numberofentries=1" + \n + "File1=" + station_data['streamURL'] + \n + "Title1=" + station_data['name'] )
</code>```

But when in station_[name] is an "Ä" or "Ü" and so on, I get this error

```<code>UnicodeEncodeError: 'ascii' codec can't enconde character u'\xfc' in position 171: ordinal not in range(128)
</code>```

This is the whole script

```<code>import requests
import sys
import os
import json
import io
from objbrowser import browse

class RadioStations():
  user_agent = {'User-agent': 'User-Agent: XBMC Addon Radio'}
  data = []
  no_data = True
  url = "http://radio.de/info/menu/broadcastsofcategory?category=_top"
  try:
    response  = requests.get(url, headers = user_agent)
    data = response.json()
    no_data = False
    print("Data found")
  except requests.HTTPError, e:
    print("HTTP error %s", e.code)
    no_data = False
  except requests.ConnectionError, e:
    data.append({'name': 'no station data'})
    no_data = True
    print("Connection error %s", e)
  print("Getting StreamUrls and creating files")
  for item in data:
     id2 = str(item['id'])
     url = "http://radio.de/info/broadcast/getbroadcastembedded?broadcast=" + id2
     response = requests.get(url, headers = user_agent)
     station_data = response.json()
     with open("{}.pls".format(station_data['name']).encode('utf-8'), "wb") as file:
       txt = "[playlist]\nnumberofentries=1\nFile1={}\nTitle1={}".format(station_data['streamURL'],station_data['name'])
       file.write(txt)
     if "errorCode" in station_data.keys():
       print("no such entry")

  print("Finished")
</code>```

It is based on this script on GitHub

答:
```<code>with open(u"{}.pls".format(station_data['name']), "wb") as file:
       txt = u"[playlist]\nnumberofentries=1\nFile1={}\nTitle1={}".format(station_data['streamURL'],station_data['name']).encode('utf-8')
       file.write(txt)
</code>```

It works with this variant which is combined of your answers

Body:
I am creating files with this function in python 2

 with io.FileIO(station_data['name']+".pls", "w") as file:
       file.write("[playlist] " + \n + "numberofentries=1" + \n + "File1=" + station_data['streamURL'] + \n + "Title1=" + station_data['name'] )

But when in station_[name] is an "Ä" or "Ü" and so on, I get this error

UnicodeEncodeError: 'ascii' codec can't enconde character u'\xfc' in position 171: ordinal not in range(128)

This is the whole script

import requests
import sys
import os
import json
import io
from objbrowser import browse

class RadioStations():
  user_agent = {'User-agent': 'User-Agent: XBMC Addon Radio'}
  data = []
  no_data = True
  url = "http://radio.de/info/menu/broadcastsofcategory?category=_top"
  try:
    response  = requests.get(url, headers = user_agent)
    data = response.json()
    no_data = False
    print("Data found")
  except requests.HTTPError, e:
    print("HTTP error %s", e.code)
    no_data = False
  except requests.ConnectionError, e:
    data.append({'name': 'no station data'})
    no_data = True
    print("Connection error %s", e)
  print("Getting StreamUrls and creating files")
  for item in data:
     id2 = str(item['id'])
     url = "http://radio.de/info/broadcast/getbroadcastembedded?broadcast=" + id2
     response = requests.get(url, headers = user_agent)
     station_data = response.json()
     with open("{}.pls".format(station_data['name']).encode('utf-8'), "wb") as file:
       txt = "[playlist]\nnumberofentries=1\nFile1={}\nTitle1={}".format(station_data['streamURL'],station_data['name'])
       file.write(txt)
     if "errorCode" in station_data.keys():
       print("no such entry")

  print("Finished")

It is based on this script on GitHub

Body:
with open(u"{}.pls".format(station_data['name']), "wb") as file:
       txt = u"[playlist]\nnumberofentries=1\nFile1={}\nTitle1={}".format(station_data['streamURL'],station_data['name']).encode('utf-8')
       file.write(txt)

It works with this variant which is combined of your answers


答:
You can use the following code :</p>

```<code>var userIds = ['Ab526', 'shvx23', '23636dsd'];
var ids = '';
userIds.forEach(function(entry,index) {
    ids += (index == 0) ? entry : ',' + entry;
});
console.log(ids);
</code>```

Title: Javascript Array to MySQL "In" list of values

Body:
You can use the following code :

var userIds = ['Ab526', 'shvx23', '23636dsd'];
var ids = '';
userIds.forEach(function(entry,index) {
    ids += (index == 0) ? entry : ',' + entry;
});
console.log(ids);


问:
PHP: Is it better to concatenate on 1 line or multiple lines? Or is there a difference?
Is there a difference or is one better than the other of the following:

```<code>$var = '';
...
$var .= 'blah blah';
$var .= $var2;
$var .= 'blah blah';
</code>```

Or

```<code>$var = '';
...
$var .= 'blah blah' . $var2 . 'blah blah';
</code>```

Is there a speed difference or is there a reason why you'd pick one over the other?

答:
Both PEZ and Topbit are correct. I just want to point out something I think looks better than has been seen here:

```<code>$var  = "line 1 \n";
$var .= "line 2 \n";
</code>```

versus

```<code>$var = "line 1 \n"
     . "line 2 \n";
</code>```

I much prefer the second one to the first one as visually it is obvious your result is the one string $var. It also prevents stupid bugs like:

```<code>$var  = "line 1 \n";
$var .= "line 2 \n";
$vat .= "line 3 \n";
$var .= "line 4 \n";
</code>```

OwnerDisplayName: Darryl Hein

Body:
Is there a difference or is one better than the other of the following:

$var = '';
...
$var .= 'blah blah';
$var .= $var2;
$var .= 'blah blah';

Or

$var = '';
...
$var .= 'blah blah' . $var2 . 'blah blah';

Is there a speed difference or is there a reason why you'd pick one over the other?

LastEditorDisplayName: Paul Dixon

Body:
Both PEZ and Topbit are correct. I just want to point out something I think looks better than has been seen here:

$var  = "line 1 \n";
$var .= "line 2 \n";

versus

$var = "line 1 \n"
     . "line 2 \n";

I much prefer the second one to the first one as visually it is obvious your result is the one string $var. It also prevents stupid bugs like:

$var  = "line 1 \n";
$var .= "line 2 \n";
$vat .= "line 3 \n";
$var .= "line 4 \n";


问:
ICloneable question
If a class implemented ICloneable, what does that mean?

答:
ICloneable is not meaningful by itself, but may be useful in conjunction with other constraints (e.g. one could provide that a parameter must be a Foo that implements ICloneable).  Thus, one could have a Foo, a CloneableFoo, an AdvancedFoo, and a CloneableAdvancedFoo, allowing Foo derivatives that support cloning to be distinguished from those that do not, but also allowing routines that expect a cloneable Foo to accept a cloneable derivative of Foo.

Unfortunately, while a function parameter passed with IClonable and Foo constraints may be used as an IClonable and as a Foo, without typecasts, there's no way to create a field meeting such criteria, nor is there any way to typecast a field.  A remedy for this may be to create an ICloneable(Of T As ICloneable(Of T)), which contains a "Clone" method that returns T, and a "Self" method which also returns T (Thus, a field holding an "ICloneable Of Foo" could be accessed as a Foo via the "Self" method).  A little care would be needed to make this all work, but the pattern should be quite nice.

Title: ICloneable question


问:
Excel VBA macro to copy specific rows and delete it
Here what I want to do:

I have 2 worksheet named Pending & Records.

Columns in "Pending" worksheet: A: Date, B: Delivery To, C: Delivery to office, D: Delivery to Manager, E: Subject, F: Date & G: Letter No.

Columns in "Records" worksheet: A: Date, B: Letter No. & C: Subject.

When entered number in cell G (Letter No.) of "Pending" worksheet, the below cells copy to specified cells in "Records" worksheet.

E (Subject) in "Pending" worksheet sit in C (subject) of "Records" worksheet.

F (Date) in "Pending" worksheet sit in A (Date) of "Records" worksheet.

G (Letter No.) in "Pending" worksheet sit in B (Letter No.) of "Records" worksheet.

Delete the row that was copied in "Pending" worksheet.

Sort the rows in "Records" worksheet according to Letter No. (Column C).

This is codes that I write for what I want to do (not work good) and some screenshot:

```<code>Private Sub Worksheet_Change(ByVal Target As Range)

If Target.Column = 6 Then
    If Len(Target.Value) > 0 Then
        Dim r As Range
        Dim a As String
        Dim b As String

        b = "sheet3!A" & Sheet1.Cells(1, 9) + 3 & ":C" & Sheet1.Cells(1, 9) + 3
        a = "E" & Target.Row & ":G" & Target.Row
        Dim r1, r2 As Range
        r1 = Sheet1.Range(a)
        Sheet2.Range(b).Value = r1
        Sheet1.Range(a).EntireRow.Delete
    End If
End If

End Sub
</code>```

picture 1
picture 2

答:
Put the code below in "Pending" worksheet module, under Worksheet_Change event.

First, you should learn to enjoy the benefits of the Target variable.

For instance, if you want to copy a value from column "F" at the same row of Column "G" (your Target), you can use Target.Offset(, -1).Copy.

If you want to delete the entire row of your Target after it's copied, simply use Target.EntireRow.Delete.

Another thing, according to your screen-shot (and the first part of your post) "Letter No" is located at Column "B" in "Records" sheet. Therefore, the Sort is done according to Column "B".

Code

```<code>Option Explicit

Private Sub Worksheet_Change(ByVal Target As range)

Dim RecSht      As Worksheet
Dim NextRow     As Long

Application.ScreenUpdating = False
Application.EnableEvents = False

If Target.Column = 7 Then ' Column "G"
    If Target.Value <> "" Then
        Set RecSht = Worksheets("Records")
        NextRow = RecSht.Cells(RecSht.Rows.Count, "A").End(xlUp).Row + 1 ' <-- get next empty row at Column A in "Records" sheet

        RecSht.Range("B" & NextRow).Value = Target.Value ' column "G"
        RecSht.Range("A" & NextRow).Value = Target.Offset(, -1).Value ' column "F"
        RecSht.Range("C" & NextRow).Value = Target.Offset(, -2).Value ' column "E"

        Target.EntireRow.Delete ' <-- Delete entire row that was copied

        '--- Sort Section ---
        RecSht.Range("A2:C" & NextRow).Sort key1:=RecSht.Range("B2:B" & NextRow), _
                                         order1:=xlAscending, Header:=xlYes
    End If
End If

Application.EnableEvents = True
Application.ScreenUpdating = True

End Sub
</code>```

Body:
Here what I want to do:

I have 2 worksheet named Pending & Records.

Columns in "Pending" worksheet: A: Date, B: Delivery To, C: Delivery to office, D: Delivery to Manager, E: Subject, F: Date & G: Letter No.

Columns in "Records" worksheet: A: Date, B: Letter No. & C: Subject.

When entered number in cell G (Letter No.) of "Pending" worksheet, the below cells copy to specified cells in "Records" worksheet.

E (Subject) in "Pending" worksheet sit in C (subject) of "Records" worksheet.

F (Date) in "Pending" worksheet sit in A (Date) of "Records" worksheet.

G (Letter No.) in "Pending" worksheet sit in B (Letter No.) of "Records" worksheet.

Delete the row that was copied in "Pending" worksheet.

Sort the rows in "Records" worksheet according to Letter No. (Column C).

This is codes that I write for what I want to do (not work good) and some screenshot:

Private Sub Worksheet_Change(ByVal Target As Range)

If Target.Column = 6 Then
    If Len(Target.Value) > 0 Then
        Dim r As Range
        Dim a As String
        Dim b As String

        b = "sheet3!A" & Sheet1.Cells(1, 9) + 3 & ":C" & Sheet1.Cells(1, 9) + 3
        a = "E" & Target.Row & ":G" & Target.Row
        Dim r1, r2 As Range
        r1 = Sheet1.Range(a)
        Sheet2.Range(b).Value = r1
        Sheet1.Range(a).EntireRow.Delete
    End If
End If

End Sub

picture 1
picture 2

Body:
Put the code below in "Pending" worksheet module, under Worksheet_Change event.

First, you should learn to enjoy the benefits of the Target variable.

For instance, if you want to copy a value from column "F" at the same row of Column "G" (your Target), you can use Target.Offset(, -1).Copy.

If you want to delete the entire row of your Target after it's copied, simply use Target.EntireRow.Delete.

Another thing, according to your screen-shot (and the first part of your post) "Letter No" is located at Column "B" in "Records" sheet. Therefore, the Sort is done according to Column "B".

Code

Option Explicit

Private Sub Worksheet_Change(ByVal Target As range)

Dim RecSht      As Worksheet
Dim NextRow     As Long

Application.ScreenUpdating = False
Application.EnableEvents = False

If Target.Column = 7 Then ' Column "G"
    If Target.Value <> "" Then
        Set RecSht = Worksheets("Records")
        NextRow = RecSht.Cells(RecSht.Rows.Count, "A").End(xlUp).Row + 1 ' <-- get next empty row at Column A in "Records" sheet

        RecSht.Range("B" & NextRow).Value = Target.Value ' column "G"
        RecSht.Range("A" & NextRow).Value = Target.Offset(, -1).Value ' column "F"
        RecSht.Range("C" & NextRow).Value = Target.Offset(, -2).Value ' column "E"

        Target.EntireRow.Delete ' <-- Delete entire row that was copied

        '--- Sort Section ---
        RecSht.Range("A2:C" & NextRow).Sort key1:=RecSht.Range("B2:B" & NextRow), _
                                         order1:=xlAscending, Header:=xlYes
    End If
End If

Application.EnableEvents = True
Application.ScreenUpdating = True

End Sub


问:
Using writel to write 4 bit to ioremap-ed memory address
I'm new to kernel programming, and now trying to write some values to a 32-bit GPIO register in a device driver. The I/O is ioremap()-ed to a memory address. The problem is, I don't know how writel()/writeb()/writew() writes bits to the addresses.

The vendor documents says the register is on 0xE5200000. The bits I have to write to is the [0:3] bits and leave the remaining 28 bits (the [4:31] bits) as zeros.

This is part of the code in the device driver I've written so far:

```<code>#define TCON_ADDR 0xE250000 // The address as provided by the vendor
static void *TIMER_CON_ADDR;
// I have to map and write to the address when the device is opened
static int on_dev_open(struct inode *inode, struct file *file) {
    unsigned int data;
    TIMER_CON_ADDR = ioremap(TCON_ADDR, 4); // Map the [0:4] bits to TIMER_CON_ADDR
    data = 4; // 0100 in binary
    writel(data, TIMER_CON_ADDR); // Write 0100 to TIMER_CON_ADDR
    return 0;
}
</code>```

The above code might just be outright gibberish to you all, but I am not familiar with write(l|w|b) and ioremap().

So my questions are:

Did I map the [0:4] bits to TIMER_CON_ADDR correctly?

If not, how do I map them correctly?

After I have correctly mapped the 4 bits, how do I use any of the write(1|w|b) functions to write bits (0100) to TIMER_CON_ADDR in the correct order?

What does write(l|w|b) do under the hood to write bits?

Is there any information I've missed / got wrong?

Thanks for all your help in advance.

答:
Did I map the [0:4] bits to TIMER_CON_ADDR correctly?

no, you write 32bits, writel  write 4 bytes, 4 * 8 = 32 bits

If not, how do I map them correctly?

No way to map 4 bits, minimum 8 bits = 1 bytes, but if you work with 32bit
register you need map 32 bits = 4 bytes. Also do not forget check and handle
errors.

After I have correctly mapped the 4 bits, how do I use any of the write(1|w|b) functions to write bits (0100) to TIMER_CON_ADDR in the correct order?

you need use readl, kernel full of examples, just run grep inside drivers subdirectory of linux kernel source tree.
General idea read/write:

```<code>u32 reg = readl(TIMER_CON_ADDR);
reg &= ~0xfu;
reg |= 4;
writel(reg, TIMER_CON_ADDR);
</code>```

What does write(l|w|b) do under the hood to write bits?

look at source code, it just simple C functions, like:

```<code>static inline void __raw_writel(u32 value, volatile void __iomem *addr)
{
    *(volatile u32 __force *)addr = value;
}
</code>```

the main idea is telling to compiler that it should not remove
your memory reading/writing

Is there any information I've missed / got wrong?

read source code of similar drivers, it is already contains almost
all solutions for such simple drivers.

Body:
I'm new to kernel programming, and now trying to write some values to a 32-bit GPIO register in a device driver. The I/O is ioremap()-ed to a memory address. The problem is, I don't know how writel()/writeb()/writew() writes bits to the addresses.

The vendor documents says the register is on 0xE5200000. The bits I have to write to is the [0:3] bits and leave the remaining 28 bits (the [4:31] bits) as zeros.

This is part of the code in the device driver I've written so far:

#define TCON_ADDR 0xE250000 // The address as provided by the vendor
static void *TIMER_CON_ADDR;
// I have to map and write to the address when the device is opened
static int on_dev_open(struct inode *inode, struct file *file) {
    unsigned int data;
    TIMER_CON_ADDR = ioremap(TCON_ADDR, 4); // Map the [0:4] bits to TIMER_CON_ADDR
    data = 4; // 0100 in binary
    writel(data, TIMER_CON_ADDR); // Write 0100 to TIMER_CON_ADDR
    return 0;
}

The above code might just be outright gibberish to you all, but I am not familiar with write(l|w|b) and ioremap().

So my questions are:

Did I map the [0:4] bits to TIMER_CON_ADDR correctly?

If not, how do I map them correctly?

After I have correctly mapped the 4 bits, how do I use any of the write(1|w|b) functions to write bits (0100) to TIMER_CON_ADDR in the correct order?

What does write(l|w|b) do under the hood to write bits?

Is there any information I've missed / got wrong?

Thanks for all your help in advance.

Body:
Did I map the [0:4] bits to TIMER_CON_ADDR correctly?

no, you write 32bits, writel  write 4 bytes, 4 * 8 = 32 bits

If not, how do I map them correctly?

No way to map 4 bits, minimum 8 bits = 1 bytes, but if you work with 32bit
register you need map 32 bits = 4 bytes. Also do not forget check and handle
errors.

After I have correctly mapped the 4 bits, how do I use any of the write(1|w|b) functions to write bits (0100) to TIMER_CON_ADDR in the correct order?

you need use readl, kernel full of examples, just run grep inside drivers subdirectory of linux kernel source tree.
General idea read/write:

u32 reg = readl(TIMER_CON_ADDR);
reg &= ~0xfu;
reg |= 4;
writel(reg, TIMER_CON_ADDR);

What does write(l|w|b) do under the hood to write bits?

look at source code, it just simple C functions, like:

static inline void __raw_writel(u32 value, volatile void __iomem *addr)
{
    *(volatile u32 __force *)addr = value;
}

the main idea is telling to compiler that it should not remove
your memory reading/writing

Is there any information I've missed / got wrong?

read source code of similar drivers, it is already contains almost
all solutions for such simple drivers.


问:
Correctly convert String array to String and back in java
I have a following code:

```<code>String[] stringArray = new String[] { "One,", "Two", "Three" };
System.out.println(Arrays.toString(stringArray));
</code>```

which produces the following string:

```<code>[One,, Two, Three]
</code>```

Right now It is impossible to convert this string back into the same String[] with 3 elements because of two consecutive commas ,,

How to correctly make this conversion ?

UPDATED

```<code>Arrays.toString(stringArray)
</code>```

is just a particular case and I'm not limited to use only this approach. I need to implement approach where conversion from String[] to String and back from String to String[] will be idempotent operation.

答:
You state that "Arrays.toString is absolutely not required."1

I suggest you serialize the Array to Base64:

```<code>public String serializeArray(final String[] data) {
    try (final ByteArrayOutputStream boas = new ByteArrayOutputStream();
         final ObjectOutputStream oos = new ObjectOutputStream(boas)) {
        oos.writeObject(data);
        return Base64.getEncoder().encodeToString(boas.toByteArray());
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
</code>```

Then deserialize the Base64 to an array:

```<code>public String[] deserializeArray(final String data) {
    try (final ByteArrayInputStream bias = new ByteArrayInputStream(Base64.getDecoder().decode(data));
         final ObjectInputStream ois = new ObjectInputStream(bias)) {
        return (String[]) ois.readObject();
    } catch (IOException | ClassNotFoundException e) {
        throw new RuntimeException(e);
    }
}
</code>```

This requires Java 8.

Example:

```<code>public static void main(String args[]) throws Exception {
    String[] stringArray = new String[]{"One,", "Two", "Three"};
    String serialized = serializeArray(stringArray);
    String[] deserialized = deserializeArray(serialized);
    System.out.println(Arrays.toString(stringArray));
    System.out.println(serialized);
    System.out.println(Arrays.toString(deserialized));
}
</code>```

Output

```<code>[One,, Two, Three]
rO0ABXVyABNbTGphdmEubGFuZy5TdHJpbmc7rdJW5+kde0cCAAB4cAAAAAN0AARPbmUsdAADVHdvdAAFVGhyZWU=
[One,, Two, Three]
</code>```

Note, this works for any Object that implements Serializable, not just String[].

As a simple alternative, you could replace , by \, before joining the array and then also replace \, by , after splitting it. This relies on the standard "escaped delimiter" pattern that CSV uses. But it will fail if the user inputs \, somewhere in the input, so is less robust: YMMV.

```<code>public String serializeArray(final String[] data) {
    return Arrays.stream(data)
            .map(s -> s.replace(",", "\\,"))
            .collect(joining(","));
}

public String[] deserializeArray(final String data) {
    return Pattern.compile("(?<!\\\\),").splitAsStream(data)
            .map(s -> s.replace("\\,", ","))
            .toArray(String[]::new);
}
</code>```

Body:
I have a following code:

String[] stringArray = new String[] { "One,", "Two", "Three" };
System.out.println(Arrays.toString(stringArray));

which produces the following string:

[One,, Two, Three]

Right now It is impossible to convert this string back into the same String[] with 3 elements because of two consecutive commas ,,

How to correctly make this conversion ?

UPDATED

Arrays.toString(stringArray)

is just a particular case and I'm not limited to use only this approach. I need to implement approach where conversion from String[] to String and back from String to String[] will be idempotent operation.

Body:
You state that "Arrays.toString is absolutely not required."1

I suggest you serialize the Array to Base64:

public String serializeArray(final String[] data) {
    try (final ByteArrayOutputStream boas = new ByteArrayOutputStream();
         final ObjectOutputStream oos = new ObjectOutputStream(boas)) {
        oos.writeObject(data);
        return Base64.getEncoder().encodeToString(boas.toByteArray());
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

Then deserialize the Base64 to an array:

public String[] deserializeArray(final String data) {
    try (final ByteArrayInputStream bias = new ByteArrayInputStream(Base64.getDecoder().decode(data));
         final ObjectInputStream ois = new ObjectInputStream(bias)) {
        return (String[]) ois.readObject();
    } catch (IOException | ClassNotFoundException e) {
        throw new RuntimeException(e);
    }
}

This requires Java 8.

Example:

public static void main(String args[]) throws Exception {
    String[] stringArray = new String[]{"One,", "Two", "Three"};
    String serialized = serializeArray(stringArray);
    String[] deserialized = deserializeArray(serialized);
    System.out.println(Arrays.toString(stringArray));
    System.out.println(serialized);
    System.out.println(Arrays.toString(deserialized));
}

Output

[One,, Two, Three]
rO0ABXVyABNbTGphdmEubGFuZy5TdHJpbmc7rdJW5+kde0cCAAB4cAAAAAN0AARPbmUsdAADVHdvdAAFVGhyZWU=
[One,, Two, Three]

Note, this works for any Object that implements Serializable, not just String[].

As a simple alternative, you could replace , by \, before joining the array and then also replace \, by , after splitting it. This relies on the standard "escaped delimiter" pattern that CSV uses. But it will fail if the user inputs \, somewhere in the input, so is less robust: YMMV.

public String serializeArray(final String[] data) {
    return Arrays.stream(data)
            .map(s -> s.replace(",", "\\,"))
            .collect(joining(","));
}

public String[] deserializeArray(final String data) {
    return Pattern.compile("(?<!\\\\),").splitAsStream(data)
            .map(s -> s.replace("\\,", ","))
            .toArray(String[]::new);
}


问:
print python dictionary in ruby hash format
I have a simple python dict and it prints in below format,

```<code>{'stats1': {'var': {'avail': 'yes'}, 'target': {'avail': 'no'}}}
</code>```

But am looking way to print this in below format like ruby hash,

```<code>{'stats1'=> {'var'=> {'avail'=> 'yes'}, 'target'=> {'avail'=> 'no'}}}
</code>```

I tried Google to get the way to print python dict in ruby hash format but no luck.

答:
can be done with a recursive scan of the dictionary, checking if value is instance of dictionary to make a recursive call, otherwise just print (escaping of the quote char is also handled)

```<code>def rp(d,outstream):
    outstream.write("{")
    first_print = True
    for k,v in d.items():
        if not first_print:
            outstream.write(",")
        else:
            first_print = False
        outstream.write("'{}'=> ".format(k.replace("'",r"\'")))
        if isinstance(v,dict):
            rp(v,outstream)
        else:
            outstream.write("'{}'".format(v.replace("'",r"\'")))

    outstream.write("}")
</code>```

testing can be done using sys.stdout or io to get a str object

```<code>import io

d = {'stats1': {'var': {'avail': 'yes'}, 'target': {'avail': 'no'}}}

outs = io.StringIO()
rp(d,outs)
print(outs.getvalue())
</code>```

result:

```<code>{'stats1'=> {'target'=> {'avail'=> 'no'},'var'=> {'avail'=> 'yes'}}}
</code>```

Of course this solution is quite frail: passing a list of dicts won't work for instance. Can be done, of course, with more coding and isinstance. And there are probably more cornercases.

Body:
I have a simple python dict and it prints in below format,

{'stats1': {'var': {'avail': 'yes'}, 'target': {'avail': 'no'}}}

But am looking way to print this in below format like ruby hash,

{'stats1'=> {'var'=> {'avail'=> 'yes'}, 'target'=> {'avail'=> 'no'}}}

I tried Google to get the way to print python dict in ruby hash format but no luck.

Body:
can be done with a recursive scan of the dictionary, checking if value is instance of dictionary to make a recursive call, otherwise just print (escaping of the quote char is also handled)

def rp(d,outstream):
    outstream.write("{")
    first_print = True
    for k,v in d.items():
        if not first_print:
            outstream.write(",")
        else:
            first_print = False
        outstream.write("'{}'=> ".format(k.replace("'",r"\'")))
        if isinstance(v,dict):
            rp(v,outstream)
        else:
            outstream.write("'{}'".format(v.replace("'",r"\'")))

    outstream.write("}")

testing can be done using sys.stdout or io to get a str object

import io

d = {'stats1': {'var': {'avail': 'yes'}, 'target': {'avail': 'no'}}}

outs = io.StringIO()
rp(d,outs)
print(outs.getvalue())

result:

{'stats1'=> {'target'=> {'avail'=> 'no'},'var'=> {'avail'=> 'yes'}}}

Of course this solution is quite frail: passing a list of dicts won't work for instance. Can be done, of course, with more coding and isinstance. And there are probably more cornercases.


问:
How to create modal box using html, css and jquery?
How to create modal box using html, css and jquery?
    </p>

```<code><button id="myBtn">Open Modal</button>
</code>```

<p>
    </p>

```<code>  <!-- Modal content -->
  <div class="modal-content">
    <span class="close">×</span>
    <p>Some text in the Modal..</p>
  </div>

</div>
</code>```

答:
Why don't you use JQuery UI Dialog, its very handy, if you still want to do this using just jquery then you can try below.

$('#myBtn').click(function(){
    $('.modal-content').show();
    $('body').toggleClass('modalbackground');
});

$('.modal-content .close').click(function(){
    $('.modal-content').hide();
    $('body').toggleClass('modalbackground');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.modal-content {
    display: none;
    position: fixed;
}

.modalbackground {
    width: 100%;
    height: 100%;
    background: rgba(0,0,0,0.25);
    z-index: 1;
}

.modal-content {
    width: 33.333%;
    top: 20%;
    left: 33.3333%;
    background: white;
    z-index: 2;
}

.close{
    cursor: pointer;
}</code>```

<button id="myBtn">Open Modal</button>

    ×

Some text in the Modal..

```

Body:
How to create modal box using html, css and jquery?

<button id="myBtn">Open Modal</button>

    ×

Some text in the Modal..

Body:
Why don't you use JQuery UI Dialog, its very handy, if you still want to do this using just jquery then you can try below.

$('#myBtn').click(function(){
    $('.modal-content').show();
    $('body').toggleClass('modalbackground');
});

$('.modal-content .close').click(function(){
    $('.modal-content').hide();
    $('body').toggleClass('modalbackground');
});

.modal-content {
    display: none;
    position: fixed;
}

.modalbackground {
    width: 100%;
    height: 100%;
    background: rgba(0,0,0,0.25);
    z-index: 1;
}

.modal-content {
    width: 33.333%;
    top: 20%;
    left: 33.3333%;
    background: white;
    z-index: 2;
}

.close{
    cursor: pointer;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="myBtn">Open Modal</button>

<div class="modal-content">
    <span class="close">&times;</span>
    <p>Some text in the Modal..</p>
  </div>


问:
Why the regex with re.findall() doesn't work?
I tried to extract the text from a html code. And here's my code:

```<code>import re
Luna = open('D:\Python\Luna.txt','r+')
text=Luna.read()
txt=re.findall('<p>\s+(.*)</p>',text)
print txt
</code>```

However, it only eliminate the part before the first
 and everything after the first
 remained. What should I do to improve my code so that it would only return the part between
and
 ?
Here's a part of the original html code:

```<code>src="/advjs/gg728x90.js"></script></td>  </tr></table><div class="text" align="justify"></p><p> Sure. Eye of newt. Tongue of snake.</p><p>  She added, “Since you’re taking Skills for Living, it’ll be good practice.”</p><p>  For what? I wondered. Poisoning my family? “I have to baby-sit,” I said, a little too gleefully.</p>
</code>```

答:
I strongly recommend you use a proper HTML parser, like BeautifulSoup:

```<code>from bs4 import BeautifulSoup

soup = BeautifulSoup(Luna.read())
para_strings = (p.get_text() for p in soup.find_all('p'))
txt = [p.strip() for p in para_strings if p.startswith(' ')]
</code>```

You can fix your regex by using a non-greedy operator (append a ? question mark to the * operator):

```<code>txt=re.findall('<p>\s+(.*?)</p>',text)
</code>```

However, you'll most likely run into other issues with regex parsing, as HTML is not a regular language.

Body:
I tried to extract the text from a html code. And here's my code:

import re
Luna = open('D:\Python\Luna.txt','r+')
text=Luna.read()
txt=re.findall('
\s+(.*)
',text)
print txt

However, it only eliminate the part before the first
 and everything after the first
 remained. What should I do to improve my code so that it would only return the part between
and
 ?
Here's a part of the original html code:

src="/advjs/gg728x90.js"></script>

 Sure. Eye of newt. Tongue of snake.

  She added, “Since you’re taking Skills for Living, it’ll be good practice.”

  For what? I wondered. Poisoning my family? “I have to baby-sit,” I said, a little too gleefully.

Body:
I strongly recommend you use a proper HTML parser, like BeautifulSoup:

from bs4 import BeautifulSoup

soup = BeautifulSoup(Luna.read())
para_strings = (p.get_text() for p in soup.find_all('p'))
txt = [p.strip() for p in para_strings if p.startswith(' ')]

You can fix your regex by using a non-greedy operator (append a ? question mark to the * operator):

txt=re.findall('<p>\s+(.*?)</p>',text)

However, you'll most likely run into other issues with regex parsing, as HTML is not a regular language.


问:
How to show the required fields on the first access of a View?
I am using MVC 2.0 and I wonder know how to show my required fields on the view on first acess.

For example.. I have a page that I can register a person and also I have my fields:

Name;

Age;

City;

Country;

Phone;

But, just "Name" and "Phone" fields are requireds. I alread have the validation in my server side, but, I want that when somebody load the page, the page shows the required fields.

For example:
 Name [Put_text_here___________] *

I have on my pages:

```<code><%= Html.TextBoxFor(model => model.soliInscricaoImobiliaria})%>

<%= Html.ValidationMessageFor(model => model.Name, "*") %>
</code>```

How do I do that?

Best regards,
Dan

答:
This is not super user-friendly, and I'd look at putting it into a @helper block. But short of simply hard-coding an asterisk into the form...

```<code>@(ViewData.ModelMetadata.Properties.First(m => m.PropertyName == "Name").IsRequired ? "*" : "")
</code>```

More information here:

http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-1-introduction.html
http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-2-modelmetadata.html
http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-4-custom-object-templates.html

Body:
I am using MVC 2.0 and I wonder know how to show my required fields on the view on first acess.

For example.. I have a page that I can register a person and also I have my fields:

Name;

Age;

City;

Country;

Phone;

But, just "Name" and "Phone" fields are requireds. I alread have the validation in my server side, but, I want that when somebody load the page, the page shows the required fields.

For example:
 Name [Put_text_here___________] *

I have on my pages:

<%= Html.TextBoxFor(model => model.soliInscricaoImobiliaria})%>

<%= Html.ValidationMessageFor(model => model.Name, "*") %>

How do I do that?

Best regards,
Dan

Body:
This is not super user-friendly, and I'd look at putting it into a @helper block. But short of simply hard-coding an asterisk into the form...

@(ViewData.ModelMetadata.Properties.First(m => m.PropertyName == "Name").IsRequired ? "*" : "")

More information here:

http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-1-introduction.html
http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-2-modelmetadata.html
http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-4-custom-object-templates.html


问:
trigger jquery using button in dropdown
I have a series of dropdown buttons on a page and am trying to trigger a single function with the button's id. Why is my function not getting called?

```<code><div class="dropdown">
  <button class="btn btn-secondary dropdown-toggle btn-sm btn-block" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
    Options
  </button>
  <div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
    <a class="dropdown-item" href="lists/{{ $list['id'] }}/details">Edit Details</a>
    <a class="dropdown-item" href="#">Convert to...</a>
    <a class="dropdown-item" href="#" id= "{{ $list['id'] }}" class="copy-row">Copy</a>
  </div>
</div>
</code>```

and the JS:

```<code>$('.copy-row').click( function(e) {

  e.preventDefault();
  var token = $('meta[name="csrf-token"]').attr('content');

  var id = $(this).attr('id');
  $.ajax({url: '/lists/' + id, data: {_token:token}, type: 'PUT'})
  window.location.reload();

});
</code>```

答:
I had two separate class statements:

```<code><a class="dropdown-item" href="#" id= "{{ $list['id'] }}" class="copy-row">Copy</a>
</code>```

changed to

```<code><a class="dropdown-item copy-row" href="#" id= "{{ $list['id'] }}">Copy</a>
</code>```

Title: trigger jquery using button in dropdown

Body:
I have a series of dropdown buttons on a page and am trying to trigger a single function with the button's id. Why is my function not getting called?

  <button class="btn btn-secondary dropdown-toggle btn-sm btn-block" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
    Options
  </button>

    Edit Details
    Convert to...
    Copy

and the JS:

$('.copy-row').click( function(e) {

  e.preventDefault();
  var token = $('meta[name="csrf-token"]').attr('content');

  var id = $(this).attr('id');
  $.ajax({url: '/lists/' + id, data: {_token:token}, type: 'PUT'})
  window.location.reload();

});

Body:
I had two separate class statements:

<a class="dropdown-item" href="#" id= "{{ $list['id'] }}" class="copy-row">Copy</a>

changed to

<a class="dropdown-item copy-row" href="#" id= "{{ $list['id'] }}">Copy</a>


问:
Provide security between two web applications
I have an application A where I log in normally and after this login the user can access another application B but application B has no authentication. My problem is that the user can access application B directly without credentials. How do I get my B application to use the same authenticated session from application A.</p>

答: Try using cookies. When user logs in in A then a cookie is stored and B checks if the cookie is set and which content it has and opens a new session.</p>


问:
Stop a running AppleScript in such a way that calls its error handler
I run automation scripts using ssh. The scripts are written in AppleScript. I would like to be able to stop a script in such a way that it's error handler is called rather than just stopping dead.

Using the following AppleScript as an example:

```<code>on run

    try
        repeat with i from 1 to 1000
            delay 1
        end repeat

    on error
        beep 1
    end try

end run
</code>```

I save the script to my home folder as test.applescript

I then run it from the terminal:

```<code>osascript ~/test.applescript
</code>```

Is there anyway to stop the script from the command line in such a way that you hear the beep? using kill -s SIGHUP stops the script but I do not hear a beep. I've tried all the signals to no avail.

The closest I've gotten is by using the following:

osacriptmonitor ~/test.applescript and then using the gear menu to cancel. By doing that I hear the beep. (please see Running AppleScripts through the ScriptMonitor.app Utility for more information on osascriptmonitor).

It's also important to note that when I use osacriptmonitor instead osascript, I get the following from ps -ax | grep osascript:

/usr/bin/osascript -T 4984 -P /Users/david/test.applescript

Does anyone know what -T and -P are used for? I have been unable to find any reference to those options.

答:
Applescript runs from beginning to the end. If you kill it the whole script is removed.

If you want to have a more controllable ending you need to include another routine in your loop. E.g. check something outside the script every tenth loop. Then you only need to change that outside value to trigger something else inside your script.

Body:
I run automation scripts using ssh. The scripts are written in AppleScript. I would like to be able to stop a script in such a way that it's error handler is called rather than just stopping dead.

Using the following AppleScript as an example:

on run

    try
        repeat with i from 1 to 1000
            delay 1
        end repeat

    on error
        beep 1
    end try

end run

I save the script to my home folder as test.applescript

I then run it from the terminal:

osascript ~/test.applescript

Is there anyway to stop the script from the command line in such a way that you hear the beep? using kill -s SIGHUP stops the script but I do not hear a beep. I've tried all the signals to no avail.

The closest I've gotten is by using the following:

osacriptmonitor ~/test.applescript and then using the gear menu to cancel. By doing that I hear the beep. (please see Running AppleScripts through the ScriptMonitor.app Utility for more information on osascriptmonitor).

It's also important to note that when I use osacriptmonitor instead osascript, I get the following from ps -ax | grep osascript:

/usr/bin/osascript -T 4984 -P /Users/david/test.applescript

Does anyone know what -T and -P are used for? I have been unable to find any reference to those options.


问:
php or html, css and js
I am programming a school website where I want an easy system for teachers, where they could post news, informations, etc. I also want a timetable there. Which language is best suited for these needs?

Thanks
Adam

答: You may be trying to learn https://moodle.org/ ( this's open source )  if you can not create their own learning website</p>

Title: php or html, css and js


答:
First You should learn what is a static website and what is dynamic website. Then decide which one you want to create.
In your description you wrote:

I am programming a school website where I want an easy system for
  teachers, where they could post news, informations, etc. I also want a
  timetable there. Which language is best suited for these needs?

You basically asked for a site in which teachers could post things like news, informations, etc. That's a dynamic content. Therefor you will need php and mysql database to create something like this. Whereas to design the layout of the website you will need html, css and javascript.

Title: php or html, css and js

Body:
I am programming a school website where I want an easy system for teachers, where they could post news, informations, etc. I also want a timetable there. Which language is best suited for these needs?

Thanks
Adam


问:
Select first visible cell of new row in DataGridView
I'm trying to focus input and fire the editing event on each new row that I add to a DataGridView in my form.

This is the code I am trying to user to achieve this.

```<code>Private Sub grd_GoldAdders_RowsAdded(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewRowsAddedEventArgs) Handles grd_GoldAdders.RowsAdded
        Dim grid As DataGridView = DirectCast(sender, DataGridView)

        grid.ClearSelection()

        If grid.Rows(e.RowIndex).Cells("grid_flag").FormattedValue = Constants.[New] Then

            For Each cell As DataGridViewCell In grid.Rows(e.RowIndex).Cells
                If Not cell.Visible Then Continue For
                grid.CurrentCell = cell
                grid.BeginEdit(False)
                Exit For
            Next

        End If

    End Sub
</code>```

The "grid_flag" is a hidden cell which is used to store custom states for a row.

Prior to adding a row, this is what we see on the form:

This is what we see when we actually try and add a new row:

Notice that both the column 0,0 and the first visible column of the new row are selected, but the column 0,0 has the focus.  I do not wish for 0,0 to either get selected or have the focus.  I also see here that the row indicator is pointing at row 0 too...

This is how I would like to see things after clicking my Add button:

Does anyone know where I am going wrong with the code? I've searched SO for the most part of the day trying to solve this one.

答:
Instead of using your DataGridView's RowAdded event to set the CurrentCell, add the following code wherever you're adding a new record to your DGV (in your Add button's Click event I assume):

```<code>''# Add the new record to your Data source/DGV.

For Each row As DataGridViewRow In grd_GoldAdders.Rows
    If row.Cells("grid_flag").FormattedValue = Constants.[New] Then
        grd_GoldAdders.CurrentCell = row.Cells("AssySiteColumn")  ''# I'm calling the first column in your DGV 'AssySiteColumn'.
        grd_GoldAdders.BeginEdit(False)
        Exit For
    End If
Next
</code>```

This code simply loops through all the rows in your DGV and specifies as the CurrentCell the first cell in the first row with your Constants.[New] flag value.

Body:
I'm trying to focus input and fire the editing event on each new row that I add to a DataGridView in my form.

This is the code I am trying to user to achieve this.

Private Sub grd_GoldAdders_RowsAdded(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewRowsAddedEventArgs) Handles grd_GoldAdders.RowsAdded
        Dim grid As DataGridView = DirectCast(sender, DataGridView)

        grid.ClearSelection()

        If grid.Rows(e.RowIndex).Cells("grid_flag").FormattedValue = Constants.[New] Then

            For Each cell As DataGridViewCell In grid.Rows(e.RowIndex).Cells
                If Not cell.Visible Then Continue For
                grid.CurrentCell = cell
                grid.BeginEdit(False)
                Exit For
            Next

        End If

    End Sub

The "grid_flag" is a hidden cell which is used to store custom states for a row.

Prior to adding a row, this is what we see on the form:

This is what we see when we actually try and add a new row:

Notice that both the column 0,0 and the first visible column of the new row are selected, but the column 0,0 has the focus.  I do not wish for 0,0 to either get selected or have the focus.  I also see here that the row indicator is pointing at row 0 too...

This is how I would like to see things after clicking my Add button:

Does anyone know where I am going wrong with the code? I've searched SO for the most part of the day trying to solve this one.

Body:
Instead of using your DataGridView's RowAdded event to set the CurrentCell, add the following code wherever you're adding a new record to your DGV (in your Add button's Click event I assume):

''# Add the new record to your Data source/DGV.

For Each row As DataGridViewRow In grd_GoldAdders.Rows
    If row.Cells("grid_flag").FormattedValue = Constants.[New] Then
        grd_GoldAdders.CurrentCell = row.Cells("AssySiteColumn")  ''# I'm calling the first column in your DGV 'AssySiteColumn'.
        grd_GoldAdders.BeginEdit(False)
        Exit For
    End If
Next

This code simply loops through all the rows in your DGV and specifies as the CurrentCell the first cell in the first row with your Constants.[New] flag value.


问:
In C++ is really a "reference" just an alias, instead of a "pointer"?
This code:

```<code>int main()
{
    int v[] = {0,10,45};

    for (auto& x : v) {
        cout << x << endl;
        x++;
    }
}
</code>```

Is giving this output:

0
10
45

So, why when "x" is being read is reading the value, but when "x" is modified is modifying the reference target?.

答:
So, why when "x" is being read is reading the value, but when "x" is modified is modifying the reference target?.

Because that is what is specified in your for statement.

```<code>for (auto& x : v)
</code>```

As I noted in comment below your question, the & specifies that x is a reference, and the overall meaning of for (auto &x : v) is that x, in each iteration of the loop, is a reference to a particular element of v (sequentially, from the first to the last).

The compiler takes care of the machinery of changing what x refers to for each iteration (e.g. by newly creating x at the start of every iteration and destroying it after the loop body is done).

So, in the first iteration, x refers to v[0].  So x++ will increment v[0].   It will not change what x refers to, so x still refers to v[0].   It will never refer to v[1] during the first iteration of the loop.

In the second iteration, x refers to v[1] (the compiler takes care of that, as I mentioned above).   So x++ increments v[1], but x will still refer to v[1].

And so on, until the end of v is detected.

If you change the loop to

```<code>for (const auto & x : v)
</code>```

you will find that x++ within the loop body will not compile.   This is because the const tells the compiler that x is a reference to const (i.e. that x cannot be used to change the elements of v).   x will still refer to v[0] in the first iteration, but cannot be directly used to change v[0].

Body:
This code:

int main()
{
    int v[] = {0,10,45};

    for (auto& x : v) {
        cout << x << endl;
        x++;
    }
}

Is giving this output:

0
10
45

So, why when "x" is being read is reading the value, but when "x" is modified is modifying the reference target?.

Body:
So, why when "x" is being read is reading the value, but when "x" is modified is modifying the reference target?.

Because that is what is specified in your for statement.

for (auto& x : v)

As I noted in comment below your question, the & specifies that x is a reference, and the overall meaning of for (auto &x : v) is that x, in each iteration of the loop, is a reference to a particular element of v (sequentially, from the first to the last).

The compiler takes care of the machinery of changing what x refers to for each iteration (e.g. by newly creating x at the start of every iteration and destroying it after the loop body is done).

So, in the first iteration, x refers to v[0].  So x++ will increment v[0].   It will not change what x refers to, so x still refers to v[0].   It will never refer to v[1] during the first iteration of the loop.

In the second iteration, x refers to v[1] (the compiler takes care of that, as I mentioned above).   So x++ increments v[1], but x will still refer to v[1].

And so on, until the end of v is detected.

If you change the loop to

for (const auto & x : v)

you will find that x++ within the loop body will not compile.   This is because the const tells the compiler that x is a reference to const (i.e. that x cannot be used to change the elements of v).   x will still refer to v[0] in the first iteration, but cannot be directly used to change v[0].


问:
SimpleDateFormat and not allowing it to go above 12 hours
So I have this method that I wanted to expand on to have the user input a valid 12 hour time. And I have it to this which works okay. But I want it so that if the hour is over 12 hours or the minutes is over 59 then it will prompt to do it again. But right now it will just convert the time by adding it.
Also is there a more efficient way to write this? (Like without having the
Date newTime = sdf.parse(startTime); And have it so that the user can just input a string and have it check if it's in the correct format?

```<code>public static void userInput(){
    Scanner in = new Scanner(System.in);
    SimpleDateFormat sdf = new SimpleDateFormat("hh:mm aa");
    String startTime;

    System.out.print("What is the start time?: ");
    boolean success = false;
    while (success != true){
        try{
        startTime = in.nextLine();
        Date newTime = sdf.parse(startTime);
        startTime = sdf.format(newTime);

        System.out.println(startTime);

        success = true;
        }
        catch(Exception e){
            System.out.println("Not a valid time. Please use this format (HH:MM AM)");
        }
    }
}
</code>```

答:
You are experiencing SimpleDateFormat behaving as designed. It’s a behaviour that comes as a negative surprise to most.

There are two solutions: the recommended one and the discouraged one.

Recommended solution: LocalTime

```<code>        DateTimeFormatter timeFormat = DateTimeFormatter.ofPattern("hh:mm a", Locale.ROOT);
        try {
            LocalTime lt = LocalTime.parse(startTime, timeFormat);
            startTime = lt.format(timeFormat);
            System.out.println(startTime);
        } catch (DateTimeParseException e) {
            System.out.println("Not a valid time. Please use this format (HH:MM AM)");
        }
</code>```

LocalTime and a bunch of other better designed and more programmer-friendly classes were introduced in Java 8. If you cannot use Java 8, there are again two solutions: (1) Resort to the discouraged solution, see below. (2) Use the backport of the Java 8 date and time classes to Java 6 and 7: ThreeTen Backport (I haven’t got experience with ThreeTen Backport).

In the code, please specify the correct locale instead of Locale.ROOT. I don’t know whether AM and PM may have other names in some locales, so I would want to make sure we are using a locale that agrees with the user input on this point.

Discouraged solution: setLenient()

```<code>    SimpleDateFormat sdf = new SimpleDateFormat("hh:mm aa");
    sdf.setLenient(false);
</code>```

The SimpleDateFormat is lenient as default and accepts 09:63 as 10:03 and 14:00 AM as 02:00 PM. When you setLenient(false), it will no longer accept out-of-range values this way, but will throw a ParseException as you had expected.

Just checking if the format is correct

In either solution, the best way to check the format is what you are already doing: you try to parse it and catch the relevant exception type. Only don’t just catch Exception, be specific since exceptions may come of many other causes. That is, catch DateTimeParseException with the recommended solution and ParseException with the discouraged solution.

Also, if you want to store the time for use later, it is probably more convenient and object-oriented to store it as a LocalTime (or what class best reflects your needs) rather than String.

Body:
So I have this method that I wanted to expand on to have the user input a valid 12 hour time. And I have it to this which works okay. But I want it so that if the hour is over 12 hours or the minutes is over 59 then it will prompt to do it again. But right now it will just convert the time by adding it.
Also is there a more efficient way to write this? (Like without having the
Date newTime = sdf.parse(startTime); And have it so that the user can just input a string and have it check if it's in the correct format?

public static void userInput(){
    Scanner in = new Scanner(System.in);
    SimpleDateFormat sdf = new SimpleDateFormat("hh:mm aa");
    String startTime;

    System.out.print("What is the start time?: ");
    boolean success = false;
    while (success != true){
        try{
        startTime = in.nextLine();
        Date newTime = sdf.parse(startTime);
        startTime = sdf.format(newTime);

        System.out.println(startTime);

        success = true;
        }
        catch(Exception e){
            System.out.println("Not a valid time. Please use this format (HH:MM AM)");
        }
    }
}

Body:
You are experiencing SimpleDateFormat behaving as designed. It’s a behaviour that comes as a negative surprise to most.

There are two solutions: the recommended one and the discouraged one.

Recommended solution: LocalTime

        DateTimeFormatter timeFormat = DateTimeFormatter.ofPattern("hh:mm a", Locale.ROOT);
        try {
            LocalTime lt = LocalTime.parse(startTime, timeFormat);
            startTime = lt.format(timeFormat);
            System.out.println(startTime);
        } catch (DateTimeParseException e) {
            System.out.println("Not a valid time. Please use this format (HH:MM AM)");
        }

LocalTime and a bunch of other better designed and more programmer-friendly classes were introduced in Java 8. If you cannot use Java 8, there are again two solutions: (1) Resort to the discouraged solution, see below. (2) Use the backport of the Java 8 date and time classes to Java 6 and 7: ThreeTen Backport (I haven’t got experience with ThreeTen Backport).

In the code, please specify the correct locale instead of Locale.ROOT. I don’t know whether AM and PM may have other names in some locales, so I would want to make sure we are using a locale that agrees with the user input on this point.

Discouraged solution: setLenient()

    SimpleDateFormat sdf = new SimpleDateFormat("hh:mm aa");
    sdf.setLenient(false);

The SimpleDateFormat is lenient as default and accepts 09:63 as 10:03 and 14:00 AM as 02:00 PM. When you setLenient(false), it will no longer accept out-of-range values this way, but will throw a ParseException as you had expected.

Just checking if the format is correct

In either solution, the best way to check the format is what you are already doing: you try to parse it and catch the relevant exception type. Only don’t just catch Exception, be specific since exceptions may come of many other causes. That is, catch DateTimeParseException with the recommended solution and ParseException with the discouraged solution.

Also, if you want to store the time for use later, it is probably more convenient and object-oriented to store it as a LocalTime (or what class best reflects your needs) rather than String.


问:
Why private/protected members must originate from the same class for type compatibility?
In TypeScript Handbook, it says:

Private and protected members in a class affect their compatibility.
  When an instance of a class is checked for compatibility, if the
  instance contains a private member, then the target type must also
  contain a private member that originated from the same class.
  Likewise, the same applies for an instance with a protected member.
  This allows a class to be assignment compatible with its super class,
  but not with classes from a different inheritance hierarchy which
  otherwise have the same shape.

While type compatibility in TypeScript being structural (duck typing):

```<code>class Animal {
    feet: number;
}

class Size {
    feet: number;
}

let a: Animal = new Size; // Ok!
</code>```

the cases for class containing protected/private members is actually nominal:

```<code>class Animal {
    private feet: number;
}

class Size {
    private feet: number;
}

let a: Animal = new Size; // Error!
</code>```

Could anyone explain why this inconsistency exists in TypeScript between public and protected/private members?

答:
This is by design to prevent private/protected members from being accessed from a different type.

From https://github.com/Microsoft/TypeScript/issues/7755:

Consider something like this

```<code>class Foo {
    private versionNumber = 10;

    public compareTo(other: Foo) {
        return this.getVersion() === other.getVersion();
    }

    private getVersion() {
        return this.versionNumber;
    }
}

class Bar {
    private myName = 'default;'
    public compareTo(other: Bar) {
        return this.myName === other.myName;
    }

    private getVersion() {
        /* ... DANGEROUS CODE HERE ...*/
        return -1;
    }
}
</code>```

By inspection, Bar#getVersion is never invoked -- it's a private
  method and there are no calls to it from the originating class. That
  inspection ought to be sufficient for code that doesn't actively try
  to work around the typechecker.

But this code does invoke Bar#getVersion:

```<code>let f = new Foo();
let b = new Bar();
f.compareTo(b);
</code>```

Body:
In TypeScript Handbook, it says:

Private and protected members in a class affect their compatibility.
  When an instance of a class is checked for compatibility, if the
  instance contains a private member, then the target type must also
  contain a private member that originated from the same class.
  Likewise, the same applies for an instance with a protected member.
  This allows a class to be assignment compatible with its super class,
  but not with classes from a different inheritance hierarchy which
  otherwise have the same shape.

While type compatibility in TypeScript being structural (duck typing):

class Animal {
    feet: number;
}

class Size {
    feet: number;
}

let a: Animal = new Size; // Ok!

the cases for class containing protected/private members is actually nominal:

class Animal {
    private feet: number;
}

class Size {
    private feet: number;
}

let a: Animal = new Size; // Error!

Could anyone explain why this inconsistency exists in TypeScript between public and protected/private members?

Body:
This is by design to prevent private/protected members from being accessed from a different type.

From https://github.com/Microsoft/TypeScript/issues/7755:

Consider something like this

class Foo {
    private versionNumber = 10;

    public compareTo(other: Foo) {
        return this.getVersion() === other.getVersion();
    }

    private getVersion() {
        return this.versionNumber;
    }
}

class Bar {
    private myName = 'default;'
    public compareTo(other: Bar) {
        return this.myName === other.myName;
    }

    private getVersion() {
        /* ... DANGEROUS CODE HERE ...*/
        return -1;
    }
}

By inspection, Bar#getVersion is never invoked -- it's a private
  method and there are no calls to it from the originating class. That
  inspection ought to be sufficient for code that doesn't actively try
  to work around the typechecker.

But this code does invoke Bar#getVersion:

let f = new Foo();
let b = new Bar();
f.compareTo(b);


问:
String Format Get Attribute Function
I try to create an attribute function in a model which returns a string result but I would like to change the format of the string.

Actually I have a number licence (varchar column), which is displayed like 17923457 and I would like to change the format to 17-92-3457.

My function attribute actually is like:

```<code>public function getNumberAttribute() {

return $this->num_licence ;

}
</code>```

Someone knows how I can display that specific format? Thanks a lot in advance

答:
if you are sure you are always going to have 8 digits, you can do

```<code>public function getNumberAttribute() {
    $first = substr($this->num_licence, 0, 2); //from position 0, take 2 digits
    $second = substr($this->num_licence, 2, 2); //from position 2, take 2
    $third = substr($this->num_licence, 4); //from 4 take the rest.
    return $first . '-' . $second . '-' . $third;
}
</code>```

You get it. Use substring to split your varchar/string. https://www.w3schools.com/php/func_string_substr.asp

Title: String Format Get Attribute Function

Body:
I try to create an attribute function in a model which returns a string result but I would like to change the format of the string.

Actually I have a number licence (varchar column), which is displayed like 17923457 and I would like to change the format to 17-92-3457.

My function attribute actually is like:

public function getNumberAttribute() {

return $this->num_licence ;

}

Someone knows how I can display that specific format? Thanks a lot in advance

Body:
if you are sure you are always going to have 8 digits, you can do

public function getNumberAttribute() {
    $first = substr($this->num_licence, 0, 2); //from position 0, take 2 digits
    $second = substr($this->num_licence, 2, 2); //from position 2, take 2
    $third = substr($this->num_licence, 4); //from 4 take the rest.
    return $first . '-' . $second . '-' . $third;
}

You get it. Use substring to split your varchar/string. https://www.w3schools.com/php/func_string_substr.asp


问:
Generate Dagger components using Annotation Processor
I'm working on an Android App which follows the MVP architecture pattern. In all my fragments I'm injecting a Presenter. Therefore my Fragments (Views) need to have a Component in which I declare the injects. For example:

```<code>@ActivityScope
@Component(
        dependencies = AppComponent.class,
        modules = {
                PresenterModule.class,
                InteractorModule.class
        }
)
public interface ViewInjectorComponent {
    void inject(SelectEventOccurrenceFragment fragment);
    void inject(CreateOpponentFragment fragment);
    void inject(SelectOpponentFragment fragment);
    void inject(TeammatesInvitedFragment fragment);
    ...
}
</code>```

Every new View that I add into my App (Fragment) needs to have its entry declared here. I was wondering if It's possible to generate this code automatically with some kind of annotation processor. The App has already several fragments, this component file has easily more than 300 entries. It'd be awesome if I could do something like:

```<code>@Injectable
public class MyNewFragment implements MyNewView {
...
}
</code>```

And then automatically generate the entry in the ViewInjectorComponent file. It's possible? Where should I look at?

答:
I'm not entirely sure that what I'm going to say is appropriate for an answer, but I'll take a chance here.

Even if you find a way to do what you want, don't do this in production (it is fine if you just want to learn code generation techniques).

The benefits you get from such an approach are small (not writing several lines of trivial code), but consider the drawbacks:

The logic for code generation needs to be written/debugged/maintained

Such an approach will be a violation of "principle of least astonishment"

Code generation is BAD

Note the third point - I really mean it. Usage of code generation always leads to maintenance overhead, therefore it should be used only as a last resort.

Dagger by itself uses code generation, but for a good reason - performance. However, performance is not an issue in your case.

To summarize: your idea is very interesting, but approaches like this should not be used for production applications (unless this functionality is added to Dagger natively).

Body:
I'm working on an Android App which follows the MVP architecture pattern. In all my fragments I'm injecting a Presenter. Therefore my Fragments (Views) need to have a Component in which I declare the injects. For example:

@ActivityScope
@Component(
        dependencies = AppComponent.class,
        modules = {
                PresenterModule.class,
                InteractorModule.class
        }
)
public interface ViewInjectorComponent {
    void inject(SelectEventOccurrenceFragment fragment);
    void inject(CreateOpponentFragment fragment);
    void inject(SelectOpponentFragment fragment);
    void inject(TeammatesInvitedFragment fragment);
    ...
}

Every new View that I add into my App (Fragment) needs to have its entry declared here. I was wondering if It's possible to generate this code automatically with some kind of annotation processor. The App has already several fragments, this component file has easily more than 300 entries. It'd be awesome if I could do something like:

@Injectable
public class MyNewFragment implements MyNewView {
...
}

And then automatically generate the entry in the ViewInjectorComponent file. It's possible? Where should I look at?


问:
How to "yield put" in redux-saga within a callback?
Because "yield"-statement isn't allowed within a callback, how can i use the "put" feature of redux-saga within a callback?

I'd like to have the following callback:

```<code>function onDownloadFileProgress(progress) {
  yield put({type: ACTIONS.S_PROGRESS, progress})
}
</code>```

This isn't working and ends up in "unexpected token", because yield is not allowed in a plain function. Otherwise i can't pass a callback as a "function *", that would allow yield. ES6 seems broken here.

I've read that redux-saga provides some features called "channels", but to be honest, i didn't get it. I've read several times about these channels and example code, but in all examples they've solved very difficult and different problems, not my simple case and at the end of the day i've got up there.

Can someone tell me a solution how to deal with this issue?

The whole context:

```<code>function onDownloadFileProgress(progress) {
  yield put({type: ACTIONS.S_PROGRESS, progress})
}

export function * loadFile(id) {
  let url = `media/files/${id}`;

  const tempFilename = RNFS.CachesDirectoryPath + '/' + id;

  const download = RNFS.downloadFile( {
    fromUrl: url,
    toFile: tempFilename,
    background: false,
    progressDivider: 10,
    progress: onDownloadFileProgress,
  })

  yield download.promise;

}
</code>```

答:
One possible solution, as you already mentioned, is to use channels. Here is an example that should work in your case:

```<code>import { channel } from 'redux-saga'
import { put, take } from 'redux-saga/effects'

const downloadFileChannel = channel()

export function* loadFile(id) {
  ...
  const download = RNFS.downloadFile({
     ...
     // push `S_PROGRESS` action into channel on each progress event
     progress: (progress) => downloadFileChannel.put({
       type: ACTIONS.S_PROGRESS,
       progress,
     }),
  })
  ...
}

export function* watchDownloadFileChannel() {
  while (true) {
    const action = yield take(downloadFileChannel)
    yield put(action)
  }
}
</code>```

The idea here is that we will push a S_PROGRESS action on the channel for each progress event that is emitted from RNFS.downloadFile.

We also have to start another saga function that is listening to each pushed action in a while loop (watchDownloadFileChannel). Everytime an action has been taken from the channel, we use the normal yield put to tell redux-saga that this action should be dispatched.

I hope this answer will help you.

Body:
Because "yield"-statement isn't allowed within a callback, how can i use the "put" feature of redux-saga within a callback?

I'd like to have the following callback:

function onDownloadFileProgress(progress) {
  yield put({type: ACTIONS.S_PROGRESS, progress})
}

This isn't working and ends up in "unexpected token", because yield is not allowed in a plain function. Otherwise i can't pass a callback as a "function *", that would allow yield. ES6 seems broken here.

I've read that redux-saga provides some features called "channels", but to be honest, i didn't get it. I've read several times about these channels and example code, but in all examples they've solved very difficult and different problems, not my simple case and at the end of the day i've got up there.

Can someone tell me a solution how to deal with this issue?

The whole context:

function onDownloadFileProgress(progress) {
  yield put({type: ACTIONS.S_PROGRESS, progress})
}

export function * loadFile(id) {
  let url = `media/files/${id}`;

  const tempFilename = RNFS.CachesDirectoryPath + '/' + id;

  const download = RNFS.downloadFile( {
    fromUrl: url,
    toFile: tempFilename,
    background: false,
    progressDivider: 10,
    progress: onDownloadFileProgress,
  })

  yield download.promise;

}

Body:
One possible solution, as you already mentioned, is to use channels. Here is an example that should work in your case:

import { channel } from 'redux-saga'
import { put, take } from 'redux-saga/effects'

const downloadFileChannel = channel()

export function* loadFile(id) {
  ...
  const download = RNFS.downloadFile({
     ...
     // push `S_PROGRESS` action into channel on each progress event
     progress: (progress) => downloadFileChannel.put({
       type: ACTIONS.S_PROGRESS,
       progress,
     }),
  })
  ...
}

export function* watchDownloadFileChannel() {
  while (true) {
    const action = yield take(downloadFileChannel)
    yield put(action)
  }
}

The idea here is that we will push a S_PROGRESS action on the channel for each progress event that is emitted from RNFS.downloadFile.

We also have to start another saga function that is listening to each pushed action in a while loop (watchDownloadFileChannel). Everytime an action has been taken from the channel, we use the normal yield put to tell redux-saga that this action should be dispatched.

I hope this answer will help you.