问:
Add custom text to the output text field in bootstrap datetimepicker
I'm using bootstrap 3 date/time picker here:

https://eonasdan.github.io/bootstrap-datetimepicker/

Is it possible to customise the output text in the date/time text field? I wish to add a string at the start, such as 'Departure:'.

My current set up is very simple, the javascript is simply:

```<code>$('#datetimepicker').datetimepicker({defaultDate:'now',ignoreReadonly: true });
$('#datetimepicker').data("DateTimePicker").format('DD/MM/YYYY HH:mm:ss');
</code>```

The HTML is:

```<code><div class="form-group" style = "margin-bottom:4px;">
    <div class='input-group date' id='datetimepicker'>
        <input type='text' class="form-control" readonly='readonly'/>
        <span class="input-group-addon" style="padding: 6px 11.5px;">
        <span class="glyphicon glyphicon-calendar"></span>
        </span>
    </div>
</div>
</code>```

This will display the date and time as per the formatting given in the code.  How can I add the string Departing: to the beginning of the text field?

答:
You have to use square brackets in your format option, because the component uses moment tokens.

Moment docs has an Escaping characters section which states:

To escape characters in format strings, you can wrap the characters in square brackets.

```<code>moment().format('[today] dddd'); // 'today Sunday'
</code>```

Here is a working sample:

$('#datetimepicker').datetimepicker({
  defaultDate:'now',
  ignoreReadonly: true,
  format: '[Departing:] DD/MM/YYYY HH:mm:ss'
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.css" rel="stylesheet"/>
<link href="//cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/css/bootstrap-datetimepicker.css" rel="stylesheet"/>

<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/js/bootstrap-datetimepicker.min.js"></script>

<div class="form-group" style = "margin-bottom:4px;">
    <div class='input-group date' id='datetimepicker'>
        <input type='text' class="form-control" readonly='readonly'/>
        <span class="input-group-addon" style="padding: 6px 11.5px;">
        <span class="glyphicon glyphicon-calendar"></span>
        </span>
    </div>
</div></code>```

Body:
I'm using bootstrap 3 date/time picker here:

https://eonasdan.github.io/bootstrap-datetimepicker/

Is it possible to customise the output text in the date/time text field? I wish to add a string at the start, such as 'Departure:'.

My current set up is very simple, the javascript is simply:

$('#datetimepicker').datetimepicker({defaultDate:'now',ignoreReadonly: true });
$('#datetimepicker').data("DateTimePicker").format('DD/MM/YYYY HH:mm:ss');

The HTML is:

        <input type='text' class="form-control" readonly='readonly'/>

This will display the date and time as per the formatting given in the code.  How can I add the string Departing: to the beginning of the text field?

Body:
You have to use square brackets in your format option, because the component uses moment tokens.

Moment docs has an Escaping characters section which states:

To escape characters in format strings, you can wrap the characters in square brackets.

moment().format('[today] dddd'); // 'today Sunday'

Here is a working sample:

$('#datetimepicker').datetimepicker({
  defaultDate:'now',
  ignoreReadonly: true,
  format: '[Departing:] DD/MM/YYYY HH:mm:ss'
});

<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.css" rel="stylesheet"/>
<link href="//cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/css/bootstrap-datetimepicker.css" rel="stylesheet"/>

<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/js/bootstrap-datetimepicker.min.js"></script>

<div class="form-group" style = "margin-bottom:4px;">
    <div class='input-group date' id='datetimepicker'>
        <input type='text' class="form-control" readonly='readonly'/>
        <span class="input-group-addon" style="padding: 6px 11.5px;">
        <span class="glyphicon glyphicon-calendar"></span>
        </span>
    </div>
</div>


来源: stackexchange

问:
Background image on div isn't rendering
I've been trying to apply a simple background image to a div. It seems like such a simple problem but after hours of searching through many threads on Stack and other sources, and trying many of the solutions, i'm still looking at an empty div.

I've verified that the asterisk.png file exists and renders when called by itself from an  tag.

Here is the HTML

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

Here is the CSS

```<code>.element{
  background-image: url('images/asterisk.png');
  background-repeat: repeat-x;
  width: 400px;
  height: 50px;
}
</code>```

Im hoping someone can point out the simple error I'm making here ... Thanks!

答:
Fixed it. I was incorrectly linking to the image file. 'images/asterisk.png' vs '../images/asterisk.png'.

My apologies ... I guess I had been staring at the screen for way too long and just needed to rest!

Thanks everyone.

ContentLicense: CC BY-SA 3.0

Title: Background image on div isn't rendering

Body:
I've been trying to apply a simple background image to a div. It seems like such a simple problem but after hours of searching through many threads on Stack and other sources, and trying many of the solutions, i'm still looking at an empty div.

I've verified that the asterisk.png file exists and renders when called by itself from an  tag.

Here is the HTML

Here is the CSS

.element{
  background-image: url('images/asterisk.png');
  background-repeat: repeat-x;
  width: 400px;
  height: 50px;
}

Im hoping someone can point out the simple error I'm making here ... Thanks!


问:
How can I make certain parts of my html not selectable?
How can I make certain parts of my html not selectable?

I have some absolutely positioned divs that keep getting selected if a user tries to select the content of my page.

Is there a way to make it so certain elements (such as those divs) aren't selectable?

EDIT: The main issue is when someone copies these absolute div's and then pastes them into the rich text editor on my site, the rich text editor breaks on IE.

答:
For IE, add the attribute unselectable="ON".  (EDIT: Although it won't completely help)

For Gecko, add the CSS style -moz-user-select: none.

For WebKit, add the CSS style -webkit-user-select: none.

ContentLicense: CC BY-SA 2.5


问:
Error while uploading apk on playstore
getting following error while uploading apk on playstore, please help.

deactivation of this apk will result into your app being available for
  new installs on fewer types of devices.

Thank you.

答:
This message is a warning which says that your new apk will be available for a fewer number of devices.

The reason is, you made changes which probably affected AndroidManifest.xml. You could add new permissions, feature, screen support etc. So this message will be helpful when you added one of them by mistake and you would make apk available for fewer people (who would like to do that by mistake?).

Go through your code changes (comparing to the previous build) to check what exactly makes this limitation happened.

In most of the cases it's totally fine, because it's just natural that during the development process, you request more regarding system or device and as a result, it will run on a smaller number of devices.

You can ignore this warning and go ahead with publishing if you're aware what you're doing.

Title: Error while uploading apk on playstore


问:
How do I create multiple strings from one string?
I want to filter out all the sections of numbers of a string and add them all to a list of strings.

So from: ["2931741444","2931789497","2931745064","2931763896","2931728251","2931786984","2931799607","293177823","2931795568","293171105"]

to

```<code>list.Add(2931741444);
list.Add(2931789497);
list.Add(2931745064);
</code>```

etc...

I loop through the string, look at where the numbers began and add them to a new string, but I'm stuck now. Here's my attempt:

static void Main(string[] args)
        {

```<code>        using (WebClient wc = new WebClient())
        {
            var json = wc.DownloadString("http://api.hivemc.com/v1/game/SG/data");
            Console.WriteLine(json);
            Console.WriteLine("Was called first.");

            int counter = 2;
            string newString = "";
            string s = json.ToString();
            // loop through the string
            for (int i=0; i < s.Length; i++)
            {

                if (s[i].ToString() == "\"")
                {
                    counter++;
                }

                if (counter.isEven)
                {
                    newString = newString + i;
                }
            }
        }

        Console.ReadKey();
    }
</code>```

Is there an easier way to do this? I also can't see how I would do the other strings with this code.

答:
```<code>var stringValues = JsonConvert.DeserializeObject<string[]>(json);
int[] values = Array.ConvertAll(stringValues, s => int.Parse(s));
</code>```

?

(feel free to swap for any other json serializer library there; the example is with Json.NET)

Body:
I want to filter out all the sections of numbers of a string and add them all to a list of strings.

So from: ["2931741444","2931789497","2931745064","2931763896","2931728251","2931786984","2931799607","293177823","2931795568","293171105"]

to

list.Add(2931741444);
list.Add(2931789497);
list.Add(2931745064);

etc...

I loop through the string, look at where the numbers began and add them to a new string, but I'm stuck now. Here's my attempt:

static void Main(string[] args)
        {

        using (WebClient wc = new WebClient())
        {
            var json = wc.DownloadString("http://api.hivemc.com/v1/game/SG/data");
            Console.WriteLine(json);
            Console.WriteLine("Was called first.");

            int counter = 2;
            string newString = "";
            string s = json.ToString();
            // loop through the string
            for (int i=0; i < s.Length; i++)
            {

                if (s[i].ToString() == "\"")
                {
                    counter++;
                }

                if (counter.isEven)
                {
                    newString = newString + i;
                }
            }
        }

        Console.ReadKey();
    }

Is there an easier way to do this? I also can't see how I would do the other strings with this code.

Body:
var stringValues = JsonConvert.DeserializeObject<string[]>(json);
int[] values = Array.ConvertAll(stringValues, s => int.Parse(s));

?

(feel free to swap for any other json serializer library there; the example is with Json.NET)


问:
postgres (pgAdmin) database connection issue
I'm a new sql user (3 days) and I'm having some problems querying data from database tables I've created, whereas there is no problems querying the default 'postgres' database tables. My first thought was that it was a access/privilege problem, but had no effect. I did also notice that my database activity in the dashboard is always idle, whereas the default postgres database is always active. So it looks like my database is available but not connected. Can I choose which database to connect to? Ive been checking the docs, but can't find how to make my database active. Any help appreciated. Thanks</p>

答:
When you connect to PgAdmin to a Postgres instance you get to choose which database you want your queries to work against. You can see an example here.

If you cannot see your database once you connect to the instance you might either:
1) not have the db created in that instance.
2) not have permissions to view/access it. For this one you may need to ask to the administrator of the db for the relevant permission grants.


问:
How to enable a button when all textfield is filled
Initially button.isHidden = true, however, I would like to set the button.isHidden = false, when all textfields are filled. Where should I put the If-Else condition in, most probably not in viewDidLoad, please advise.

答:
You might want to take a look at this post UITextField text change event
and then in textFieldDidChange function you should check texts of each textfield</p>


问:
Dynamic flat file connection string in SSIS
I'm using a flat file connection source in my SSIS Package. The filename has the following naming convention viz.,<<filename><year><month><date><time>>. Example - sample201703291515.txt. The filename would have different time appended to it as the file creation time would differ. I have created expressions in the connection string to fetch the name for the current date.

```<code>"c:\source\sample"+(DT_STR,4,1252)YEAR( DATEADD( "dd", -1, getdate() ))+DT_STR,4,1252)MONTH( DATEADD( "dd", -1, getdate() ))+(DT_STR,4,1252)DAY( DATEADD( "dd", -1, getdate() ))+".txt"
</code>```

But since the time changes, is there any possibility to get the filename dynamically or is there any expression I can add up? Please help.

答:
The normal way to handle this is to use a foreach loop that goes through all the files in the folder.   Then use a script task to look at the file name and compare it to some known pattern.   So if you know you want "sample20170329xxxx.txt" where the xxxx is some unknown time string, you can either use a Regex in the script task, or you can just compare a substring of the file name and only look at the characters before the time portion of the name, to see if it's the file you want.

Then, if it is the file you want, you set your connection string to use that filename, otherwise, loop to the next file.

Body:
I'm using a flat file connection source in my SSIS Package. The filename has the following naming convention viz.,<<filename><year><month><date><time>>. Example - sample201703291515.txt. The filename would have different time appended to it as the file creation time would differ. I have created expressions in the connection string to fetch the name for the current date.

"c:\source\sample"+(DT_STR,4,1252)YEAR( DATEADD( "dd", -1, getdate() ))+DT_STR,4,1252)MONTH( DATEADD( "dd", -1, getdate() ))+(DT_STR,4,1252)DAY( DATEADD( "dd", -1, getdate() ))+".txt"

But since the time changes, is there any possibility to get the filename dynamically or is there any expression I can add up? Please help.


问:
How to retry on error only inner observable?
I have the following sample:

```<code>const result = http.get('http://google.com')

               .switchMap(() => 'http://example.com')

               // This retry should retry only example.com
               .retryWhen(error =>
                    (error instanceof Response && error.status == 429) ?
                     Observable.timeout(5000) : Observable.throw(error))

               // This retry should retry google.com
               .retryWhen(error => Observable.timeout(5000))
</code>```

I want to have a retryWhen which will retry only his immediate parent. And then in case of a global error I will retry the whole sequence. Is there an easy way with RxJS 5 ?

UPD: These are just examples. In reality situation is more complex I just need an idea for this.

答:
You just need put the retryWhen inside the switchMap:

```<code>const inner = http.get('http://example.com')
      // This retry should retry only example.com
      .retryWhen(error =>
       (error instanceof Response && error.status == 429) ?
        Observable.timer(5000) : Observable.throw(error))

const outer = http.get('http://google.com')
  .switchMap(() => inner)
  // This retry should retry google.com
  .retryWhen(error => Observable.timeout(5000))
</code>```

Body:
I have the following sample:

const result = http.get('http://google.com')

               .switchMap(() => 'http://example.com')

               // This retry should retry only example.com
               .retryWhen(error =>
                    (error instanceof Response && error.status == 429) ?
                     Observable.timeout(5000) : Observable.throw(error))

               // This retry should retry google.com
               .retryWhen(error => Observable.timeout(5000))

I want to have a retryWhen which will retry only his immediate parent. And then in case of a global error I will retry the whole sequence. Is there an easy way with RxJS 5 ?

UPD: These are just examples. In reality situation is more complex I just need an idea for this.

Body:
You just need put the retryWhen inside the switchMap:

const inner = http.get('http://example.com')
      // This retry should retry only example.com
      .retryWhen(error =>
       (error instanceof Response && error.status == 429) ?
        Observable.timer(5000) : Observable.throw(error))

const outer = http.get('http://google.com')
  .switchMap(() => inner)
  // This retry should retry google.com
  .retryWhen(error => Observable.timeout(5000))


问:
I wrote a script which makes a new dataframe based on a condition, how can I make it more efficient ?
Here's my code

```<code>df = *some df
coin = *some string
color = 'red'

events = pd.DataFrame()
events['date'] = df.date
events['event'] = np.NaN

data_list = []
for i in range(len(df)):
    if df.iloc[i].color == color:
        data_list.append(1)
    else:
        data_list.append(np.NaN)

events['event'] = l
</code>```

from the original data frame if the color == 'red' the corresponding date in the new dataframe (events) should be 1 otherwise NaN.

I know you can probably do it in one line but I'm not sure how

bonus question after performing this I reset the index to the date column, something I cant do before because iloc doesn't work with range i-> len(df)

```<code>events = pd.DataFrame()
events[coin] = data_list
events = events.set_index(events['date'].values)

data = pd.DataFrame()
data[coin] = df.close
data = data.set_index(events['date'].values)
data = {'close':data}
</code>```

答:
Lots of different ways to do this

e.g. build a series using list comprehension

```<code>import pandas as pd
import numpy as np
df = pd.DataFrame({'color' : ['red', 'blue', 'red'],
                   'date'  : ['3/10/17', '4/10/17', '5/10/17']})

color_bools = pd.Series([1 if val == 'red' else np.nan for val in df['color']],
                         index = df['date'].values)
color_bools

Out[18]:
3/10/17    1.0
4/10/17    NaN
5/10/17    1.0
dtype: float64
</code>```

Body:
Here's my code

df = *some df
coin = *some string
color = 'red'

events = pd.DataFrame()
events['date'] = df.date
events['event'] = np.NaN

data_list = []
for i in range(len(df)):
    if df.iloc[i].color == color:
        data_list.append(1)
    else:
        data_list.append(np.NaN)

events['event'] = l

from the original data frame if the color == 'red' the corresponding date in the new dataframe (events) should be 1 otherwise NaN.

I know you can probably do it in one line but I'm not sure how

bonus question after performing this I reset the index to the date column, something I cant do before because iloc doesn't work with range i-> len(df)

events = pd.DataFrame()
events[coin] = data_list
events = events.set_index(events['date'].values)

data = pd.DataFrame()
data[coin] = df.close
data = data.set_index(events['date'].values)
data = {'close':data}

Body:
Lots of different ways to do this

e.g. build a series using list comprehension

import pandas as pd
import numpy as np
df = pd.DataFrame({'color' : ['red', 'blue', 'red'],
                   'date'  : ['3/10/17', '4/10/17', '5/10/17']})

color_bools = pd.Series([1 if val == 'red' else np.nan for val in df['color']],
                         index = df['date'].values)
color_bools

Out[18]:
3/10/17    1.0
4/10/17    NaN
5/10/17    1.0
dtype: float64


问:
jQuery file not found when navigating away from home page
I'm using a function refresh a div with the content from a PHP script which is working fine.

Code below

```<code>var auto_refresh = setInterval(
function()
{
  jQuery('#livenow').load('connect/status.php');
  jQuery('#upnext').load('connect/upnext.php');
}, 5000);
</code>```

But when I navigate away from the home page to another page I'm getting a debugger error of 404 not found as it's trying to search for this script from the current url.

GET http://xxxxxx.co.uk/timetable/connect/status.php 404 (Not Found)

But on the homepage all is well - http://xxxxxx.co.uk/connect/status.php, which is the the absolute file path

The files are in a folder in the root directory - connect/upnext.php

Is there a way I can use the ('connect/status.php'); universally rather than it searching from the current url path?

Thanks for your help

答:
You should refer to it by its absolute path rather than its relative path.  Absolute path starts with a forward slash "/".

Fore example:

```<code>var auto_refresh = setInterval(
function()
{
  jQuery('#livenow').load('/connect/status.php');
  jQuery('#upnext').load('/connect/upnext.php');
}, 5000);
</code>```

Body:
I'm using a function refresh a div with the content from a PHP script which is working fine.

Code below

var auto_refresh = setInterval(
function()
{
  jQuery('#livenow').load('connect/status.php');
  jQuery('#upnext').load('connect/upnext.php');
}, 5000);

But when I navigate away from the home page to another page I'm getting a debugger error of 404 not found as it's trying to search for this script from the current url.

GET http://xxxxxx.co.uk/timetable/connect/status.php 404 (Not Found)

But on the homepage all is well - http://xxxxxx.co.uk/connect/status.php, which is the the absolute file path

The files are in a folder in the root directory - connect/upnext.php

Is there a way I can use the ('connect/status.php'); universally rather than it searching from the current url path?

Thanks for your help

Body:
You should refer to it by its absolute path rather than its relative path.  Absolute path starts with a forward slash "/".

Fore example:

var auto_refresh = setInterval(
function()
{
  jQuery('#livenow').load('/connect/status.php');
  jQuery('#upnext').load('/connect/upnext.php');
}, 5000);


问:
Errors creating a string in c++
Whenever I try to create a string in my header file I get the error: 'string' is not a member of 'std'. I am using the Microsoft Visual c++ express 2010 compiler. Here is my header file:

```<code>using namespace std;

class Person
{
private:
 string name;
 string p_number;

public:
 Person();
 Person(string, string);
 string get_number();
 string get_name();
};
</code>```

I am a decent java programmer who just started  learning c++

答: Do you also have #include <string> in your header?  You need it for the declarations of the string classes.

Title: Errors creating a string in c++

Body:
Whenever I try to create a string in my header file I get the error: 'string' is not a member of 'std'. I am using the Microsoft Visual c++ express 2010 compiler. Here is my header file:

using namespace std;

class Person
{
private:
 string name;
 string p_number;

public:
 Person();
 Person(string, string);
 string get_number();
 string get_name();
};

I am a decent java programmer who just started  learning c++


问:
I am looking for a way to call multiple shell scripts in a serialized manner from a base shell script
I am looking for a way to call multiple shell scripts in a serialized manner from a base shell script. Scenario:

A shell script- Base_script.sh , which will internally call:

script_1.sh ,

script_2.sh ,
script_3.sh ,

Once "script_1.sh" will finish, THEN ONLY it should call "script_2.sh" and so on.

What all methods i have tried, are somehow executing all the scripts at once.
OS: RHEL using Shell/Bash

Edit: In response to some comments, I agree, i can use (which i already did):

script1.sh && script2.sh

calling each script one by one (sh script1.sh; sh script2.sh ..so on)

even tried using an array to declare the scripts and then execute each in a loop

Problem & the Solution i got:

Each script eg-"script_1.sh" was a complex one. Its all doing some kind of database benchmarking.
The scripts were having some function that was going in background (someFunction &) while execution. So even though the scripts were actually getting called one by one, yet the processing of the previous scripts kept on going in the background.

Had to redesign the entire thing to get every module & functions in the "Base_script.sh" itself.

Thanks everyone for the answers though. Appreciate it !!

答:
In the general case, there's nothing needed here at all.

```<code>./script1
./script2
./script3
</code>```

...will automatically wait for script1 to exit before running script2.

On the other hand, what you may have here is a case where your script1 intentionally backgrounds itself (an action also known as "self-daemonization"). One way to wait for a daemonized process to exit is to use filesystem-level advisory locking; the below uses the flock command for that purpose:

```<code>flock -x my.lck ./script1
flock -x my.lck ./script2
flock -x my.lck ./script3
flock -x my.lck true
</code>```

Even if script1 itself exits, if it has child processes still running that hold the file descriptor on my.lck, then script2 will be blocked from starting.

Body:
In the general case, there's nothing needed here at all.

./script1
./script2
./script3

...will automatically wait for script1 to exit before running script2.

On the other hand, what you may have here is a case where your script1 intentionally backgrounds itself (an action also known as "self-daemonization"). One way to wait for a daemonized process to exit is to use filesystem-level advisory locking; the below uses the flock command for that purpose:

flock -x my.lck ./script1
flock -x my.lck ./script2
flock -x my.lck ./script3
flock -x my.lck true

Even if script1 itself exits, if it has child processes still running that hold the file descriptor on my.lck, then script2 will be blocked from starting.


问:
Continuous integration software with support for Git and gated check-in?
I've been looking at TFS, TeamCity, Jenkins and Bamboo and to be honest, none of them were convincing. I want

Good reporting

Good Git support

Gated/delayed check-in/commit

Integration with Visual Studio and/or Atlassian products

The solution shouldn't require regular developers to use command line or terminal (Git Extensions FTW)

TFS is a mess to configure and work with in general, it doesn't support Git obviously, but it has gated check-ins (although it seems to unnecessarily check out the whole project every time and so it is slow?). Also really lacking in the reporting department.

TeamCity has really bad gated check-in support when it comes to Git, otherwise it's my favorite. Supports a lot of stuff out of the box.

The reporting in Jenkins is bad (historical trends and so on), it seems to have more bugs than the others, and the plugin quality can be scary. On the other hand it's free and versatile. How is the support for Git and gated check-ins?

Bamboo obviously has great Atlassian integration, but no support for gated check-ins. :(

Any advice?

答:
Verigreen is a server side solution for verification of git commits which is somehow similar to Gated Check in of TFS.
 It will push only those commits to protected branch, which are built successfully.

Travis is a CI service used to build and test your app.


问:
Reading REST Request Output using HttpURLConnection
I am trying to do REST request on the StackExchange API on java and I have some problems to read the output. I made a small code example to see if I can read properly:

```<code>package Utils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class RestClient
{

public static void main(String[] args)
{
    try
    {
        URL url = new URL("https://api.stackexchange.com/2.2/questions?order=desc&sort=activity&site=stackoverflow");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        System.out.println(conn.getResponseCode());

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

        String output;

        while ((output = reader.readLine()) != null)
        {
            System.out.println(output);
        }

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

}
</code>```

Below is a sample output from the website:

```<code>{"items":[{"tags":["c++","templates","covariant"],"owner":{"reputation":3,"user_id":7447292,"user_type":"registered","profile_image":"https://www.gravatar.com/avatar/8979f1b328b9b0f786dec8b4edd514bc?s=128&d=identicon&r=PG&f=1","display_name":"B.Oudot","link":"http://stackoverflow.com/users/7447292/b-oudot"}
</code>```

However when I print the output of my java program, I get the status code 200 and then the rest is just bunch of non-ascii characters. I am new with REST and JSON. I would like to not use any 3rd party library if possible.

EDIT
I have put the output of my program as an image.

答:
you need to use GZIPInputStream api, when the content encoding used gZip. it is also an inputstream.

i used gipinput stream to your response and i see output in json.

```<code>public static void main(String[] args){
    try
    {
        URL url = new URL("https://api.stackexchange.com/2.2/questions?order=desc&sort=activity&site=stackoverflow");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        System.out.println(conn.getResponseCode());

        GZIPInputStream gzis = new GZIPInputStream(conn.getInputStream());
        InputStreamReader reader = new InputStreamReader(gzis);
        BufferedReader in = new BufferedReader(reader);

        String readed;
        while ((readed = in.readLine()) != null) {
            System.out.println(readed);
        }
        //BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

        String output;

        while ((output = in.readLine()) != null)
        {
            System.out.println(output);
        }

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

    }
</code>```

it worked for me.

Body:
I am trying to do REST request on the StackExchange API on java and I have some problems to read the output. I made a small code example to see if I can read properly:

package Utils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class RestClient
{

public static void main(String[] args)
{
    try
    {
        URL url = new URL("https://api.stackexchange.com/2.2/questions?order=desc&sort=activity&site=stackoverflow");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        System.out.println(conn.getResponseCode());

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

        String output;

        while ((output = reader.readLine()) != null)
        {
            System.out.println(output);
        }

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

}

Below is a sample output from the website:

{"items":[{"tags":["c++","templates","covariant"],"owner":{"reputation":3,"user_id":7447292,"user_type":"registered","profile_image":"https://www.gravatar.com/avatar/8979f1b328b9b0f786dec8b4edd514bc?s=128&d=identicon&r=PG&f=1","display_name":"B.Oudot","link":"http://stackoverflow.com/users/7447292/b-oudot"}

However when I print the output of my java program, I get the status code 200 and then the rest is just bunch of non-ascii characters. I am new with REST and JSON. I would like to not use any 3rd party library if possible.

EDIT
I have put the output of my program as an image.

Body:
you need to use GZIPInputStream api, when the content encoding used gZip. it is also an inputstream.

i used gipinput stream to your response and i see output in json.

public static void main(String[] args){
    try
    {
        URL url = new URL("https://api.stackexchange.com/2.2/questions?order=desc&sort=activity&site=stackoverflow");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        System.out.println(conn.getResponseCode());

        GZIPInputStream gzis = new GZIPInputStream(conn.getInputStream());
        InputStreamReader reader = new InputStreamReader(gzis);
        BufferedReader in = new BufferedReader(reader);

        String readed;
        while ((readed = in.readLine()) != null) {
            System.out.println(readed);
        }
        //BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

        String output;

        while ((output = in.readLine()) != null)
        {
            System.out.println(output);
        }

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

    }

it worked for me.


问:
How can I render a Matplotlib Axes object to an image (as a Numpy array)?
Is there a way to render the contents of a particular Axes object to an image, as a Numpy array? I know you can do this with the entire figure, but I want to get the image of a particular Axes.

The Axes I'm trying to render contains an image (drawn with imshow), with some lines plotted on top. Ideally, the rendered ndarray would contain just these elements, and no tick marks, borders, etc.

Update:

I forgot to mention that I'm looking for a solution that doesn't require saving an image file.

I've written the following example that almost achieves this, except it doesn't preserve image resolution. Any hints as to what I may be doing wrong would be greatly appreciated:

```<code>
import matplotlib.pylab as plt
import numpy as np

def main():
  """Test for extracting pixel data from an Axes.

  This creates an image I, imshow()'s it to one Axes, then copies the pixel
  data out of that Axes to a numpy array I_copy, and imshow()'s the I_copy to
  another Axes.

  Problem: The two Axes *look* identical, but I does not equal I_copy.
  """

  fig, axes_pair = plt.subplots(1, 2)

  reds, greens = np.meshgrid(np.arange(0, 255), np.arange(0, 122))
  blues = np.zeros_like(reds)
  image = np.concatenate([x[..., np.newaxis] for x in (reds, greens, blues)],
                         axis=2)
  image = np.asarray(image, dtype=np.uint8)

  axes_pair[0].imshow(image)
  fig.canvas.draw()

  trans = axes_pair[0].figure.dpi_scale_trans.inverted()
  bbox = axes_pair[0].bbox.transformed(trans)
  bbox_contents = fig.canvas.copy_from_bbox(axes_pair[0].bbox)
  left, bottom, right, top = bbox_contents.get_extents()

  image_copy = np.fromstring(bbox_contents.to_string(),
                             dtype=np.uint8,
                             sep="")

  image_copy = image_copy.reshape([top - bottom, right - left, 4])
  image_copy = image_copy[..., :3]  # chop off alpha channel

  axes_pair[1].imshow(image_copy)

  print("Are the images perfectly equal? {}".format(np.all(image == image_copy)))

  plt.show()

if __name__ == '__main__':
  main()

</code>```

答:
One idea can be to intermediately turn the axes off, find out the bounding box of the axes in inches and then save the figure using the bbox_inches argument to plt.savefig().

If a numpy array is wanted, one can then read in the saved image again using plt.imread.

In this solution the returned array has dimensions exactly as the axes has pixels when plotted on the screen.

```<code>import matplotlib.pyplot as plt
import numpy as np; np.random.seed(0)

im = np.random.rand(16,16)

x = np.arange(9)
y = np.random.randint(1,14, size=(9,))
y2 = np.random.randint(1,7, size=(9,))

fig, (ax1, ax2) = plt.subplots(1,2)

ax1.imshow(im[:16,:9], cmap="viridis")
ax2.imshow(im[7:16,7:], cmap="YlGnBu")
ax1.plot(x, y, color="C3")
ax1.scatter(x, y, color="w")
ax2.plot(x, y2, color="C1")
ax2.scatter(x, y2, color="k")
ax1.set_xlabel("YlFasOcto")

def save_ax(ax, filename, **kwargs):
    ax.axis("off")
    ax.figure.canvas.draw()
    trans = ax.figure.dpi_scale_trans.inverted()
    bbox = ax.bbox.transformed(trans)
    plt.savefig(filename, dpi="figure", bbox_inches=bbox,  **kwargs)
    ax.axis("on")
    im = plt.imread(filename)
    return im

arr = save_ax(ax1, __file__+".png")
print(arr.shape)
plt.show()
</code>```

In order to prevent saving a file to disk, one could use a Stream to save the data.

```<code>import io

def save_ax_nosave(ax, **kwargs):
    ax.axis("off")
    ax.figure.canvas.draw()
    trans = ax.figure.dpi_scale_trans.inverted()
    bbox = ax.bbox.transformed(trans)
    buff = io.BytesIO()
    plt.savefig(buff, format="png", dpi=ax.figure.dpi, bbox_inches=bbox,  **kwargs)
    ax.axis("on")
    buff.seek(0)
    im = plt.imread(buff )
    return im
</code>```

Body:
Is there a way to render the contents of a particular Axes object to an image, as a Numpy array? I know you can do this with the entire figure, but I want to get the image of a particular Axes.

The Axes I'm trying to render contains an image (drawn with imshow), with some lines plotted on top. Ideally, the rendered ndarray would contain just these elements, and no tick marks, borders, etc.

Update:

I forgot to mention that I'm looking for a solution that doesn't require saving an image file.

I've written the following example that almost achieves this, except it doesn't preserve image resolution. Any hints as to what I may be doing wrong would be greatly appreciated:

import matplotlib.pylab as plt
import numpy as np

def main():
  """Test for extracting pixel data from an Axes.

  This creates an image I, imshow()'s it to one Axes, then copies the pixel
  data out of that Axes to a numpy array I_copy, and imshow()'s the I_copy to
  another Axes.

  Problem: The two Axes *look* identical, but I does not equal I_copy.
  """

  fig, axes_pair = plt.subplots(1, 2)

  reds, greens = np.meshgrid(np.arange(0, 255), np.arange(0, 122))
  blues = np.zeros_like(reds)
  image = np.concatenate([x[..., np.newaxis] for x in (reds, greens, blues)],
                         axis=2)
  image = np.asarray(image, dtype=np.uint8)

  axes_pair[0].imshow(image)
  fig.canvas.draw()

  trans = axes_pair[0].figure.dpi_scale_trans.inverted()
  bbox = axes_pair[0].bbox.transformed(trans)
  bbox_contents = fig.canvas.copy_from_bbox(axes_pair[0].bbox)
  left, bottom, right, top = bbox_contents.get_extents()

  image_copy = np.fromstring(bbox_contents.to_string(),
                             dtype=np.uint8,
                             sep="")

  image_copy = image_copy.reshape([top - bottom, right - left, 4])
  image_copy = image_copy[..., :3]  # chop off alpha channel

  axes_pair[1].imshow(image_copy)

  print("Are the images perfectly equal? {}".format(np.all(image == image_copy)))

  plt.show()

if __name__ == '__main__':
  main()

Body:
One idea can be to intermediately turn the axes off, find out the bounding box of the axes in inches and then save the figure using the bbox_inches argument to plt.savefig().

If a numpy array is wanted, one can then read in the saved image again using plt.imread.

In this solution the returned array has dimensions exactly as the axes has pixels when plotted on the screen.

import matplotlib.pyplot as plt
import numpy as np; np.random.seed(0)

im = np.random.rand(16,16)

x = np.arange(9)
y = np.random.randint(1,14, size=(9,))
y2 = np.random.randint(1,7, size=(9,))

fig, (ax1, ax2) = plt.subplots(1,2)

ax1.imshow(im[:16,:9], cmap="viridis")
ax2.imshow(im[7:16,7:], cmap="YlGnBu")
ax1.plot(x, y, color="C3")
ax1.scatter(x, y, color="w")
ax2.plot(x, y2, color="C1")
ax2.scatter(x, y2, color="k")
ax1.set_xlabel("YlFasOcto")

def save_ax(ax, filename, **kwargs):
    ax.axis("off")
    ax.figure.canvas.draw()
    trans = ax.figure.dpi_scale_trans.inverted()
    bbox = ax.bbox.transformed(trans)
    plt.savefig(filename, dpi="figure", bbox_inches=bbox,  **kwargs)
    ax.axis("on")
    im = plt.imread(filename)
    return im

arr = save_ax(ax1, __file__+".png")
print(arr.shape)
plt.show()

In order to prevent saving a file to disk, one could use a Stream to save the data.

import io

def save_ax_nosave(ax, **kwargs):
    ax.axis("off")
    ax.figure.canvas.draw()
    trans = ax.figure.dpi_scale_trans.inverted()
    bbox = ax.bbox.transformed(trans)
    buff = io.BytesIO()
    plt.savefig(buff, format="png", dpi=ax.figure.dpi, bbox_inches=bbox,  **kwargs)
    ax.axis("on")
    buff.seek(0)
    im = plt.imread(buff )
    return im


问:
Connect to MySQL Data Source in PHPStorm
I'm using an IDE "Phpstorm" with "wampserver". i want to connect with MySQL data source, but i'm getting a problem:

```<code>Connection to MySQL - DatabaseName@localhost failed: Exception in thread "main" java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:190)
at com.intellij.persistence.database.console.RemoteJdbcServer.main(RemoteJdbcServer.java:15)
</code>```

I also downloaded mysql-connector-java-gpl-5.1.29.msi and installed it, but I'm still getting some problems.

答:
Anyone else who came here trying to locate the Database tab in the latest version of PhpStorm (Version 2017.1), which is hidden at first, try the following, taken from PhpStorm Website

Database support is provided through the Database Tool Window on the right-hand side of the IDE. Use the View | Tool Windows | Database menu or Find Action, by pressing Ctrl+Alt+A (Alt-CMD-A on Mac OS X) and search for "Database" to open it.

Body:
I'm using an IDE "Phpstorm" with "wampserver". i want to connect with MySQL data source, but i'm getting a problem:

Connection to MySQL - DatabaseName@localhost failed: Exception in thread "main" java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:190)
at com.intellij.persistence.database.console.RemoteJdbcServer.main(RemoteJdbcServer.java:15)

I also downloaded mysql-connector-java-gpl-5.1.29.msi and installed it, but I'm still getting some problems.


问:
Text to Time with Milliseconds
In column A1 I have 16304238, which represents Hour, Minutes, Seconds and Milliseconds, which I want to display in B1 as 4:30:42:380 PM.

I know how to format with hour and minutes, but can't get the seconds and millisecond correct. I tried

```<code>=TIME(LEFT(E2,2),MID(E2,3,2),RIGHT(E2,2))
</code>```

Which comes out as 16:30:38.000. Also, I'm using

```<code>[h]:mm:ss.000
</code>```

to format the result. What do I need to use, instead of [h], to get AM/PM instead or military time?

答:
Change your formula to:

```<code>=--CONCATENATE(LEFT(E2,2),":",MID(E2,3,2),":",MID(E2,5,2),".",RIGHT(E2,2))
</code>```

Then format the cell to:

```<code>h:mm:ss.000 AM/PM
</code>```

Title: Text to Time with Milliseconds

Body:
In column A1 I have 16304238, which represents Hour, Minutes, Seconds and Milliseconds, which I want to display in B1 as 4:30:42:380 PM.

I know how to format with hour and minutes, but can't get the seconds and millisecond correct. I tried

=TIME(LEFT(E2,2),MID(E2,3,2),RIGHT(E2,2))

Which comes out as 16:30:38.000. Also, I'm using

[h]:mm:ss.000

to format the result. What do I need to use, instead of [h], to get AM/PM instead or military time?

Body:
Change your formula to:

=--CONCATENATE(LEFT(E2,2),":",MID(E2,3,2),":",MID(E2,5,2),".",RIGHT(E2,2))

Then format the cell to:

h:mm:ss.000 AM/PM


问:
Deploying Rails App to AWS using capistrano, puma and nginx. Always show Welcome to nginx
Good day! I like to ask if someone encounter this issue, after the deployment of Rails app using Capistrano, Puma and NGINX. Welcome to nginx! page appear instead of Rails page root path? I tried to solve the issue but no luck. Hoping someone can help me. Thank you

Here's my nginx config

```<code>upstream app {
  # Path to Puma SOCK file, as defined previously
  server unix:/home/deploy/appname/shared/tmp/sockets/puma.sock fail_timeout=0;
}
server {
  listen 80;
  server_name localhost;
  root /home/deploy/appname/current/public;
  try_files $uri/index.html $uri @app;
  location / {
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header Host $host;
    proxy_redirect off;
    proxy_http_version 1.1;
    proxy_set_header Connection '';
    proxy_pass http://app;
  }
  location ~ ^/(assets|fonts|system)/|favicon.ico|robots.txt {
    gzip_static on;
    expires max;
    add_header Cache-Control public;
  }
  error_page 500 502 503 504 /500.html;
  client_max_body_size 4G;
  keepalive_timeout 10;
}

and cap deploy.rb

# config valid only for current version of Capistrano
lock "3.8.0"
set :application, 'appname'
set :branch, :aws_deployment_v1
set :repo_url, git repo link
set :deploy_to, '/home/deploy/appname'
set :pty, true
set :linked_files, %w{config/database.yml config/application.yml}
set :linked_dirs, %w{bin log tmp/pids tmp/cache tmp/sockets vendor/bundle public/system public/uploads}
set :keep_releases, 5
set :rvm_type, :user
set :rvm_ruby_version, 'ruby-2.1.6' # Edit this if you are using MRI Ruby
set :puma_rackup, -> { File.join(current_path, 'config.ru') }
set :puma_state, "#{shared_path}/tmp/pids/puma.state"
set :puma_pid, "#{shared_path}/tmp/pids/puma.pid"
set :puma_bind, "unix://#{shared_path}/tmp/sockets/puma.sock"    #accept array for multi-bind
set :puma_conf, "#{shared_path}/puma.rb"
set :puma_access_log, "#{shared_path}/log/puma_error.log"
set :puma_error_log, "#{shared_path}/log/puma_access.log"
set :puma_role, :app
set :puma_env, fetch(:rack_env, fetch(:rails_env, 'production'))
set :puma_threads, [0, 8]
set :puma_workers, 0
set :puma_worker_timeout, nil
set :puma_init_active_record, true
set :puma_preload_app, false
</code>```

答:
Have you tried switching the index.html and the @app around?

```<code>try_files $uri @app $uri/index.html;
</code>```

Body:
Good day! I like to ask if someone encounter this issue, after the deployment of Rails app using Capistrano, Puma and NGINX. Welcome to nginx! page appear instead of Rails page root path? I tried to solve the issue but no luck. Hoping someone can help me. Thank you

Here's my nginx config

upstream app {
  # Path to Puma SOCK file, as defined previously
  server unix:/home/deploy/appname/shared/tmp/sockets/puma.sock fail_timeout=0;
}
server {
  listen 80;
  server_name localhost;
  root /home/deploy/appname/current/public;
  try_files $uri/index.html $uri @app;
  location / {
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header Host $host;
    proxy_redirect off;
    proxy_http_version 1.1;
    proxy_set_header Connection '';
    proxy_pass http://app;
  }
  location ~ ^/(assets|fonts|system)/|favicon.ico|robots.txt {
    gzip_static on;
    expires max;
    add_header Cache-Control public;
  }
  error_page 500 502 503 504 /500.html;
  client_max_body_size 4G;
  keepalive_timeout 10;
}

and cap deploy.rb

# config valid only for current version of Capistrano
lock "3.8.0"
set :application, 'appname'
set :branch, :aws_deployment_v1
set :repo_url, git repo link
set :deploy_to, '/home/deploy/appname'
set :pty, true
set :linked_files, %w{config/database.yml config/application.yml}
set :linked_dirs, %w{bin log tmp/pids tmp/cache tmp/sockets vendor/bundle public/system public/uploads}
set :keep_releases, 5
set :rvm_type, :user
set :rvm_ruby_version, 'ruby-2.1.6' # Edit this if you are using MRI Ruby
set :puma_rackup, -> { File.join(current_path, 'config.ru') }
set :puma_state, "#{shared_path}/tmp/pids/puma.state"
set :puma_pid, "#{shared_path}/tmp/pids/puma.pid"
set :puma_bind, "unix://#{shared_path}/tmp/sockets/puma.sock"    #accept array for multi-bind
set :puma_conf, "#{shared_path}/puma.rb"
set :puma_access_log, "#{shared_path}/log/puma_error.log"
set :puma_error_log, "#{shared_path}/log/puma_access.log"
set :puma_role, :app
set :puma_env, fetch(:rack_env, fetch(:rails_env, 'production'))
set :puma_threads, [0, 8]
set :puma_workers, 0
set :puma_worker_timeout, nil
set :puma_init_active_record, true
set :puma_preload_app, false

Body:
Have you tried switching the index.html and the @app around?

try_files $uri @app $uri/index.html;


问:
Windows Forms Drag and Drop Functionality
I appear to have all of the things necessary for Drag-n-Drop to be working, yet my code is not called when I attempt to drag something from one control to another.

I created a Test Class to use to create data:

```<code>class TestClass
{

    public TestClass()
    {
        Name = "Blank";
        Id = -1;
    }

    public String Name { get; set; }

    public int Id { get; set; }

    public object Data { get; set; }

    public override String ToString()
    {
        return String.Format("{0}: {1}", Id, Name);
    }

}
</code>```

I created an empty form with 2 List View controls, listView1 and listView2:

I created event handlers for all of the Drag-n-Drop methods and put breakpoints on them:

```<code>private void Form_DragDrop(object sender, DragEventArgs e)
{
    e.Effect = DragDropEffects.Copy;
    if (e.Data.GetDataPresent(typeof(TestClass)))
    {
        var item = e.Data.GetData(typeof(TestClass)) as TestClass;
        if (item != null)
        {
            // ?
        }
    }
}

private void Form_DragEnter(object sender, DragEventArgs e)
{
    e.Effect = DragDropEffects.Copy;
    if (sender.Equals(listView2))
    {
        e.Effect = DragDropEffects.All;
        if (e.Data != null)
        {
            var format = GetString(e);
            Console.WriteLine("{0} has a(n) {1} entering it.", listView2.Name, format);
        }
    }
}

private void Form_DragLeave(object sender, EventArgs e)
{
    if (sender.Equals(listView2))
    {

    }
}

private void Form_DragOver(object sender, DragEventArgs e)
{
    // Code Project Article 9017 says DragOver fires repeatedly, even if the mouse does not move.
    if ((e.X != _lastX) || (e.Y != _lastY))
    {
        _lastX = e.X;
        _lastY = e.Y;
        if (e.Data.GetDataPresent(typeof(TestClass)))
        {

        }
        else
        {
            e.Effect = DragDropEffects.None;
        }
    }
}

private void Form_GiveFeedback(Object sender, GiveFeedbackEventArgs e)
{
    if (sender.Equals(listView2))
    {
        // ?
    }
}

private void Form_QueryContinueDrag(object sender, QueryContinueDragEventArgs e)
{
    var listView = sender as ListView;
    if (listView != null)
    {

    }
}

private String GetString(DragEventArgs e)
{
    var result = String.Empty;
    if ((e.AllowedEffect & DragDropEffects.Copy) == DragDropEffects.Copy)
    {
        var formats = e.Data.GetFormats();
        foreach (var format in formats)
        {
            Console.WriteLine("Data is in the format of [{0}].", format);
            result = format;
        }
    }
    return result;
}
</code>```

I wired both controls up after the constructor's InitializeComponent();:

```<code>public ListViewsForm()
{
    InitializeComponent();
    // Setup ListView 1:
    listView1.AllowDrop = true;
    listView1.DragDrop += Form_DragDrop;
    listView1.DragEnter += Form_DragEnter;
    listView1.DragLeave += Form_DragLeave;
    listView1.DragOver += Form_DragOver;
    listView1.GiveFeedback += Form_GiveFeedback;
    listView1.QueryContinueDrag += Form_QueryContinueDrag;
    listView1.Dock = DockStyle.Fill;
    listView1.View = View.List;
    // Setup ListView 2:
    listView2.AllowDrop = true;
    listView2.DragDrop += Form_DragDrop;
    listView2.DragEnter += Form_DragEnter;
    listView2.DragLeave += Form_DragLeave;
    listView2.DragOver += Form_DragOver;
    listView2.GiveFeedback += Form_GiveFeedback;
    listView2.QueryContinueDrag += Form_QueryContinueDrag;
    listView2.Dock = DockStyle.Fill;
    // Create some data:
    var group1 = new ListViewGroup("Known Colors");
    foreach (KnownColor known in Enum.GetValues(typeof(KnownColor)))
    {
        var item = new TestClass()
        {
            Name = known.ToString(),
            Id = (int)known,
            Data = known,
        };
        var color = Color.FromKnownColor(known);
        var lvi = new ListViewItem(item.ToString(), group1) {
            BackColor = Color.FromArgb(color.ToArgb() ^ 0xffffff),
            ForeColor = color,
            Tag = item,
        };
        listView1.Items.Add(lvi);
    }
}
</code>```

Whenever I run the project, everything loads up fine, but any attempt to drag an item from the LEFT side to the RIGHT side does nothing. None of my break points are hit. Nothing happens.

What have I left out?

答:
You are missing a handy event and the method that starts the dragging operation:</p>

```<code>listView1.ItemDrag += listView1_ItemDrag;

void listView1_ItemDrag(object sender, ItemDragEventArgs e) {
  DoDragDrop(e.Item, DragDropEffects.Copy);
}
</code>```

Body:
I appear to have all of the things necessary for Drag-n-Drop to be working, yet my code is not called when I attempt to drag something from one control to another.

I created a Test Class to use to create data:

class TestClass
{

    public TestClass()
    {
        Name = "Blank";
        Id = -1;
    }

    public String Name { get; set; }

    public int Id { get; set; }

    public object Data { get; set; }

    public override String ToString()
    {
        return String.Format("{0}: {1}", Id, Name);
    }

}

I created an empty form with 2 List View controls, listView1 and listView2:

I created event handlers for all of the Drag-n-Drop methods and put breakpoints on them:

private void Form_DragDrop(object sender, DragEventArgs e)
{
    e.Effect = DragDropEffects.Copy;
    if (e.Data.GetDataPresent(typeof(TestClass)))
    {
        var item = e.Data.GetData(typeof(TestClass)) as TestClass;
        if (item != null)
        {
            // ?
        }
    }
}

private void Form_DragEnter(object sender, DragEventArgs e)
{
    e.Effect = DragDropEffects.Copy;
    if (sender.Equals(listView2))
    {
        e.Effect = DragDropEffects.All;
        if (e.Data != null)
        {
            var format = GetString(e);
            Console.WriteLine("{0} has a(n) {1} entering it.", listView2.Name, format);
        }
    }
}

private void Form_DragLeave(object sender, EventArgs e)
{
    if (sender.Equals(listView2))
    {

    }
}

private void Form_DragOver(object sender, DragEventArgs e)
{
    // Code Project Article 9017 says DragOver fires repeatedly, even if the mouse does not move.
    if ((e.X != _lastX) || (e.Y != _lastY))
    {
        _lastX = e.X;
        _lastY = e.Y;
        if (e.Data.GetDataPresent(typeof(TestClass)))
        {

        }
        else
        {
            e.Effect = DragDropEffects.None;
        }
    }
}

private void Form_GiveFeedback(Object sender, GiveFeedbackEventArgs e)
{
    if (sender.Equals(listView2))
    {
        // ?
    }
}

private void Form_QueryContinueDrag(object sender, QueryContinueDragEventArgs e)
{
    var listView = sender as ListView;
    if (listView != null)
    {

    }
}

private String GetString(DragEventArgs e)
{
    var result = String.Empty;
    if ((e.AllowedEffect & DragDropEffects.Copy) == DragDropEffects.Copy)
    {
        var formats = e.Data.GetFormats();
        foreach (var format in formats)
        {
            Console.WriteLine("Data is in the format of [{0}].", format);
            result = format;
        }
    }
    return result;
}

I wired both controls up after the constructor's InitializeComponent();:

public ListViewsForm()
{
    InitializeComponent();
    // Setup ListView 1:
    listView1.AllowDrop = true;
    listView1.DragDrop += Form_DragDrop;
    listView1.DragEnter += Form_DragEnter;
    listView1.DragLeave += Form_DragLeave;
    listView1.DragOver += Form_DragOver;
    listView1.GiveFeedback += Form_GiveFeedback;
    listView1.QueryContinueDrag += Form_QueryContinueDrag;
    listView1.Dock = DockStyle.Fill;
    listView1.View = View.List;
    // Setup ListView 2:
    listView2.AllowDrop = true;
    listView2.DragDrop += Form_DragDrop;
    listView2.DragEnter += Form_DragEnter;
    listView2.DragLeave += Form_DragLeave;
    listView2.DragOver += Form_DragOver;
    listView2.GiveFeedback += Form_GiveFeedback;
    listView2.QueryContinueDrag += Form_QueryContinueDrag;
    listView2.Dock = DockStyle.Fill;
    // Create some data:
    var group1 = new ListViewGroup("Known Colors");
    foreach (KnownColor known in Enum.GetValues(typeof(KnownColor)))
    {
        var item = new TestClass()
        {
            Name = known.ToString(),
            Id = (int)known,
            Data = known,
        };
        var color = Color.FromKnownColor(known);
        var lvi = new ListViewItem(item.ToString(), group1) {
            BackColor = Color.FromArgb(color.ToArgb() ^ 0xffffff),
            ForeColor = color,
            Tag = item,
        };
        listView1.Items.Add(lvi);
    }
}

Whenever I run the project, everything loads up fine, but any attempt to drag an item from the LEFT side to the RIGHT side does nothing. None of my break points are hit. Nothing happens.

What have I left out?

Body:
You are missing a handy event and the method that starts the dragging operation:

listView1.ItemDrag += listView1_ItemDrag;

void listView1_ItemDrag(object sender, ItemDragEventArgs e) {
  DoDragDrop(e.Item, DragDropEffects.Copy);
}


答: You need to #include <string>.

Title: Errors creating a string in c++

Body: You need to #include <string>.


问:
How to set locale for numbers in angular 2.0
The number format in Swiss German is like "100'000.00" (not "100,000.00"). How can I change that? I tried to change the settings in number_pipe.js from en-US to de-CH without success.

```<code>var defaultLocale: string = 'de-CH';</code>```

Is there a workaround or do I have to implement my own pipe?

答:
If you only need one locale for your app, you can as of now (@angular ~2.4.0) register the locale provider in @NgModule.

@NgModule({
    ...
    providers: [
        {provide: LOCALE_ID, useValue: "de-CH"}
    ]
})
export class AppModule {}```

Body:
The number format in Swiss German is like "100'000.00" (not "100,000.00"). How can I change that? I tried to change the settings in number_pipe.js from en-US to de-CH without success.

var defaultLocale: string = 'de-CH';

Is there a workaround or do I have to implement my own pipe?


问:
iterating through json getting empty value
Not able to push values out. Please help!!

function pullJSON(data) {
 var url="https://www.eventbriteapi.com/v3/subcategories/?event_status=live&token=XXXXXXXXXXX&page_count=4"; // Paste your JSON URL here

   var response = UrlFetchApp.fetch(url); // get feed
 var data = JSON.parse(response.getContentText()); //
  var dict = JSON.stringify(data);
  //Logger.log(dict);
   var keys = [];
  for(var k in dict) keys.push(k+':'+dict[k]);
  Logger.log(keys);

}```

Here is the result: [17-03-29 11:41:19:033 EDT] []

JSON data

答:
When you use JSON.stringify(), it will return a string.  It looks like you want to have an object, not a string.

Try using this instead of your for loop:

```<code>var keys = Object.keys(data).map(function(key){ return key + ':' + data[key]});
</code>```

Body:
Not able to push values out. Please help!!

function pullJSON(data) {
 var url="https://www.eventbriteapi.com/v3/subcategories/?event_status=live&token=XXXXXXXXXXX&page_count=4"; // Paste your JSON URL here

   var response = UrlFetchApp.fetch(url); // get feed
 var data = JSON.parse(response.getContentText()); //
  var dict = JSON.stringify(data);
  //Logger.log(dict);
   var keys = [];
  for(var k in dict) keys.push(k+':'+dict[k]);
  Logger.log(keys);

}

Here is the result: [17-03-29 11:41:19:033 EDT] []

JSON data

Body:
When you use JSON.stringify(), it will return a string.  It looks like you want to have an object, not a string.

Try using this instead of your for loop:

var keys = Object.keys(data).map(function(key){ return key + ':' + data[key]});


问:
Regex URL - replace matches by links
I try to code a regex for URL (with replace) respecting these points :

http://www.test.com is correct
=> www.test.com

https://www.test.com is correct
=> www.test.com

http://test.com is correct
=> test.com

www.test.com is correct
=> www.test.com

test.com is incorrect

What I have done :

```<code>// __url__ is the rest of the regex but NOT IMPORTANT in my problem
var regex = new Regex(@"((https?:\/\/)?(?<URL>www\." + __url__ + "))");
regex.Replace("www.test.com", "<a href=\"http://${URL}\">${URL}</a>");
</code>```

Some problems here :

```<code>- Test 1 OK
- Test 2 KO
  I force http as protocol
- Test 3 KO
- Test 4 OK
</code>```

答:
You may capture either the protocol or the www. part to make either obligatory (with (?:(https?:\/\/)|(www\.))). That way, you will avoid matching test.com. Then, you will just need to use a dynamic replacing logic inside a match evaluator:

```<code>var inputs = new[] {"http://www.test.com",  "https://www.test.com", "http://test.com", "www.test.com","test.com" };
foreach (var s in inputs)
{
    var res = Regex.Replace(s,@"(?:(https?:\/\/)|(www\.))(\S+)", m =>
        m.Groups[1].Success ?
            string.Format("<a href=\"{0}{1}{2}\">{1}{2}</a>", m.Groups[1].Value,m.Groups[2].Value,m.Groups[3].Value) :
            string.Format("<a href=\"http://{0}{1}\">{0}{1}</a>", m.Groups[2].Value,m.Groups[3].Value)
        );
    Console.WriteLine("{0} => {1}", s, res);
}
</code>```

See the C# online demo

Output:

```<code>http://www.test.com => <a href="http://www.test.com">www.test.com</a>
https://www.test.com => <a href="https://www.test.com">www.test.com</a>
http://test.com => <a href="http://test.com">test.com</a>
www.test.com => <a hr
</code>```

Title: Regex URL - replace matches by links

Body:
I try to code a regex for URL (with replace) respecting these points :

http://www.test.com is correct
=> www.test.com

https://www.test.com is correct
=> www.test.com

http://test.com is correct
=> test.com

www.test.com is correct
=> www.test.com

test.com is incorrect

What I have done :

// __url__ is the rest of the regex but NOT IMPORTANT in my problem
var regex = new Regex(@"((https?:\/\/)?(?<URL>www\." + __url__ + "))");
regex.Replace("www.test.com", "${URL}");

Some problems here :

- Test 1 OK
- Test 2 KO
  I force http as protocol
- Test 3 KO
- Test 4 OK

Body:
You may capture either the protocol or the www. part to make either obligatory (with (?:(https?:\/\/)|(www\.))). That way, you will avoid matching test.com. Then, you will just need to use a dynamic replacing logic inside a match evaluator:

var inputs = new[] {"http://www.test.com",  "https://www.test.com", "http://test.com", "www.test.com","test.com" };
foreach (var s in inputs)
{
    var res = Regex.Replace(s,@"(?:(https?:\/\/)|(www\.))(\S+)", m =>
        m.Groups[1].Success ?
            string.Format("<a href=\"{0}{1}{2}\">{1}{2}</a>", m.Groups[1].Value,m.Groups[2].Value,m.Groups[3].Value) :
            string.Format("<a href=\"http://{0}{1}\">{0}{1}</a>", m.Groups[2].Value,m.Groups[3].Value)
        );
    Console.WriteLine("{0} => {1}", s, res);
}

See the C# online demo

Output:

http://www.test.com => <a href="http://www.test.com">www.test.com</a>
https://www.test.com => <a href="https://www.test.com">www.test.com</a>
http://test.com => <a href="http://test.com">test.com</a>
www.test.com => <a hr


问:
How to POST json from c# through localhost and get the data in php?
I'm trying to do a simple program with a very simple UI.

Just a button in a c# windows form, when i press the button it encodes a simple array to Json and upload it to http://localhost, and then get the json data in PHP.

This is my code now in c#

```<code>private void button_Click(object sender, RoutedEventArgs e)
{
    var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://localhost:8080/SemesterProject/index.php");
    httpWebRequest.ContentType = "application/json";
    httpWebRequest.Method = "POST";

    using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
    {
        string json = new JavaScriptSerializer().Serialize(new
        {
            user = "Foo",
            password = "Baz"
        });

        streamWriter.Write(json);
        Console.WriteLine("Console.WriteLine(json);");
        Console.WriteLine(json);

    }

    var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
    using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
    {
        var result = streamReader.ReadToEnd();
        Console.WriteLine("Console.WriteLine(result);");
        Console.WriteLine(result);

    }
}
</code>```

And this is my code in PHP:

```<code><?php
$post= file_get_contents("php://input");
$decodedjson=json_decode($post,true);
var_dump($decodedjson);

?>
</code>```

at PHP output i get
       'NULL'
and in c# output i get

```<code>Console.WriteLine(json);
{"user":"Foo","password":"Baz"}
Console.WriteLine(result);
array(2) {
  ["user"]=>
  string(3) "Foo"
  ["password"]=>
  string(3) "Baz"
}
</code>```

After this i need to post the data from PHP to phpMyAdmin database

答:
Try simple way:

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections.Specialized;
using System.Net;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
    public Form1()
        {
        InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {

        using (var client = new WebClient())
            {
            var postData = new NameValueCollection();
            postData["user"] = "Foo";
            postData["password"] = "Baz";
            var response = client.UploadValues("http://localhost/xxx.php", postData);
            var data = Encoding.Default.GetString(response);
            // Console.WriteLine("Data from server: " + data);
            MessageBox.Show(data);
            }

        }
    }
}
</code>```

// php file xxx.php

```<code><?php
echo json_encode($_POST);
?>
</code>```

In your message box will dosplay json string

Body:
I'm trying to do a simple program with a very simple UI.

Just a button in a c# windows form, when i press the button it encodes a simple array to Json and upload it to http://localhost, and then get the json data in PHP.

This is my code now in c#

private void button_Click(object sender, RoutedEventArgs e)
{
    var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://localhost:8080/SemesterProject/index.php");
    httpWebRequest.ContentType = "application/json";
    httpWebRequest.Method = "POST";

    using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
    {
        string json = new JavaScriptSerializer().Serialize(new
        {
            user = "Foo",
            password = "Baz"
        });

        streamWriter.Write(json);
        Console.WriteLine("Console.WriteLine(json);");
        Console.WriteLine(json);

    }

    var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
    using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
    {
        var result = streamReader.ReadToEnd();
        Console.WriteLine("Console.WriteLine(result);");
        Console.WriteLine(result);

    }
}

And this is my code in PHP:

<?php
$post= file_get_contents("php://input");
$decodedjson=json_decode($post,true);
var_dump($decodedjson);

?>

at PHP output i get
       'NULL'
and in c# output i get

Console.WriteLine(json);
{"user":"Foo","password":"Baz"}
Console.WriteLine(result);
array(2) {
  ["user"]=>
  string(3) "Foo"
  ["password"]=>
  string(3) "Baz"
}

After this i need to post the data from PHP to phpMyAdmin database

Body:
Try simple way:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections.Specialized;
using System.Net;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
    public Form1()
        {
        InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {

        using (var client = new WebClient())
            {
            var postData = new NameValueCollection();
            postData["user"] = "Foo";
            postData["password"] = "Baz";
            var response = client.UploadValues("http://localhost/xxx.php", postData);
            var data = Encoding.Default.GetString(response);
            // Console.WriteLine("Data from server: " + data);
            MessageBox.Show(data);
            }

        }
    }
}

// php file xxx.php

<?php
echo json_encode($_POST);
?>

In your message box will dosplay json string


答:
You must include the string file like this:

```<code>#include <string>
</code>```

to use std::string .

It's something like import in Java, except that Java imports classes / namespaces, C++ imports libraries or header files.

Title: Errors creating a string in c++

Body:
Whenever I try to create a string in my header file I get the error: 'string' is not a member of 'std'. I am using the Microsoft Visual c++ express 2010 compiler. Here is my header file:

using namespace std;

class Person
{
private:
 string name;
 string p_number;

public:
 Person();
 Person(string, string);
 string get_number();
 string get_name();
};

I am a decent java programmer who just started  learning c++

Body:
You must include the string file like this:

#include <string>

to use std::string .

It's something like import in Java, except that Java imports classes / namespaces, C++ imports libraries or header files.


问:
Laravel 5.2.45 Method store does not exist
I am trying to copy a file to my server Public Folder.

I am getting the following error :

BadMethodCallException in Macroable.php line 74: Method store does not exist.

This is the html to upload the file :

```<code> <form action="/leads/csvFiles" method="post" enctype="multipart/form-data">
                            {{csrf_field()}}
                            <input type="file" name="csvfile" />
                            <input type="submit"/>
                        </form>
</code>```

And here is the Route:

```<code>Route::post('leads/csvFiles', function(){

request()->file('csvfile')->store('Public');
return back();

});
</code>```

答:
store() method has been implemented from Laravel 5.3, you need to use something like:

```<code>Route::post('leads/csvFiles', function(){
    $request->file('csvfile')->move('Public');
    return back();
});
</code>```

Its advised to check first if file is valid:

```<code>if ($request->file('csvfile')->isValid()) {
    //next code here
}
</code>```

Then you you can actually save the file with whatever name you want.

```<code>$request->file('csvfile')->move('Public', 'myfilename.csv');
</code>```

Body:
I am trying to copy a file to my server Public Folder.

I am getting the following error :

BadMethodCallException in Macroable.php line 74: Method store does not exist.

This is the html to upload the file :

 <form action="/leads/csvFiles" method="post" enctype="multipart/form-data">
                            {{csrf_field()}}
                            <input type="file" name="csvfile" />
                            <input type="submit"/>
                        </form>

And here is the Route:

Route::post('leads/csvFiles', function(){

request()->file('csvfile')->store('Public');
return back();

});

Body:
store() method has been implemented from Laravel 5.3, you need to use something like:

Route::post('leads/csvFiles', function(){
    $request->file('csvfile')->move('Public');
    return back();
});

Its advised to check first if file is valid:

if ($request->file('csvfile')->isValid()) {
    //next code here
}

Then you you can actually save the file with whatever name you want.

$request->file('csvfile')->move('Public', 'myfilename.csv');


问:
Windows Updates caused Internet Explorer to shrink an iframe to quarter of its size
Our users found an issue in which (when discovered by our IT department) Windows updates KB4012204 and KB4012216 caused an IFrame that had a list of radio buttons to shrink to a quarter of the size and add the scrollbar as seen below (I had to obfuscate some things, so excuse the ugly pic):

答:
We weren't very successful in finding a solid solution to the issue.  The one suggestion we found from https://www.askwoody.com/forums/topic/win10-march-cumulative-update-kb-4013429-breaks-display-of-forms-in-ms-dynamics-crm-2011/#post-101672 did not work for us since it didn't pertain to our situation.

What I found worked for us was setting the height of the IFrame to something very high like 750px instead of just using 100%.  It works for our case, but I'm wondering if anyone else has encountered the issue and if they have a better solution to this.  If not, feel free to use this solution as a starting point if you are encountering what we found.


问:
how to switch to a variable sheet based on a cell value in google sheets
I am looking to create a button in google sheets and assign it a script which will take the user to a specific sheet based on a specific string in a cell.

I have played around trying to merge other answers to similar questions but i haven't been successful!

This is where i am at currently:

```<code>function sheetchanger() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var cell = ss.getRange("Lookup!B5");
ss.setActiveSheet(cell)
</code>```

I am really, REALLY new to code, so please excuse the above if it is way off!

Thanks for any and all help :)

答:
Try this:

function sheetChanger() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var first = ss.getSheetByName("Lookup");
  var range = first.getRange("B5:B5");
 range.activate();
}```
</div>
</div>
</p>

<p>Looking again, I think I misunderstood what you are trying to do. If you want to jump to Lookup!B5 then the above will work. </p>

<p>If you need to jump to the sheet that is named in Lookup!B5, then this will work:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function sheetChanger() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var first = ss.getSheetByName("Lookup");
  var range = first.getRange("B5");
  var cell = range.getCell(1,1);
  var sheet = cell.getValue();
  Logger.log(cell.getValue());
  ss.getSheetByName(sheet).getRange("A1").activate();
}</code>```

Body:
I am looking to create a button in google sheets and assign it a script which will take the user to a specific sheet based on a specific string in a cell.

I have played around trying to merge other answers to similar questions but i haven't been successful!

This is where i am at currently:

function sheetchanger() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var cell = ss.getRange("Lookup!B5");
ss.setActiveSheet(cell)

I am really, REALLY new to code, so please excuse the above if it is way off!

Thanks for any and all help :)

Body:
Try this:

function sheetChanger() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var first = ss.getSheetByName("Lookup");
  var range = first.getRange("B5:B5");
 range.activate();
}

Looking again, I think I misunderstood what you are trying to do. If you want to jump to Lookup!B5 then the above will work.

If you need to jump to the sheet that is named in Lookup!B5, then this will work:

function sheetChanger() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var first = ss.getSheetByName("Lookup");
  var range = first.getRange("B5");
  var cell = range.getCell(1,1);
  var sheet = cell.getValue();
  Logger.log(cell.getValue());
  ss.getSheetByName(sheet).getRange("A1").activate();
}


问:
Could not retrieve the change details
Git Extensions is all setup, the repository can be cloned, commits can be published to Gerrit, but it seems that the "Download Gerrit Change" button doesn't work as it give me an error saying Could not retrieve the change details.

I got all of this working on a previous machine, but now I had to change to a different one and it seems that it stopped working.

Checked all the settings on the 2 machines and they are matching.

The only difference is that the previous machine was on Windows 8.1 and this one is on Windows 10 (don't know if this can cause a problem).

Any help would be appreciated.

GitExtension version 2.49
Git version 2.11.1

Edit : One thing to add here is that previously I was using Windows 8.1 and the new machine has Windows 10 (don't know if that could cause the problem). All of my colleagues that have the same problem are on Windows 10.

答:
Don't know exactly at what stage this is supposed to happen, but it seems like the ssh agent is supposed to have some environment variables being set.

GitExtensions is trying to look for the location of the ssh.exe file, but it fails and that's why the error message is thrown.

The Environment Variables (to get here, press WINDOWS KEY + PAUSE -> Advanced System Settings -> Environment Variables...) that we need to have are:

User variables:

Name: GIT_SSH

Value: C:\Program Files (x86)\Git\usr\bin\ssh.exe

System variables

Name: GIT_SSH

Value: C:\Program Files (x86)\Git\usr\bin

*Note: This is where the ssh agent is in my case (and my colleagues), check where your one is and replace the paths.

Hope this helps!

UPDATE:

An even easier way of sorting out this problem is just to go into GitExtensions -> Tools -> Settings -> SSH and select Other ssh client and specify the location of ssh.exe (in my case it was C:\Program Files (x86)\Git\usr\bin\ssh.exe).

Title: Could not retrieve the change details


问:
Python - Method that calls itself
I am trying to learn Python. I just made a simple rock, paper, scissors game for practice. I am having a small problem.

When each player choose the same item, the game ends in a tie.

When the player makes a mistake and has to choose again, the variable is empty. Notice that Player 1 says "none".

This is the method. The problem occurs in the else branch.

```<code>def play1():
    player1_choice = input("Player 1 - Go: ")
    if (check(player1_choice)):
        return player1_choice
    else:
        print(error_msg)
        play1() # Something is wrong here.
</code>```

What did I do wrong? How can I fix it? Thanks

答:
Don't use recursion if you don't have to. Try this:</p>

```<code>def play1():
    while True:
        player1_choice = input("Player 1 - Go: ")
        if (check(player1_choice)):
            return player1_choice
        else:
            print(error_msg)
</code>```

Title: Python - Method that calls itself

Body:
I am trying to learn Python. I just made a simple rock, paper, scissors game for practice. I am having a small problem.

When each player choose the same item, the game ends in a tie.

When the player makes a mistake and has to choose again, the variable is empty. Notice that Player 1 says "none".

This is the method. The problem occurs in the else branch.

def play1():
    player1_choice = input("Player 1 - Go: ")
    if (check(player1_choice)):
        return player1_choice
    else:
        print(error_msg)
        play1() # Something is wrong here.

What did I do wrong? How can I fix it? Thanks

Body:
Don't use recursion if you don't have to. Try this:

def play1():
    while True:
        player1_choice = input("Player 1 - Go: ")
        if (check(player1_choice)):
            return player1_choice
        else:
            print(error_msg)


问:
Implicit looping through numpy array to replace values
I'm new to python and am trying to find a way to implicitly replace values in "array_to_replace" with one of two values in "values_to_use" based on the values in "array_of_positions":

First, the setup:

```<code>values_to_use = np.array([[0.5, 0.3, 0.4], [0.6, 0.7, 0.75]])
array_of_positions = np.array([0, 1, 1, 0, 1, 0, 0, 1, 0, 1])
array_to_replace = np.array([[5, 5, 4], [6, 5, 4], [1, 2, 3], [9, 9, 9], [8, 8, 8], [7, 7, 7], [6, 5, 7], [5, 7, 9], [1, 3, 5], [3, 3, 3]])
</code>```

Then, the brute force way to do what I want, which is to replace values in "array_to_replace" based on conditional values in "array_of_positions", is something like the following:

```<code>for pos in range(0, len(aray_to_replace)):
   if (array_of_positions[pos] == 0):
      array_to_replace[pos] = values_to_use[0]
   else:
      array_to_replace[pos] = values_to_use[1]
</code>```

Would you have any recommendations on how to do this happen implicitly?

答:
The answer for this turned out to be pretty simple.  To get what I wanted, all I needed to do was the following:

print values_to_use[array_of_positions]

This gave me what I needed.

Body:
I'm new to python and am trying to find a way to implicitly replace values in "array_to_replace" with one of two values in "values_to_use" based on the values in "array_of_positions":

First, the setup:

values_to_use = np.array([[0.5, 0.3, 0.4], [0.6, 0.7, 0.75]])
array_of_positions = np.array([0, 1, 1, 0, 1, 0, 0, 1, 0, 1])
array_to_replace = np.array([[5, 5, 4], [6, 5, 4], [1, 2, 3], [9, 9, 9], [8, 8, 8], [7, 7, 7], [6, 5, 7], [5, 7, 9], [1, 3, 5], [3, 3, 3]])

Then, the brute force way to do what I want, which is to replace values in "array_to_replace" based on conditional values in "array_of_positions", is something like the following:

for pos in range(0, len(aray_to_replace)):
   if (array_of_positions[pos] == 0):
      array_to_replace[pos] = values_to_use[0]
   else:
      array_to_replace[pos] = values_to_use[1]

Would you have any recommendations on how to do this happen implicitly?


问:
RecyclerView uses old ViewHolder when data fully changed
I have a recyclerview that shows "no content" layout before data has been loaded.
After I receive data I do:

```<code>    mItems.addAll(newItems);
    notifyDataSetChanged();
</code>```

After that everything is fine, except the last element is still "no content" layout. I have checked the behaviour and I know that RecyclerView uses the old layout. The problem is that that I need to use a different layout. And furthermore, why the old layout at last position and not at first as originally it has been?
How do I force RecyclerView to re-create that ViewHolder?

答:
You call notifyItemRangeRemoved(0, end), now the size of the adapter is 0.

Then you call notifyItemRangeChanged(0, end), but the adapter is empty so what is there to change? This leads to inconsistent state and might be the cause of the undesired behaviour.

Best solution would be to just update the items, then call notifyDataSetChanged(), since, well the entire data set has changed.

Other option is to first call notifyItemRangeRemoved with the old size and then notifyItemRangeInserted with the new size. Because at this point, you are not changing the removed items but adding new ones in.

Body:
I have a recyclerview that shows "no content" layout before data has been loaded.
After I receive data I do:

    mItems.addAll(newItems);
    notifyDataSetChanged();

After that everything is fine, except the last element is still "no content" layout. I have checked the behaviour and I know that RecyclerView uses the old layout. The problem is that that I need to use a different layout. And furthermore, why the old layout at last position and not at first as originally it has been?
How do I force RecyclerView to re-create that ViewHolder?


问:
Move files after importing into Access DB
I'm developing a VB macro in Access to import CSV files into an Access database and I would like move these files once the treatment is completed.

Public Sub RepertoireList()

Dim FolderName As String
Dim FolderNameMove As String
Dim FileList As String
Dim FileListMove As String
Dim FileToBeLoaded As String

tblName = "tbl_Test" 'This is to import all files into one table.
FolderName = "c:\CSV\"
FolderNameMove = "c:\CSV\Old"
FileList = Dir(FolderName & "\*.csv")
FileListMove = Dir(FolderNameMove & "\*.csv")

While (Len(Trim$(FileList)) > 0)

    If (Len(Trim$(FileList))) > 0 Then
        FileToBeLoaded = FolderName & FileList
        DoCmd.TransferText acImportDelim, "Test2 Import Specification", tblName, FileToBeLoaded, False

    End If
    FileList = Dir

    'Move files after import
    Sub Deplacer()
         Dim FSO As Object
         Set FSO = CreateObject("scripting.filesystemobject")
         FSO.MoveFile Source:=FolderName, Destination:=FolderNameMove
    End Sub

Wend

End Sub
```

The import works correctly but moving files isn't done correctly.

答:
```<code>Dim FolderName As String
Dim FileList As String
Dim FileToBeLoaded As String

tblName = "CV_Test" 'This is to import all files into one table.
FolderName = "c:\CSV\"
FolderNameMove = "c:\CSV\Old\"
FileList = Dir(FolderName & "\*.csv")

While (Len(Trim$(FileList)) > 0)
    If (Len(Trim$(FileList))) > 0 Then
        FileToBeLoaded = FolderName & FileList
        DoCmd.TransferText acImportDelim, "Test2 Import Specification", tblName, FileToBeLoaded, False
    End If
    FileList = Dir
Wend

'Move files after import
FileList = Dir(FolderName & "\*.csv")
While (Len(Trim$(FileList)) > 0)
    If (Len(Trim$(FileList))) > 0 Then
        Set FSO = CreateObject("scripting.filesystemobject")
        FSO.MoveFile Source:=FolderName & FileList, Destination:=FolderNameMove
    End If
    FileList = Dir

Wend
</code>```

Body:
I'm developing a VB macro in Access to import CSV files into an Access database and I would like move these files once the treatment is completed.

Public Sub RepertoireList()

Dim FolderName As String
Dim FolderNameMove As String
Dim FileList As String
Dim FileListMove As String
Dim FileToBeLoaded As String

tblName = "tbl_Test" 'This is to import all files into one table.
FolderName = "c:\CSV\"
FolderNameMove = "c:\CSV\Old"
FileList = Dir(FolderName & "\*.csv")
FileListMove = Dir(FolderNameMove & "\*.csv")

While (Len(Trim$(FileList)) > 0)

    If (Len(Trim$(FileList))) > 0 Then
        FileToBeLoaded = FolderName & FileList
        DoCmd.TransferText acImportDelim, "Test2 Import Specification", tblName, FileToBeLoaded, False

    End If
    FileList = Dir

    'Move files after import
    Sub Deplacer()
         Dim FSO As Object
         Set FSO = CreateObject("scripting.filesystemobject")
         FSO.MoveFile Source:=FolderName, Destination:=FolderNameMove
    End Sub

Wend

End Sub

The import works correctly but moving files isn't done correctly.


问:
Superscript Text in React Native
I would like to style text as superscript in React Native. How would this be accomplished? Is there a way to make use of the Javascript sup() string method to return a string as superscript within a <Text> object?

答:
Just use fontSize, lineHeight, textAlignVertical:</p>

```<code><Text style={{fontSize:20, lineHeight:22}}>
  foo
  <Text style={{fontSize:20 * 1.6, lineHeight:22 * 1.1, textAlignVertical: 'top'}}>
    bar
  </Text>
</Text>
</code>```

Title: Superscript Text in React Native

Body:
Just use fontSize, lineHeight, textAlignVertical:

<Text style={{fontSize:20, lineHeight:22}}>
  foo
  <Text style={{fontSize:20 * 1.6, lineHeight:22 * 1.1, textAlignVertical: 'top'}}>
    bar
  </Text>
</Text>


问:
Git edit undo. How do I edit undo many files with git?
I just made a bunch of mistakes in a bunch of my files.

Now I want to revert all those files back to the last committed change.

How to I do this with Git?

答:
```<code>git checkout HEAD -- path/to/file1 path/to/file2 ...
</code>```

To undo all of the changes you've made to every file in your working tree:

```<code>git reset --hard HEAD
</code>```

Body:
git checkout HEAD -- path/to/file1 path/to/file2 ...

To undo all of the changes you've made to every file in your working tree:

git reset --hard HEAD


问:
Realloc int array's new spaces in memory to 0
I have an int array that needs to grow when it sees a higher int value than it already has, is there any way to call realloc() and set all the new spaces in memory that are being created? Or do I need to loop through all the new spaces in memory and set them to 0 one by one? Code below for clarity.</p>

```<code>int main(){
    int i;
    int currentSize = 10;
    int *checkList = malloc(sizeof(int) * currentSize);
    while((i = readInt(fp))){
        if(i > currentSize){
             currentSize = i + 1;
             checklist = realloc(checkList, sizeof(int) * (i + 1));
             //Need to loop through checklist and declare empty mem to 0?
        }
        if(!checkList[i]) checkList[i]++;
    }

    //should have an array where seen values index in checklist == 1
}
</code>```

答:
here is how you could do the reallocation - it expands it to newSize and then uses memset to set the new elements to 0.

```<code>if(i >= currentSize) {
     int newSize = i + 1;
     checkList = realloc(checkList, sizeof(int) * newSize);
     memset(checkList+currentSize,0,sizeof(int) * (newSize - currentSize));
     currentSize = newSize;
}
</code>```

You'd probably want to use memset or calloc on your initial allocation to make sure those values are also 0 BTW.

Body:
I have an int array that needs to grow when it sees a higher int value than it already has, is there any way to call realloc() and set all the new spaces in memory that are being created? Or do I need to loop through all the new spaces in memory and set them to 0 one by one? Code below for clarity.

int main(){
    int i;
    int currentSize = 10;
    int *checkList = malloc(sizeof(int) * currentSize);
    while((i = readInt(fp))){
        if(i > currentSize){
             currentSize = i + 1;
             checklist = realloc(checkList, sizeof(int) * (i + 1));
             //Need to loop through checklist and declare empty mem to 0?
        }
        if(!checkList[i]) checkList[i]++;
    }

    //should have an array where seen values index in checklist == 1
}

Body:
here is how you could do the reallocation - it expands it to newSize and then uses memset to set the new elements to 0.

if(i >= currentSize) {
     int newSize = i + 1;
     checkList = realloc(checkList, sizeof(int) * newSize);
     memset(checkList+currentSize,0,sizeof(int) * (newSize - currentSize));
     currentSize = newSize;
}

You'd probably want to use memset or calloc on your initial allocation to make sure those values are also 0 BTW.


问:
struct pointers in c doesn't return correct value
I have this program:

```<code>#include <stdio.h>
#niclude ......

struct sort {
    char  * array;
    int left,right;
};

void quicksortthread(struct sort *s){
    int left, right;
    int i, j, x, tmp;
    pthread_t *th1, *th2;
    char * v;
    struct sort s1;
    struct sort s2;

    left = s->left;
    right = s->right;

    v = s->array;

    printf("\n\n\n\n QT: l=%i, r=%i \n",left,right);

    //sorting algorithm
    if (left >= right)
        return;
    x = v[left];
    i = left - 1;
    j = right + 1;
    while (i < j) {
        while (v[--j] > x);
        while (v[++i] < x);
        if (i < j) {
            char temp = v[i];
            v[i] = v[j];
            v[j] = temp;
        }
    }

    s1.array = v;
    s1.left = left;
    s1.right = j;
    s2.array = v;
    s2.left = j+1;
    s2.right = right;
    printf("1)left = %i; right= %i\n", left,j);
    printf("2)left = %i; right= %i\n", j+1,right);
    pthread_create(&th1, NULL, quicksortthread,&s1);
    pthread_create(&th2, NULL, quicksortthread,&s2);
}

int main (int argc, char ** argv){

    pthread_t *th1;
    int fd, len, pg, i, j;
    int left, right;
    struct stat stat_buf;
    char c, *paddr;
    struct sort s;

    /*..LOTS OF THIGS

      Define right and left as integers and
      paddr as a char *

      ..*/

    if(   (right)   >=  (atoi(argv[2]))  ){

        //printf("filling structure\n");
        s.array = paddr;
        s.left = left;
        s.right = right;
        //printf("creating threads\n");
        pthread_create(&th1, NULL, quicksortthread,&s);
    }

    sleep(100);
}
</code>```

After two thread calls it stops working. It is because the structure passed in the function pthread_create as a last parameter, seems like incorrect. It compiles and it execute without (for e.g.) segmentation fault. I am sure that I am using in the correct way structures and pointers.

Then the program returns in this way:

```<code>left = 0; right= 2048
QT: l=0, r=2048
1)left = 0; right= 0
2)left = 1; right= 2048

left = 0; right= 0
QT: l=0, r=0

left = 1037061890; right= 32542
QT: l=1037061890, r=32542
</code>```

SOLVED: Ok I have solve this problem changing the thread routine in this way:

```<code>nt left, right;
int i, j, x, tmp;
pthread_t th1, th2;
char * v;
struct sort * s1;
s1= malloc(sizeof(struct sort *));
struct sort * s2;
s2= malloc(sizeof(struct sort *));

left =  s->left;
right = s->right;
printf("\n\n\n\nleft = %i; right= %i\n", left,right);
v =  s->array;
printf("QT: l=%i, r=%i \n",left,right);

if (left >= right)
return;
x = v[left];
i = left - 1;
j = right + 1;
while (i < j) {
while (v[--j] > x);
while (v[++i] < x);
if (i < j) {

   char temp = v[i];
   v[i] = v[j];
   v[j] = temp;
     }
 }

 s1->array = v;
 s1->left = left;
 s1->right = j;
 s2->array = v;
 s2->left = j+1;
 s2->right = right;
 printf("1)left = %i; right= %i\n", left,j);
 printf("2)left = %i; right= %i\n", j+1,right);
 pthread_create(&th1, NULL, quicksortthread,s1);
 pthread_create(&th2, NULL, quicksortthread,s2);
</code>```

答:
struct sort s is an automatic variable and you are passing it's pointer to the thread. This is not a good practice. The thread will have it's existence even after the function which called pthread_create has returned in which case, the stack variable will be out of scope. Same issue exists for the way you creating threads from quicksortthread function itself in which struct sort s1 and struct sort s2 are local variables to the quicksortthread function. Better to allocate memory to these structures dynamically.

Also, it is not clear why you have added a sleep(100) in your main. You should be using pthread_join to wait for the created thread to complete before you exit from main.

pthread_create expects only a pthread_t * as the first argument, but, you are passing a pthread**. pthread_t *th1 should be pthread_t th1.

Body:
I have this program:

#include <stdio.h>
#niclude ......

struct sort {
    char  * array;
    int left,right;
};

void quicksortthread(struct sort *s){
    int left, right;
    int i, j, x, tmp;
    pthread_t *th1, *th2;
    char * v;
    struct sort s1;
    struct sort s2;

    left = s->left;
    right = s->right;

    v = s->array;

    printf("\n\n\n\n QT: l=%i, r=%i \n",left,right);

    //sorting algorithm
    if (left >= right)
        return;
    x = v[left];
    i = left - 1;
    j = right + 1;
    while (i < j) {
        while (v[--j] > x);
        while (v[++i] < x);
        if (i < j) {
            char temp = v[i];
            v[i] = v[j];
            v[j] = temp;
        }
    }

    s1.array = v;
    s1.left = left;
    s1.right = j;
    s2.array = v;
    s2.left = j+1;
    s2.right = right;
    printf("1)left = %i; right= %i\n", left,j);
    printf("2)left = %i; right= %i\n", j+1,right);
    pthread_create(&th1, NULL, quicksortthread,&s1);
    pthread_create(&th2, NULL, quicksortthread,&s2);
}

int main (int argc, char ** argv){

    pthread_t *th1;
    int fd, len, pg, i, j;
    int left, right;
    struct stat stat_buf;
    char c, *paddr;
    struct sort s;

    /*..LOTS OF THIGS

      Define right and left as integers and
      paddr as a char *

      ..*/

    if(   (right)   >=  (atoi(argv[2]))  ){

        //printf("filling structure\n");
        s.array = paddr;
        s.left = left;
        s.right = right;
        //printf("creating threads\n");
        pthread_create(&th1, NULL, quicksortthread,&s);
    }

    sleep(100);
}

After two thread calls it stops working. It is because the structure passed in the function pthread_create as a last parameter, seems like incorrect. It compiles and it execute without (for e.g.) segmentation fault. I am sure that I am using in the correct way structures and pointers.

Then the program returns in this way:

left = 0; right= 2048
QT: l=0, r=2048
1)left = 0; right= 0
2)left = 1; right= 2048

left = 0; right= 0
QT: l=0, r=0

left = 1037061890; right= 32542
QT: l=1037061890, r=32542

SOLVED: Ok I have solve this problem changing the thread routine in this way:

nt left, right;
int i, j, x, tmp;
pthread_t th1, th2;
char * v;
struct sort * s1;
s1= malloc(sizeof(struct sort *));
struct sort * s2;
s2= malloc(sizeof(struct sort *));

left =  s->left;
right = s->right;
printf("\n\n\n\nleft = %i; right= %i\n", left,right);
v =  s->array;
printf("QT: l=%i, r=%i \n",left,right);

if (left >= right)
return;
x = v[left];
i = left - 1;
j = right + 1;
while (i < j) {
while (v[--j] > x);
while (v[++i] < x);
if (i < j) {

   char temp = v[i];
   v[i] = v[j];
   v[j] = temp;
     }
 }

 s1->array = v;
 s1->left = left;
 s1->right = j;
 s2->array = v;
 s2->left = j+1;
 s2->right = right;
 printf("1)left = %i; right= %i\n", left,j);
 printf("2)left = %i; right= %i\n", j+1,right);
 pthread_create(&th1, NULL, quicksortthread,s1);
 pthread_create(&th2, NULL, quicksortthread,s2);