问:
Grow flexbox container height without row content overflowing
I have a flexbox page element with a min-height with a container that contains rows, and the rows contain events. The row heights are evenly distributed against the height of the container as in this example:

http://codepen.io/tysonnero/pen/LWXaMG

HTML

```<code><div class="page">
  <div class="container">
    <div class="row">
      <div class="event">Event 1</div>
      <div class="event">Event 2</div>
    </div>
    <div class="row">
      <div class="event">Event 1</div>
    </div>
    <div class="row">
      <div class="event">Event 1</div>
    </div>
    <div class="row">
      <div class="event">Event 1</div>
    </div>
  </div>
</div>
</code>```

CSS

```<code>.page {
  min-height: 300px;
  display: flex;
}

.container {
  display: flex;
  flex: 1;
  flex-direction: column;
  border: solid 1px #eee;
}

.row {
  display: flex;
  flex: 1;
  flex-direction: column;
  border: solid 1px #eee;
}
</code>```

However, if I add several additional events to the row, the events overflow into the next row as so:

http://codepen.io/tysonnero/pen/bqQyeG

HTML

```<code><div class="page">
  <div class="container">
    <div class="row">
      <div class="event">Event 1</div>
      <div class="event">Event 2</div>
      <div class="event">Event 3</div>
      <div class="event">Event 4</div>
      <div class="event">Event 5</div>
      <div class="event">Event 6</div>
    </div>
    <div class="row">
      <div class="event">Event 1</div>
    </div>
    <div class="row">
      <div class="event">Event 1</div>
    </div>
    <div class="row">
      <div class="event">Event 1</div>
    </div>
  </div>
</div>
</code>```

I can fix that by removing display:flex from the .page, but that causes the row to not evenly distribute the min-height when the row content is minimal.

Can anything recommend the best working approach to this?

答:
Looks like you just want to remove the flex: 1 property from .row, use the specific properties flex is short for (like flex-grow: 1), or specify each of the values you want to use in the shorthand property.

.page {
  min-height: 300px;
  display: flex;
}

.container {
  display: flex;
  flex: 1;
  flex-direction: column;
  border: solid 1px #eee;
}

.row {
  display: flex;
  flex-direction: column;
  border: solid 1px #eee;
  flex-grow: 1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="page">
  <div class="container">
    <div class="row">
      <div class="event">Event 1</div>
      <div class="event">Event 2</div>
      <div class="event">Event 3</div>
      <div class="event">Event 4</div>
      <div class="event">Event 5</div>
      <div class="event">Event 6</div>
    </div>
    <div class="row">
      <div class="event">Event 1</div>
    </div>
    <div class="row">
      <div class="event">Event 1</div>
    </div>
    <div class="row">
      <div class="event">Event 1</div>
    </div>
  </div>
</div></code>```

Body:
I have a flexbox page element with a min-height with a container that contains rows, and the rows contain events. The row heights are evenly distributed against the height of the container as in this example:

http://codepen.io/tysonnero/pen/LWXaMG

HTML

Event 1

Event 2

Event 1

Event 1

Event 1

CSS

.page {
  min-height: 300px;
  display: flex;
}

.container {
  display: flex;
  flex: 1;
  flex-direction: column;
  border: solid 1px #eee;
}

.row {
  display: flex;
  flex: 1;
  flex-direction: column;
  border: solid 1px #eee;
}

However, if I add several additional events to the row, the events overflow into the next row as so:

http://codepen.io/tysonnero/pen/bqQyeG

HTML

Event 1

Event 2

Event 3

Event 4

Event 5

Event 6

Event 1

Event 1

Event 1

I can fix that by removing display:flex from the .page, but that causes the row to not evenly distribute the min-height when the row content is minimal.

Can anything recommend the best working approach to this?

Body:
Looks like you just want to remove the flex: 1 property from .row, use the specific properties flex is short for (like flex-grow: 1), or specify each of the values you want to use in the shorthand property.

.page {
  min-height: 300px;
  display: flex;
}

.container {
  display: flex;
  flex: 1;
  flex-direction: column;
  border: solid 1px #eee;
}

.row {
  display: flex;
  flex-direction: column;
  border: solid 1px #eee;
  flex-grow: 1;
}

<div class="page">
  <div class="container">
    <div class="row">
      <div class="event">Event 1</div>
      <div class="event">Event 2</div>
      <div class="event">Event 3</div>
      <div class="event">Event 4</div>
      <div class="event">Event 5</div>
      <div class="event">Event 6</div>
    </div>
    <div class="row">
      <div class="event">Event 1</div>
    </div>
    <div class="row">
      <div class="event">Event 1</div>
    </div>
    <div class="row">
      <div class="event">Event 1</div>
    </div>
  </div>
</div>


来源: stackexchange

问:
download a file using grails project
i have a program with (".exe") type, i want to put a link in my grails project, when the user click it, this program download, how can i do this?</p>

答: You should use the static-resources plugin for that.</p>

ContentLicense: CC BY-SA 3.0

Title: download a file using grails project

ContentLicense: CC BY-SA 2.5


问:
how to change a variable value to the value of a text field?
So basically I have a component that I want to change its value, let's call him component A. And I have a component which is a text field, let's call him component B. How do I change the value of component A to the value of component B?

答:
The idea of a component is that the component class manages and controls its own template. Another component should not attempt to modify another component's template.

If one component has information that the other component's template needs, the component should provide the information to the other component's class and let the component update its template.

How this is done depends on the relationship between the components. If there is a "parent/child" relationship where one component is nested within the other, then there are well-documented techniques for parent/child communication. See this: https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#sts=Parent%20and%20children%20communicate%20via%20a%20service

If the components are not related, consider using a service to share data between the components.


问:
JavaScript ES6 - console.log with template literal
I'm writing node's script that connect to the mongo database.

I noticed that printing error response is different by small change in console.log syntax. Below example should be more meaningful.

```<code>#!/usr/bin/env node

const mongoose = require("mongoose");
const config = require("./config");

mongoose.connect(config.dbURI, (err) => {
    if (err) {
        console.log(`${err}`); // First console.log
        console.log(err); // Second console.log
    } else {
        console.log(`Database connection successful`)
    }
});
</code>```

Example output of the first console.log

```<code>MongoError: Authentication failed.
</code>```

Example output of the second console.log

```<code>{ MongoError: Authentication failed.
    at Function.MongoError.create (/Users/sigo/Sources/crypto-change/node_modules/mongodb-core/lib/error.js:31:11)
    at /Users/sigo/Sources/crypto-change/node_modules/mongodb-core/lib/connection/pool.js:489:72
    at authenticateStragglers (/Users/sigo/Sources/crypto-change/node_modules/mongodb-core/lib/connection/pool.js:435:16)
    at Connection.messageHandler (/Users/sigo/Sources/crypto-change/node_modules/mongodb-core/lib/connection/pool.js:469:5)
    at Socket.<anonymous> (/Users/sigo/Sources/crypto-change/node_modules/mongodb-core/lib/connection/connection.js:321:22)
    at emitOne (events.js:96:13)
    at Socket.emit (events.js:191:7)
    at readableAddChunk (_stream_readable.js:178:18)
    at Socket.Readable.push (_stream_readable.js:136:10)
    at TCP.onread (net.js:563:20)
  name: 'MongoError',
  message: 'Authentication failed.',
  ok: 0,
  code: 18,
  errmsg: 'Authentication failed.' }
</code>```

Where comes from this difference?

答:
By interpolating in a template string, the err object is cast to a string, using its own .toString method that is inherited from Error.prototype.toString. The code is equivalent to

```<code>console.log(String(err));
console.log(err.toString());
</code>```

When passing the err object directly to the console.log method, it uses node's inspect function instead, the code is equivalent to

```<code>console.log(util.inspect(err));
</code>```

Body:
I'm writing node's script that connect to the mongo database.

I noticed that printing error response is different by small change in console.log syntax. Below example should be more meaningful.

#!/usr/bin/env node

const mongoose = require("mongoose");
const config = require("./config");

mongoose.connect(config.dbURI, (err) => {
    if (err) {
        console.log(`${err}`); // First console.log
        console.log(err); // Second console.log
    } else {
        console.log(`Database connection successful`)
    }
});

Example output of the first console.log

MongoError: Authentication failed.

Example output of the second console.log

{ MongoError: Authentication failed.
    at Function.MongoError.create (/Users/sigo/Sources/crypto-change/node_modules/mongodb-core/lib/error.js:31:11)
    at /Users/sigo/Sources/crypto-change/node_modules/mongodb-core/lib/connection/pool.js:489:72
    at authenticateStragglers (/Users/sigo/Sources/crypto-change/node_modules/mongodb-core/lib/connection/pool.js:435:16)
    at Connection.messageHandler (/Users/sigo/Sources/crypto-change/node_modules/mongodb-core/lib/connection/pool.js:469:5)
    at Socket.<anonymous> (/Users/sigo/Sources/crypto-change/node_modules/mongodb-core/lib/connection/connection.js:321:22)
    at emitOne (events.js:96:13)
    at Socket.emit (events.js:191:7)
    at readableAddChunk (_stream_readable.js:178:18)
    at Socket.Readable.push (_stream_readable.js:136:10)
    at TCP.onread (net.js:563:20)
  name: 'MongoError',
  message: 'Authentication failed.',
  ok: 0,
  code: 18,
  errmsg: 'Authentication failed.' }

Where comes from this difference?

Body:
By interpolating in a template string, the err object is cast to a string, using its own .toString method that is inherited from Error.prototype.toString. The code is equivalent to

console.log(String(err));
console.log(err.toString());

When passing the err object directly to the console.log method, it uses node's inspect function instead, the code is equivalent to

console.log(util.inspect(err));


问:
C# read string from back to end
I have a string. For example :

```<code>string a = "abcdef098403248";
</code>```

My goal is, knowing that the string ends with a number (else something like this will happen : MessageBox.Show("String doesnt end in a number"); ), i want to read the string, starting from the end to the begining, and store the values in another string.
Now the only problem is, i can only store in that new string numbers, and when i read the string a , while i count from the back to end if i find a character that isnt a number, i stop reading and store the previous numbers found in the new string. The code output should look somthing like this:

```<code>string a = "aBcdef3213BBBBB0913456";
//part were i read the string from back to end
string finalString = "0913456";
</code>```

As you see there, i store the numbers from left to right, but i want to read them from right to left.

Another example of what i want:

```<code>string a = "aaaaa3a224444";
// part were i read the string from back to end
string finalString = "224444";
</code>```

Or:

```<code>string a = "3333333a224444";
// part were i read the string from back to end
string finalString = "224444";
</code>```

Regardless, thanks.

答:
I came up with this. Not as elegant as others. It adds the numbers to the string until it encounters a letter again then stops.</p>

```<code>    string a = "aBcdef3213BBBBB0913456";

    var charList = a.ToCharArray();

    string newString = string.Empty;

    foreach (var letter in charList.Reverse())
    {
        var number = 0;

        if (Int32.TryParse(letter.ToString(), out number))
        {
            newString = string.Format("{0}{1}", letter, newString);
        }
        else
        {
            break;
        }
    }
</code>```

Title: C# read string from back to end

Body:
I have a string. For example :

string a = "abcdef098403248";

My goal is, knowing that the string ends with a number (else something like this will happen : MessageBox.Show("String doesnt end in a number"); ), i want to read the string, starting from the end to the begining, and store the values in another string.
Now the only problem is, i can only store in that new string numbers, and when i read the string a , while i count from the back to end if i find a character that isnt a number, i stop reading and store the previous numbers found in the new string. The code output should look somthing like this:

string a = "aBcdef3213BBBBB0913456";
//part were i read the string from back to end
string finalString = "0913456";

As you see there, i store the numbers from left to right, but i want to read them from right to left.

Another example of what i want:

string a = "aaaaa3a224444";
// part were i read the string from back to end
string finalString = "224444";

Or:

string a = "3333333a224444";
// part were i read the string from back to end
string finalString = "224444";

Regardless, thanks.

Body:
I came up with this. Not as elegant as others. It adds the numbers to the string until it encounters a letter again then stops.

    string a = "aBcdef3213BBBBB0913456";

    var charList = a.ToCharArray();

    string newString = string.Empty;

    foreach (var letter in charList.Reverse())
    {
        var number = 0;

        if (Int32.TryParse(letter.ToString(), out number))
        {
            newString = string.Format("{0}{1}", letter, newString);
        }
        else
        {
            break;
        }
    }


问:
Chart.js time scale not showing data
I have a Chart.js chart which was displaying fine, until I added a time scale to it. The configuration looks like this:

```<code>    this.chart = new Chart(this.ctx, {
        type: 'line',
        data: data,
        options: {
            legend: {
                display: false
            },
            scales: {
                xAxes: [{
                    type: 'time',
                    time: {
                        unit: 'month',
                        format: 'timeFormat'
                    }
                }]
            }
        }
    });
</code>```

And the data object looks like this:

```<code>let data = {
    labels: ["1485903600", "1490738400"],
    datasets: [{
        label: '',
        data: [120, 30],
        lineTension: 0
    }]
};
</code>```

The x-axis displays the two dates correctly, and the y-axis is bounded by the correct limits (i.e. 120 and 30), but the data is not displaying on the graph.

答:
The reason your chart is not displaying data when you converted to the time scale is because you are passing string values for your labels that the Date constructor is not able to parse.

The time scale expects either an integer (number of milliseconds since epoch), a Date object, a moment.js object, or a string representation of a date that is in a format that Date.parse() can understand.

So in your case, when the chart is rendered it can not create Date objects for the X axis (because of your label values), so it creates 2 date objects using new Date() (this is why the X axis still displays some date data...notice that it is 2017 dates because new Date() returns a Date initialized to right now).

To correct this, just convert the label values to integers (e.g. remove the quotes) and the chart will then display your data points.  The chart still looks funny however because the X scale is configured in units of month but your data values are only 1 day apart (1485903600 = Jan 17, 1970 10:45 PM and 1490738400 = Jan 18, 1970 12:05 AM).

Here is a codepen example that shows your original chart and the correct chart so you can see the difference.

Title: Chart.js time scale not showing data

Body:
I have a Chart.js chart which was displaying fine, until I added a time scale to it. The configuration looks like this:

    this.chart = new Chart(this.ctx, {
        type: 'line',
        data: data,
        options: {
            legend: {
                display: false
            },
            scales: {
                xAxes: [{
                    type: 'time',
                    time: {
                        unit: 'month',
                        format: 'timeFormat'
                    }
                }]
            }
        }
    });

And the data object looks like this:

let data = {
    labels: ["1485903600", "1490738400"],
    datasets: [{
        label: '',
        data: [120, 30],
        lineTension: 0
    }]
};

The x-axis displays the two dates correctly, and the y-axis is bounded by the correct limits (i.e. 120 and 30), but the data is not displaying on the graph.


问:
ASP.NET MVC5 OWIN Facebook authentication suddenly not working
Update 2017!

The issue I had when I posted the original question has got nothing to do with the recent changes Facebook made when they forced everyone to version 2.3 of their API.  For a solution to that specific problem, see sammy34's answer below.  Version 2.3 of the /oauth/access_token endpoint now returns JSON instead of form-encoded values

For historical reasons, here's my original question/issue:

I've got an MVC5 Web application which is using the built-in support for authentication via Facebook and Google.  When we built this app a few months ago, we followed this tutorial: http://www.asp.net/mvc/tutorials/mvc-5/create-an-aspnet-mvc-5-app-with-facebook-and-google-oauth2-and-openid-sign-on and everything worked great.

Now, all of a sudden, the Facebook authentication has just stopped working alltogether.  The Google authentication still works great.

Description of the problem: We click the link to connect using Facebook, we are redirected to Facebook where we are prompted if we wan't to allow our Facebook app access to our profile.  When we click "OK" we are redirected back to our site, but instead of being logged in we simply end up at the login screen.

I've gone through this process in debug mode and I've got this ActionResult in my account controller as per the tutorial mentioned above:

```<code>// GET: /Account/ExternalLoginCallback
[AllowAnonymous]
public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
{
    var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
    if (loginInfo == null)
    {
        return RedirectToAction("Login");
    }
    ............
</code>```

When stepping through the code and upon returning from Facebook, the loginInfo object is always NULL, which causes the user to be redirected back to the login.

In order to understand what is actually happening behind the scenes, I installed Fiddler and monitored the HTTP traffic.  What I disovered is that upon clicking "OK" at the Facebook permission dialog, Facebook redirects back to our application with this URL:

```<code>https://localhost/signin-facebook?code=<access-token>
</code>```

This URL is not an actual file and probably handled by some controller/handler built into this OWIN framework I'm guessing.  Most likely, it is connecting back to Facebook using the given code to query information about the user which is trying to login.  Now, the problem is that instead of doing that, we are redirected to:

```<code>/Account/ExternalLoginCallback?error=access_denied
</code>```

Which I'm sure is something Facebook is doing, that is, instead of giving us the user data, it's redirecting us back with this error message.

This causes the AuthenticationManager.GetExternalLoginInfoAsync(); to fail and always return NULL.

I'm completely out of ideas.  As far as we know, we did not change anything on our end.

I've tried creating a new Facebook app, I've tried following the tutorial again but I always have the same problem.

Any ideas welcome!

Update!

OK, this is driving me insane!  I've now manually gone through the steps required to perform the authentication and everything works great when I do that.  Why on earth is this not working when using the MVC5 Owin stuff?

This is what I did:

```<code>    // Step 1 - Pasted this into a browser, this returns a code
    https://www.facebook.com/dialog/oauth?response_type=code&client_id=619359858118523&redirect_uri=https%3A%2F%2Flocalhost%2Fsignin-facebook&scope=&state=u9R1m4iRI6Td4yACEgO99ETQw9NAos06bZWilJxJrXRn1rh4KEQhfuEVAq52UPnUif-lEHgayyWrsrdlW6t3ghLD8iFGX5S2iUBHotyTqCCQ9lx2Nl091pHPIw1N0JV23sc4wYfOs2YU5smyw9MGhcEuinvTAEql2QhBowR62FfU6PY4lA6m8pD3odI5MwBYOMor3eMLu2qnpEk0GekbtTVWgQnKnH6t1UcC6KcNXYY

I was redirected back to localhost (which I had shut down at this point to avoid being redirected immediately away).  The URL I was redirected to is this:

https://localhost/signin-facebook?code=<code-received-removed-for-obvious-reasons>

Now, I grabbed the code I got and used it in the URL below:

// Step 2 - opened this URL in a browser, and successfully retrieved an access token
https://graph.facebook.com/oauth/access_token?client_id=619359858118523&redirect_uri=https://localhost/signin-facebook&client_secret=<client-secret>&code=<code-from-step-1>

// Step 3 - Now I'm able to query the facebook graph using the access token from step 2!

https://graph.facebook.com/me?access_token=<access-token-from-step-2>
</code>```

No errors, everything works great!  Then why the hell is this not working when using the MVC5 Owin stuff?  There's obviously something wrong with the OWin implementation.

答:
I have been working on solution for three days. And I've just found it on github(https://github.com/aspnet/AspNetKatana/issues/38#issuecomment-290400987)

```<code>var facebookOptions = new FacebookAuthenticationOptions()
{
    AppId = "xxxxx",
    AppSecret = "xxxxx",
};

// Set requested scope
facebookOptions.Scope.Add("email");
facebookOptions.Scope.Add("public_profile");

// Set requested fields
facebookOptions.Fields.Add("email");
facebookOptions.Fields.Add("first_name");
facebookOptions.Fields.Add("last_name");

facebookOptions.Provider = new FacebookAuthenticationProvider()
{
    OnAuthenticated = (context) =>
        {
            // Attach the access token if you need it later on for calls on behalf of the user
            context.Identity.AddClaim(new System.Security.Claims.Claim("FacebookAccessToken", context.AccessToken));

            foreach (var claim in context.User)
            {
                //var claimType = string.Format("urn:facebook:{0}", claim.Key);
                var claimType = string.Format("{0}", claim.Key);
                string claimValue = claim.Value.ToString();

                    if (!context.Identity.HasClaim(claimType, claimValue))
                        context.Identity.AddClaim(new System.Security.Claims.Claim(claimType, claimValue, "XmlSchemaString", "Facebook"));
            }

            return Task.FromResult(0);
       }
};

app.UseFacebookAuthentication(facebookOptions);
</code>```

And to get values

```<code>var info = await AuthenticationManager.GetExternalLoginInfoAsync();

if (info != null)
{
    var firstName = info.ExternalIdentity.Claims.First(c => c.Type == "first_name").Value;
    var lastName = info.ExternalIdentity.Claims.First(c => c.Type == "last_name").Value;
}
</code>```

Body:
Update 2017!

The issue I had when I posted the original question has got nothing to do with the recent changes Facebook made when they forced everyone to version 2.3 of their API.  For a solution to that specific problem, see sammy34's answer below.  Version 2.3 of the /oauth/access_token endpoint now returns JSON instead of form-encoded values

For historical reasons, here's my original question/issue:

I've got an MVC5 Web application which is using the built-in support for authentication via Facebook and Google.  When we built this app a few months ago, we followed this tutorial: http://www.asp.net/mvc/tutorials/mvc-5/create-an-aspnet-mvc-5-app-with-facebook-and-google-oauth2-and-openid-sign-on and everything worked great.

Now, all of a sudden, the Facebook authentication has just stopped working alltogether.  The Google authentication still works great.

Description of the problem: We click the link to connect using Facebook, we are redirected to Facebook where we are prompted if we wan't to allow our Facebook app access to our profile.  When we click "OK" we are redirected back to our site, but instead of being logged in we simply end up at the login screen.

I've gone through this process in debug mode and I've got this ActionResult in my account controller as per the tutorial mentioned above:

// GET: /Account/ExternalLoginCallback
[AllowAnonymous]
public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
{
    var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
    if (loginInfo == null)
    {
        return RedirectToAction("Login");
    }
    ............

When stepping through the code and upon returning from Facebook, the loginInfo object is always NULL, which causes the user to be redirected back to the login.

In order to understand what is actually happening behind the scenes, I installed Fiddler and monitored the HTTP traffic.  What I disovered is that upon clicking "OK" at the Facebook permission dialog, Facebook redirects back to our application with this URL:

https://localhost/signin-facebook?code=<access-token>

This URL is not an actual file and probably handled by some controller/handler built into this OWIN framework I'm guessing.  Most likely, it is connecting back to Facebook using the given code to query information about the user which is trying to login.  Now, the problem is that instead of doing that, we are redirected to:

/Account/ExternalLoginCallback?error=access_denied

Which I'm sure is something Facebook is doing, that is, instead of giving us the user data, it's redirecting us back with this error message.

This causes the AuthenticationManager.GetExternalLoginInfoAsync(); to fail and always return NULL.

I'm completely out of ideas.  As far as we know, we did not change anything on our end.

I've tried creating a new Facebook app, I've tried following the tutorial again but I always have the same problem.

Any ideas welcome!

Update!

OK, this is driving me insane!  I've now manually gone through the steps required to perform the authentication and everything works great when I do that.  Why on earth is this not working when using the MVC5 Owin stuff?

This is what I did:

    // Step 1 - Pasted this into a browser, this returns a code
    https://www.facebook.com/dialog/oauth?response_type=code&client_id=619359858118523&redirect_uri=https%3A%2F%2Flocalhost%2Fsignin-facebook&scope=&state=u9R1m4iRI6Td4yACEgO99ETQw9NAos06bZWilJxJrXRn1rh4KEQhfuEVAq52UPnUif-lEHgayyWrsrdlW6t3ghLD8iFGX5S2iUBHotyTqCCQ9lx2Nl091pHPIw1N0JV23sc4wYfOs2YU5smyw9MGhcEuinvTAEql2QhBowR62FfU6PY4lA6m8pD3odI5MwBYOMor3eMLu2qnpEk0GekbtTVWgQnKnH6t1UcC6KcNXYY

I was redirected back to localhost (which I had shut down at this point to avoid being redirected immediately away).  The URL I was redirected to is this:

https://localhost/signin-facebook?code=

Now, I grabbed the code I got and used it in the URL below:

// Step 2 - opened this URL in a browser, and successfully retrieved an access token
https://graph.facebook.com/oauth/access_token?client_id=619359858118523&redirect_uri=https://localhost/signin-facebook&client_secret=<client-secret>&code=

// Step 3 - Now I'm able to query the facebook graph using the access token from step 2!

https://graph.facebook.com/me?access_token=<access-token-from-step-2>

No errors, everything works great!  Then why the hell is this not working when using the MVC5 Owin stuff?  There's obviously something wrong with the OWin implementation.

Body:
I have been working on solution for three days. And I've just found it on github(https://github.com/aspnet/AspNetKatana/issues/38#issuecomment-290400987)

var facebookOptions = new FacebookAuthenticationOptions()
{
    AppId = "xxxxx",
    AppSecret = "xxxxx",
};

// Set requested scope
facebookOptions.Scope.Add("email");
facebookOptions.Scope.Add("public_profile");

// Set requested fields
facebookOptions.Fields.Add("email");
facebookOptions.Fields.Add("first_name");
facebookOptions.Fields.Add("last_name");

facebookOptions.Provider = new FacebookAuthenticationProvider()
{
    OnAuthenticated = (context) =>
        {
            // Attach the access token if you need it later on for calls on behalf of the user
            context.Identity.AddClaim(new System.Security.Claims.Claim("FacebookAccessToken", context.AccessToken));

            foreach (var claim in context.User)
            {
                //var claimType = string.Format("urn:facebook:{0}", claim.Key);
                var claimType = string.Format("{0}", claim.Key);
                string claimValue = claim.Value.ToString();

                    if (!context.Identity.HasClaim(claimType, claimValue))
                        context.Identity.AddClaim(new System.Security.Claims.Claim(claimType, claimValue, "XmlSchemaString", "Facebook"));
            }

            return Task.FromResult(0);
       }
};

app.UseFacebookAuthentication(facebookOptions);

And to get values

var info = await AuthenticationManager.GetExternalLoginInfoAsync();

if (info != null)
{
    var firstName = info.ExternalIdentity.Claims.First(c => c.Type == "first_name").Value;
    var lastName = info.ExternalIdentity.Claims.First(c => c.Type == "last_name").Value;
}


问:
Subprocess call to execute a complex command
I need to start the following command in my linux shell.

```<code>./bin/winexe -U ladmin //135.249.24.214  --interactive=0 --system "cmd.exe /c powershell -c (new-object System.Net.WebClient).DownloadFile('http://135.249.21.229/fr_query/base64.tcl','C:\Users\ladmin\Desktop\successshibani456.csv')"
</code>```

However, using subprocess.call(), the parentheses and quotes don't match correctly.

Escaping double quotes does not help.

```<code>subprocess.call("./bin/winexe -U ladmin //135.249.24.214  --interactive=0 --system \"cmd.exe /c powershell -c (new-object System.Net.WebClient).DownloadFile('http://135.249.21.229/fr_query/base64.tcl','C:\Users\ladmin\Desktop\successshibani456.csv')"\")
</code>```

Command is executed wrong.

答:
You can let the subprocess module do most of the escaping for you. Can you run the following command and verify if it works? The command has been separated into its component arguments. Because backslash characters are located in the last argument, the strings are written as being raw.

```<code>completed_process = subprocess.run((
    './bin/winexe',
    '-U',
    'ladmin',
    '//135.249.24.214',
    '--interactive=0',
    '--system',
    r'cmd.exe /c powershell -c (new-object System.Net.WebClient).DownloadFile('
    r'"http://135.249.21.229/fr_query/base64.tcl",'
    r'"C:\Users\ladmin\Desktop\successshibani456.csv")'
))
</code>```

Body:
I need to start the following command in my linux shell.

./bin/winexe -U ladmin //135.249.24.214  --interactive=0 --system "cmd.exe /c powershell -c (new-object System.Net.WebClient).DownloadFile('http://135.249.21.229/fr_query/base64.tcl','C:\Users\ladmin\Desktop\successshibani456.csv')"

However, using subprocess.call(), the parentheses and quotes don't match correctly.

Escaping double quotes does not help.

subprocess.call("./bin/winexe -U ladmin //135.249.24.214  --interactive=0 --system \"cmd.exe /c powershell -c (new-object System.Net.WebClient).DownloadFile('http://135.249.21.229/fr_query/base64.tcl','C:\Users\ladmin\Desktop\successshibani456.csv')"\")

Command is executed wrong.

Body:
You can let the subprocess module do most of the escaping for you. Can you run the following command and verify if it works? The command has been separated into its component arguments. Because backslash characters are located in the last argument, the strings are written as being raw.

completed_process = subprocess.run((
    './bin/winexe',
    '-U',
    'ladmin',
    '//135.249.24.214',
    '--interactive=0',
    '--system',
    r'cmd.exe /c powershell -c (new-object System.Net.WebClient).DownloadFile('
    r'"http://135.249.21.229/fr_query/base64.tcl",'
    r'"C:\Users\ladmin\Desktop\successshibani456.csv")'
))


问:
How to pass arguments to a promise?
In the examples I see, the code in a promise is static. An example:

```<code>var promise = new Promise(function (resolve,reject) {
  if (true)
    resolve("It is a success!")
  else
    reject(("It is a failure."));
});

promise.then(function (x) {
   alert(x);
}).catch(function (err) {
      alert("Error: " + err);
    });
</code>```

How do I pass arguments to the promise so that useful work can be done?  Is it by the use of global variables?

答:
Usually it may be done with the following code:

```<code>function getSomePromise(myVar) {
  var promise = new Promise(function (resolve,reject) {
    if (myVar)
      resolve("It is a success!")
    else
      reject(("It is a failure."));
  });
  return promise;
}

var variableToPass = true;
getSomePromise(variableToPass).then(function (x) {
  alert(x);
}).catch(function (err) {
  alert("Error: " + err);
});
</code>```

Update:

As @AlonEitan suggested, you can simplify getSomePromise function:

```<code>function getSomePromise(myVar) {
  return new Promise(function (resolve,reject) {
    if (myVar)
      resolve("It is a success!")
    else
      reject(("It is a failure."));
  });
}
</code>```

Title: How to pass arguments to a promise?

Body:
In the examples I see, the code in a promise is static. An example:

var promise = new Promise(function (resolve,reject) {
  if (true)
    resolve("It is a success!")
  else
    reject(("It is a failure."));
});

promise.then(function (x) {
   alert(x);
}).catch(function (err) {
      alert("Error: " + err);
    });

How do I pass arguments to the promise so that useful work can be done?  Is it by the use of global variables?

Body:
Usually it may be done with the following code:

function getSomePromise(myVar) {
  var promise = new Promise(function (resolve,reject) {
    if (myVar)
      resolve("It is a success!")
    else
      reject(("It is a failure."));
  });
  return promise;
}

var variableToPass = true;
getSomePromise(variableToPass).then(function (x) {
  alert(x);
}).catch(function (err) {
  alert("Error: " + err);
});

Update:

As @AlonEitan suggested, you can simplify getSomePromise function:

function getSomePromise(myVar) {
  return new Promise(function (resolve,reject) {
    if (myVar)
      resolve("It is a success!")
    else
      reject(("It is a failure."));
  });
}


问:
C# LocalDB connection
I have been trying to make my c# database application run everywhere but when using the following connection string

```<code> <add name="DBCS"
   connectionString="Data Source=(LocalDB)\v13;AttachDbFilename=|DataDirectory|\ServiceCardRecorderDatabase.mdf;Integrated Security=True;database=ServiceCardRecorderDatabase"
   providerName="System.Data.SqlClient" />
</code>```

and when I try to insert data to the table I get an exception saying
 System.Data.SqlClient.SqlException: 'A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 50 - Local Database Runtime error occurred. The specified LocalDB instance does not exist.

thrown from Visual Studio:

答:
Try modifying the following subsection in entity framework section in your web.config to

```<code><parameters>
        <parameter value="correctdbversion" />
</parameters>
</code>```

Where correctdbversion can be either of the following, mssqllocaldb, v11.0, v12.0

Title: C# LocalDB connection

Body:
I have been trying to make my c# database application run everywhere but when using the following connection string

 <add name="DBCS"
   connectionString="Data Source=(LocalDB)\v13;AttachDbFilename=|DataDirectory|\ServiceCardRecorderDatabase.mdf;Integrated Security=True;database=ServiceCardRecorderDatabase"
   providerName="System.Data.SqlClient" />

and when I try to insert data to the table I get an exception saying
 System.Data.SqlClient.SqlException: 'A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 50 - Local Database Runtime error occurred. The specified LocalDB instance does not exist.

thrown from Visual Studio:

Body:
Try modifying the following subsection in entity framework section in your web.config to

<parameters>
        <parameter value="correctdbversion" />
</parameters>

Where correctdbversion can be either of the following, mssqllocaldb, v11.0, v12.0


问:
evaluate mixed type with eval()
I have two date/time variables that contains list of the date/time values and another variable containing the list of operator to operate over the date/time variables. The format can be expressed as follows:

```<code>column1 = np.array([date1, date2,.......,dateN])
column2 = np.array([date1, date2,.......,dateN])
</code>```

Both of the above variables of type Date/Time. Then I have the following variable operator that has the same length of column1 and column2:

```<code>operator = np.array(['>=','<=','==','=!',......])
</code>```

I am getting "Invalid Token" with the following operation:

```<code>np.array([eval('{}{}{}'.format(v1,op,v2)) for v1,op,v2 in zip(column1,operator,column2)])
</code>```

Any hint to get around this issue ?

-------------------EDIT----------------------

With some sample data and without eval I get the following output:

```<code> np.array(['{} {} {}'.format(v1,op,v2) for v1,op,v2 in zip(datelist1,operator,datelist2)])

array(['2017-03-30 10:30:22.928000 <= 2012-05-23 00:00:00',
   '2011-01-07 00:00:00 == 2017-03-30 10:31:14.477000'],
  dtype='|S49')
</code>```

Once I bring in eval(), I get the following error:

```<code>eval('2011-01-07 00:00:00 == 2017-03-30 10:31:14.477000')
File "<string>", line 1
2011-01-07 00:00:00 == 2017-03-30 10:31:14.477000
            ^
SyntaxError: invalid syntax
</code>```

----------------------EDIT & CORRECTIONS ----------------------------

Date/Time variables that I mentioned before are basically of type numpy datetime64 type and I am now getting the following issue while trying two date comparions with eval:

```<code>np.array([(repr(d1)+op+repr(d2)) for d1,op,d2 in zip(${Column Name1},${Operator},${Column Name2})])
</code>```

The above snippet is tried over a table with three columns where ${Column Name1} and ${Column Name2} is of numpy.datetime64 type and ${Operator} is of string type. The result is as follows for one of the rows:

```<code>numpy.datetime64('2014-08-13T02:00:00.000000+0200')>=numpy.datetime64('2014-08-13T02:00:00.000000+0200')
</code>```

Now I want to evaluate the above expression with function eval as follows:

```<code>np.array([eval(repr(d1)+op+repr(d2)) for d1,op,d2 in zip(${Column Name1},${Operator},${Column Name2})])
</code>```

Eventually I get the following error:

```<code>NameError:name 'numpy' is not defined
</code>```

I can assume the problem. The Open Source Tool that I am using is importing numpy as np whereas repr() returning numpy that it does not recognize. If this is the problem , how to fix this issue ?

答:
You might want to use python operator for this:</p>

```<code># import operators used
import operator
from operator import ge, eq, le, ne

# build a look up table from string to operators
ops = {">=": ge, "==": eq, "<=": le, "!=": ne}

import numpy as np

# used some numbers to simplify the case, should work on datetime as well
a = np.array([1, 3, 5, 3])
b = np.array([2, 3, 2, 1])
operator = np.array(['>=','<=','==','!='])

# evaluate the operation
[ops[op](x, y) for op, x, y in zip(operator, a, b)]
# [False, True, False, True]
</code>```

Title: evaluate mixed type with eval()

Body:
I have two date/time variables that contains list of the date/time values and another variable containing the list of operator to operate over the date/time variables. The format can be expressed as follows:

column1 = np.array([date1, date2,.......,dateN])
column2 = np.array([date1, date2,.......,dateN])

Both of the above variables of type Date/Time. Then I have the following variable operator that has the same length of column1 and column2:

operator = np.array(['>=','<=','==','=!',......])

I am getting "Invalid Token" with the following operation:

np.array([eval('{}{}{}'.format(v1,op,v2)) for v1,op,v2 in zip(column1,operator,column2)])

Any hint to get around this issue ?

-------------------EDIT----------------------

With some sample data and without eval I get the following output:

 np.array(['{} {} {}'.format(v1,op,v2) for v1,op,v2 in zip(datelist1,operator,datelist2)])

array(['2017-03-30 10:30:22.928000 <= 2012-05-23 00:00:00',
   '2011-01-07 00:00:00 == 2017-03-30 10:31:14.477000'],
  dtype='|S49')

Once I bring in eval(), I get the following error:

eval('2011-01-07 00:00:00 == 2017-03-30 10:31:14.477000')
File "<string>", line 1
2011-01-07 00:00:00 == 2017-03-30 10:31:14.477000
            ^
SyntaxError: invalid syntax

----------------------EDIT & CORRECTIONS ----------------------------

Date/Time variables that I mentioned before are basically of type numpy datetime64 type and I am now getting the following issue while trying two date comparions with eval:

np.array([(repr(d1)+op+repr(d2)) for d1,op,d2 in zip(${Column Name1},${Operator},${Column Name2})])

The above snippet is tried over a table with three columns where ${Column Name1} and ${Column Name2} is of numpy.datetime64 type and ${Operator} is of string type. The result is as follows for one of the rows:

numpy.datetime64('2014-08-13T02:00:00.000000+0200')>=numpy.datetime64('2014-08-13T02:00:00.000000+0200')

Now I want to evaluate the above expression with function eval as follows:

np.array([eval(repr(d1)+op+repr(d2)) for d1,op,d2 in zip(${Column Name1},${Operator},${Column Name2})])

Eventually I get the following error:

NameError:name 'numpy' is not defined

I can assume the problem. The Open Source Tool that I am using is importing numpy as np whereas repr() returning numpy that it does not recognize. If this is the problem , how to fix this issue ?

Body:
You might want to use python operator for this:

# import operators used
import operator
from operator import ge, eq, le, ne

# build a look up table from string to operators
ops = {">=": ge, "==": eq, "<=": le, "!=": ne}

import numpy as np

# used some numbers to simplify the case, should work on datetime as well
a = np.array([1, 3, 5, 3])
b = np.array([2, 3, 2, 1])
operator = np.array(['>=','<=','==','!='])

# evaluate the operation
[ops[op](x, y) for op, x, y in zip(operator, a, b)]
# [False, True, False, True]


问:
SQL Server cyrillic error in php
First of all I want to apologize to my bad English.

And now for my problem. I have a SQL Server database and I want to get data from it with php. I can execute just select queries, because the database is not on localhost. I must get data from this database and the data is in cyrillic. This is my problem. When I execute mssql_query and get data, the Cyrillic symbols are returned as ????.

I try to convert characters with iconv and mb_convert_string, but without success.

Does anybody have a similar problem and how have you solved it?

答:
Do you have the cyrillic language pack installed on the web server and your client computer?  If you can connect to the SQL Server directly you might want to just export the data from the SQL Server using the BCP command line utility.

What is the end goal that you are going for?

Title: SQL Server cyrillic error in php


问:
How to print correctly an N-ary tree with dfs pre-order
I did a recursive pre-order depth-first search function of an N-ary tree in order to traverse it and print,but I want to remove the last space in the print. How can I do that without define other functions?

```<code> public void printdfs() {

    int sz = this.children.size();
    if (sz > 0) {
        System.out.print(getValue() + " ");
    }
    else {
        System.out.print(" " + getValue());
    }

    for (int i = 0; i < sz; i++) {
        MyTree object = this.children.get(i);
        System.out.print(".");
        object.printdfs();
    }

}

Output: 8 .20 .25 . 95. 70. 80. 30. 40. 10. 9
</code>```

My structure of the N-ary tree is:

```<code>public class MyTree {
private int data;
private LinkedList<MyTree> children;

public MyTree(int data) {
    this.data = data;
    this.children = new LinkedList<>();
}
public int getValue() {
    return this.data;
}
public void addChild(MyTree child) {
    this.children.addFirst(child);
}
}
</code>```

答:
Something like this?

```<code>    for (int i = 0; i < childrens.size(); i++) {
       MyTree object = childrens.get(i);
       if (i == (childrens.size() - 1)) {
          object.printdfs().trim();
       }
       else {
          object.printdfs();
       }
    }
</code>```

EDIT after comments: Would something like this work?

```<code>public void printdfs(PrintStream ps) {
    ps.print(getValue() + " ");
    for (int i = 0; i < childrens.size(); i++) {
       MyTree object = childrens.get(i);
       object.printdfs(ps);
    }
}
</code>```

Then you have a reference to the Stream object you originally pass in to the printdfs() method and you can then print out a substring of the Stream's data after printdfs() returns.

Or maybe you just want something like this?

```<code>public void printdfs() {
    int sz = childrens.size();
    if (sz < 0) {
        System.out.print(getValue() + " ");
    }
    else {
        System.out.print(getValue());
    }
    for (int i = 0; i < sz; i++) {
       MyTree object = childrens.get(i);
       object.printdfs();
    }
}
</code>```

Body:
I did a recursive pre-order depth-first search function of an N-ary tree in order to traverse it and print,but I want to remove the last space in the print. How can I do that without define other functions?

 public void printdfs() {

    int sz = this.children.size();
    if (sz > 0) {
        System.out.print(getValue() + " ");
    }
    else {
        System.out.print(" " + getValue());
    }

    for (int i = 0; i < sz; i++) {
        MyTree object = this.children.get(i);
        System.out.print(".");
        object.printdfs();
    }

}

Output: 8 .20 .25 . 95. 70. 80. 30. 40. 10. 9

My structure of the N-ary tree is:

public class MyTree {
private int data;
private LinkedList<MyTree> children;

public MyTree(int data) {
    this.data = data;
    this.children = new LinkedList<>();
}
public int getValue() {
    return this.data;
}
public void addChild(MyTree child) {
    this.children.addFirst(child);
}
}

Body:
Something like this?

    for (int i = 0; i < childrens.size(); i++) {
       MyTree object = childrens.get(i);
       if (i == (childrens.size() - 1)) {
          object.printdfs().trim();
       }
       else {
          object.printdfs();
       }
    }

EDIT after comments: Would something like this work?

public void printdfs(PrintStream ps) {
    ps.print(getValue() + " ");
    for (int i = 0; i < childrens.size(); i++) {
       MyTree object = childrens.get(i);
       object.printdfs(ps);
    }
}

Then you have a reference to the Stream object you originally pass in to the printdfs() method and you can then print out a substring of the Stream's data after printdfs() returns.

Or maybe you just want something like this?

public void printdfs() {
    int sz = childrens.size();
    if (sz < 0) {
        System.out.print(getValue() + " ");
    }
    else {
        System.out.print(getValue());
    }
    for (int i = 0; i < sz; i++) {
       MyTree object = childrens.get(i);
       object.printdfs();
    }
}


问:
installing net framework 4 upon windows 10 environment
i really need to install .net 4 for MATLAB R2016a compiler, the problem s windows 10 has .net 4.6 and don't allow any earlier version to be installed
 I followed the suggestions in a previous related question but unfortunatelly none of the mentioned packages installed</p>

答:
Turn ON windows features of .net framework 3.5 and .net framework 4.6 from Control Panel >> Programs and Features.
https://msdn.microsoft.com/en-us/library/hh506443(v=vs.110).aspx</p>


问:
How to implement subscribe model for RabbitMQ and requeue unprocessed messages
I have a Windows service that consumes messages from a remotely hosted RabbitMQ queue.

I have working code that wakes up at fixed intervals and connects to the queue and takes messages and processes them (mostly persists them to a database). This is a simplified version of what works for me:

```<code>        #region currentmethod

        IConnection connection = factory.CreateConnection();
        IModel channel = connection.CreateModel();
        channel.ExchangeDeclare(EXCHANGE_NAME, ExchangeType.Direct, true, false, null);
        QueueDeclareOk queueDeclareOK = channel.QueueDeclare(queue: queueName, durable: true, exclusive: false, autoDelete: true, arguments: null);
        channel.QueueBind(queue: queueName, exchange: EXCHANGE_NAME, routingKey: routingkey);

        Console.WriteLine(queueDeclareOK.MessageCount.ToString());

        BasicGetResult result = channel.BasicGet(queueName, false);
        byte[] body = result.Body;
        string message = Encoding.UTF8.GetString(body);
        if (ProcessData(message))
            channel.BasicAck(result.DeliveryTag, false);
        else
            channel.BasicNack(result.DeliveryTag, false, true);

        channel.Close(200, "goodbye");
        connection.Close();
        #endregion currentmethod
</code>```

What I would like to do is implement the publish-subscribe model as described https://www.rabbitmq.com/tutorials/tutorial-three-dotnet.html so that as messages enter the queue the subscriber processes them immediately. What I need to ensure is that if the message is not successfully processed it remains in the queue and is not lost.

Here is code basically along these lines:

```<code>        #region subscribeModel
        using (connection = factory.CreateConnection())
        {
            using (channel = connection.CreateModel())
            {
                channel.ExchangeDeclare(EXCHANGE_NAME, ExchangeType.Direct, true, false, null);
                channel.QueueDeclare(queue: queueName, durable: true, exclusive: false, autoDelete: true, arguments: null);
                channel.QueueBind(queueName, EXCHANGE_NAME, routingKey);

                EventingBasicConsumer consumer = new EventingBasicConsumer(channel);
                consumer.Received += (o, e) =>
                    {
                        string data = Encoding.ASCII.GetString(e.Body);
                        Console.WriteLine(data);
                    };

                string consumerTag = channel.BasicConsume(queueName, false, consumer);

                Console.WriteLine("Listening, press ENTER to quit");
                Console.ReadLine();
            }
        }

        #endregion subscribeModel
</code>```

I have three difficulties with this.

After messages are read they are in the Unacked state but I need them to return to the Ready state. If they are successfully processed they should be Acked and leave the queue but if the processing fails they must remain in the queue.

I need to do something other than write the data to the console, but where do I put the Process code in this model?

When my code terminates in the subscription model, the queue that I have connected to is deleted, losing any messages that are in it in any state.

Does anyone know how I can requeue un-processed messages and prevent the queue from being deleted if my consumer closes?

答:
I've not had a chance to look at this much over the last week, but did some more research today and I think I can answer my own problem now, hopefully helping others along the way.

It doesn't make sense to return messages to the Ready state when using a subscription model, as this will block the rest of the queue. The subscriber will keep trying to process the unacked message until it is removed from the queue. From : https://www.rabbitmq.com/confirms.html

Positive acknowledgements simply instruct RabbitMQ to record a message
  as delivered. Negative acknowledgements with basic.reject have the
  same effect. The difference is primarily in the semantics: positive
  acknowledgements assume a message was successfully processed while
  their negative counterpart suggests that a delivery wasn't processed
  but still should be deleted.

I can achieve what I need to do by sending defective messages to a new queue, where they can be processed differently to account for whatever it is that makes them defective, like so:

```<code>            using (channel)
            {

                EventingBasicConsumer consumer = new EventingBasicConsumer(channel);
                consumer.Received += (o, e) =>
                {
                    string data = Encoding.ASCII.GetString(e.Body);
                    result = MQ.utilities.Utilities.ProcessData(data, counter);
                    if (result)
                        channel.BasicAck(e.DeliveryTag, false);
                    else
                    {
                        channel.BasicNack(e.DeliveryTag, false, false);
                        //send message to another queue ...
                        IBasicProperties basicProperties = channel.CreateBasicProperties();
                        channel.BasicPublish(_exchangeName, "newqueue", basicProperties, e.Body);
                    }
                };

                string consumerTag = channel.BasicConsume(_publishSubscribeQueueOne, false, consumer);

                Console.WriteLine("Listening, press ENTER to quit");
                Console.ReadLine();
            }
</code>```

The procesdata method(s) can occur on event Received within the Consumer.

This is because the queue is declared as autodelete. If it is not set to autodelete the queue remains, unacked messages are returned to the Ready state when the consumer terminates.

Body:
I have a Windows service that consumes messages from a remotely hosted RabbitMQ queue.

I have working code that wakes up at fixed intervals and connects to the queue and takes messages and processes them (mostly persists them to a database). This is a simplified version of what works for me:

        #region currentmethod

        IConnection connection = factory.CreateConnection();
        IModel channel = connection.CreateModel();
        channel.ExchangeDeclare(EXCHANGE_NAME, ExchangeType.Direct, true, false, null);
        QueueDeclareOk queueDeclareOK = channel.QueueDeclare(queue: queueName, durable: true, exclusive: false, autoDelete: true, arguments: null);
        channel.QueueBind(queue: queueName, exchange: EXCHANGE_NAME, routingKey: routingkey);

        Console.WriteLine(queueDeclareOK.MessageCount.ToString());

        BasicGetResult result = channel.BasicGet(queueName, false);
        byte[] body = result.Body;
        string message = Encoding.UTF8.GetString(body);
        if (ProcessData(message))
            channel.BasicAck(result.DeliveryTag, false);
        else
            channel.BasicNack(result.DeliveryTag, false, true);

        channel.Close(200, "goodbye");
        connection.Close();
        #endregion currentmethod

What I would like to do is implement the publish-subscribe model as described https://www.rabbitmq.com/tutorials/tutorial-three-dotnet.html so that as messages enter the queue the subscriber processes them immediately. What I need to ensure is that if the message is not successfully processed it remains in the queue and is not lost.

Here is code basically along these lines:

        #region subscribeModel
        using (connection = factory.CreateConnection())
        {
            using (channel = connection.CreateModel())
            {
                channel.ExchangeDeclare(EXCHANGE_NAME, ExchangeType.Direct, true, false, null);
                channel.QueueDeclare(queue: queueName, durable: true, exclusive: false, autoDelete: true, arguments: null);
                channel.QueueBind(queueName, EXCHANGE_NAME, routingKey);

                EventingBasicConsumer consumer = new EventingBasicConsumer(channel);
                consumer.Received += (o, e) =>
                    {
                        string data = Encoding.ASCII.GetString(e.Body);
                        Console.WriteLine(data);
                    };

                string consumerTag = channel.BasicConsume(queueName, false, consumer);

                Console.WriteLine("Listening, press ENTER to quit");
                Console.ReadLine();
            }
        }

        #endregion subscribeModel

I have three difficulties with this.

After messages are read they are in the Unacked state but I need them to return to the Ready state. If they are successfully processed they should be Acked and leave the queue but if the processing fails they must remain in the queue.

I need to do something other than write the data to the console, but where do I put the Process code in this model?

When my code terminates in the subscription model, the queue that I have connected to is deleted, losing any messages that are in it in any state.

Does anyone know how I can requeue un-processed messages and prevent the queue from being deleted if my consumer closes?

Body:
I've not had a chance to look at this much over the last week, but did some more research today and I think I can answer my own problem now, hopefully helping others along the way.

It doesn't make sense to return messages to the Ready state when using a subscription model, as this will block the rest of the queue. The subscriber will keep trying to process the unacked message until it is removed from the queue. From : https://www.rabbitmq.com/confirms.html

Positive acknowledgements simply instruct RabbitMQ to record a message
  as delivered. Negative acknowledgements with basic.reject have the
  same effect. The difference is primarily in the semantics: positive
  acknowledgements assume a message was successfully processed while
  their negative counterpart suggests that a delivery wasn't processed
  but still should be deleted.

I can achieve what I need to do by sending defective messages to a new queue, where they can be processed differently to account for whatever it is that makes them defective, like so:

            using (channel)
            {

                EventingBasicConsumer consumer = new EventingBasicConsumer(channel);
                consumer.Received += (o, e) =>
                {
                    string data = Encoding.ASCII.GetString(e.Body);
                    result = MQ.utilities.Utilities.ProcessData(data, counter);
                    if (result)
                        channel.BasicAck(e.DeliveryTag, false);
                    else
                    {
                        channel.BasicNack(e.DeliveryTag, false, false);
                        //send message to another queue ...
                        IBasicProperties basicProperties = channel.CreateBasicProperties();
                        channel.BasicPublish(_exchangeName, "newqueue", basicProperties, e.Body);
                    }
                };

                string consumerTag = channel.BasicConsume(_publishSubscribeQueueOne, false, consumer);

                Console.WriteLine("Listening, press ENTER to quit");
                Console.ReadLine();
            }

The procesdata method(s) can occur on event Received within the Consumer.

This is because the queue is declared as autodelete. If it is not set to autodelete the queue remains, unacked messages are returned to the Ready state when the consumer terminates.


问:
Acquiring data from another JS file
I'm making a Discord Bot and I have all of the code in one file. I want to separate all this into multiple files. For example, I could have

index.js which has all my requires (var fs = require('fs') etc).

message.js which holds all message events.
etc etc.

How would I reference each file in the index.js file?

答:
```<code>//message.js
module.exports={
  'somedata':'here are the message',
 ...
}
//index.js
var message = require('index.js');
console.log(message.somedata);//shows here are the message
</code>```

Title: Acquiring data from another JS file


问:
TextBox TextChanged event on programmatic versus user change of text contents
I would like to differentiate between changing the text programmatically
 (for example in a button click handler event)  and user input (typing,
cutting and pasting text).

Is it possible?

答:
Thanks to Tim for pointing in the right direction, but for my needs, the check for the IsFocus worked like a charm. It's so simple....</p>

```<code> if (_queryField.IsKeyboardFocused && _queryField.IsKeyboardFocusWithin)
 {
     //do your things
 }
 else
 {
     //whatever
 }
</code>```

Body:
Thanks to Tim for pointing in the right direction, but for my needs, the check for the IsFocus worked like a charm. It's so simple....

 if (_queryField.IsKeyboardFocused && _queryField.IsKeyboardFocusWithin)
 {
     //do your things
 }
 else
 {
     //whatever
 }


问:
Loading jQuery plugins with webpack 2
After spending most of the day googling and trying - i did not get it to work and at this point i'm not sure what's missing.

I already have jQuery working (and verified it works) in webpack.common.js:

```<code>new ProvidePlugin({
        jQuery: 'jquery',
        $: 'jquery',
        jquery: 'jquery'
    })
</code>```

For example i have a "MetisMenu" plugin, where should i configure it?

I tried various combinations of require/include in my app.module.ts.

Like (including assigning them to a constant/var but import/require always give this error):

```<code>import 'metismenu';
jQuery(...).metisMenu is not a function

import { metisMenu } from 'metismenu';
Cannot assign to read only property 'exports' of object '#<Object>'

require ('metismenu');
Cannot assign to read only property 'exports' of object '#<Object>'

import * as jQuery from 'jquery';
import "metismenu";
Cannot assign to read only property 'exports' of object '#<Object>'
</code>```

答:
I was faced to the same problem. I can't bundle Jquery and external plugin with webpack 2.

So I "solved" partially using externals options of webpack.

I Link CDN library (jquery and other jquery plugin).

```<code><script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.9/semantic.min.js" crossorigin="anonymous"></script>
</code>```

I specify "externals" option on my webpack.config

```<code>externals: {
    jquery: 'jQuery'
}
</code>```

And add the ProvidePlugin

```<code>new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery' })
</code>```

In the app file, I import jquery and use the plugin like this

```<code> import * as $ from 'jquery';
 $('.accordion').accordion();
</code>```

I appreciate if someone can tell me how to bundle jQuery with Webpack 2

Title: Loading jQuery plugins with webpack 2

Body:
After spending most of the day googling and trying - i did not get it to work and at this point i'm not sure what's missing.

I already have jQuery working (and verified it works) in webpack.common.js:

new ProvidePlugin({
        jQuery: 'jquery',
        $: 'jquery',
        jquery: 'jquery'
    })

For example i have a "MetisMenu" plugin, where should i configure it?

I tried various combinations of require/include in my app.module.ts.

Like (including assigning them to a constant/var but import/require always give this error):

import 'metismenu';
jQuery(...).metisMenu is not a function

import { metisMenu } from 'metismenu';
Cannot assign to read only property 'exports' of object '#<Object>'

require ('metismenu');
Cannot assign to read only property 'exports' of object '#<Object>'

import * as jQuery from 'jquery';
import "metismenu";
Cannot assign to read only property 'exports' of object '#<Object>'

Body:
I was faced to the same problem. I can't bundle Jquery and external plugin with webpack 2.

So I "solved" partially using externals options of webpack.

I Link CDN library (jquery and other jquery plugin).

<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.9/semantic.min.js" crossorigin="anonymous"></script>

I specify "externals" option on my webpack.config

externals: {
    jquery: 'jQuery'
}

And add the ProvidePlugin

new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery' })

In the app file, I import jquery and use the plugin like this

 import * as $ from 'jquery';
 $('.accordion').accordion();

I appreciate if someone can tell me how to bundle jQuery with Webpack 2


问:
A case insensitive string class in python
I need to perform case insensitive string comparisons in python in sets and dictionary keys. Now, to create sets and dict subclasses that are case insensitive proves surprisingly tricky (see: Case insensitive dictionary for ideas, note they all use lower - hey there's even a rejected PEP, albeit its scope is a bit broader). So I went with creating a case insensitive string class (leveraging this answer by @AlexMartelli):

```<code>class CIstr(unicode):
    """Case insensitive with respect to hashes and comparisons string class"""

    #--Hash/Compare
    def __hash__(self):
        return hash(self.lower())
    def __eq__(self, other):
        if isinstance(other, basestring):
            return self.lower() == other.lower()
        return NotImplemented
    def __ne__(self, other): return not (self == other)
    def __lt__(self, other):
        if isinstance(other, basestring):
            return self.lower() < other.lower()
        return NotImplemented
    def __ge__(self, other): return not (self < other)
    def __gt__(self, other):
        if isinstance(other, basestring):
            return self.lower() > other.lower()
        return NotImplemented
    def __le__(self, other): return not (self > other)
</code>```

I am fully aware that lower is not really enough to cover all cases of string comparisons in unicode but I am refactoring existing code that used a much clunkier class for string comparisons (memory and speed wise) which anyway used lower() - so I can amend this on a later stage - plus I am on python 2 (as seen by unicode). My questions are:

did I get the operators right ?

is this class enough for my purposes, given that I take care to construct keys in dicts and set elements as CIstr instances - my purposes being checking equality, containment, set differences and similar operations in a case insensitive way. Or am I missing something ?

is it worth it to cache the lower case version of the string (as seen for instance in this ancient python recipe: Case Insensitive Strings). This comment suggests that not - plus I want to have construction as fast as possible and size as small as possible but people seem to include this.

Python 3 compatibility tips are appreciated !

Tiny demo:

```<code>d = {CIstr('A'): 1, CIstr('B'): 2}
print 'a' in d # True
s = set(d)
print {'a'} - s # set([])
</code>```

答:
In your demo you are using 'a' to look stuff up in your set. It wouldn't work if you tried to use 'A', because 'A' has a different hash. Also 'A' in d.keys() would be true, but 'A' in d would be false. You've essentially created a type that violates the normal contract of all hashes, by claiming to be equal to objects that have different hashes.

You could combine this answer with the answers about creating specialised dicts, and have a dict that converted any possible key into CIstr before trying to look it up. Then all your CIstr conversions could be hidden away inside the dictionary class.

E.g.

```<code>class CaseInsensitiveDict(dict):
    def __setitem__(self, key, value):
        super(CaseInsensitiveDict, self).__setitem__(convert_to_cistr(key), value)
    def __getitem__(self, key):
        return super(CaseInsensitiveDict, self).__getitem__(convert_to_cistr(key))
    # __init__, __contains__ etc.
</code>```

(Based on https://stackoverflow.com/a/2082169/3890632)

Body:
I need to perform case insensitive string comparisons in python in sets and dictionary keys. Now, to create sets and dict subclasses that are case insensitive proves surprisingly tricky (see: Case insensitive dictionary for ideas, note they all use lower - hey there's even a rejected PEP, albeit its scope is a bit broader). So I went with creating a case insensitive string class (leveraging this answer by @AlexMartelli):

class CIstr(unicode):
    """Case insensitive with respect to hashes and comparisons string class"""

    #--Hash/Compare
    def __hash__(self):
        return hash(self.lower())
    def __eq__(self, other):
        if isinstance(other, basestring):
            return self.lower() == other.lower()
        return NotImplemented
    def __ne__(self, other): return not (self == other)
    def __lt__(self, other):
        if isinstance(other, basestring):
            return self.lower() < other.lower()
        return NotImplemented
    def __ge__(self, other): return not (self < other)
    def __gt__(self, other):
        if isinstance(other, basestring):
            return self.lower() > other.lower()
        return NotImplemented
    def __le__(self, other): return not (self > other)

I am fully aware that lower is not really enough to cover all cases of string comparisons in unicode but I am refactoring existing code that used a much clunkier class for string comparisons (memory and speed wise) which anyway used lower() - so I can amend this on a later stage - plus I am on python 2 (as seen by unicode). My questions are:

did I get the operators right ?

is this class enough for my purposes, given that I take care to construct keys in dicts and set elements as CIstr instances - my purposes being checking equality, containment, set differences and similar operations in a case insensitive way. Or am I missing something ?

is it worth it to cache the lower case version of the string (as seen for instance in this ancient python recipe: Case Insensitive Strings). This comment suggests that not - plus I want to have construction as fast as possible and size as small as possible but people seem to include this.

Python 3 compatibility tips are appreciated !

Tiny demo:

d = {CIstr('A'): 1, CIstr('B'): 2}
print 'a' in d # True
s = set(d)
print {'a'} - s # set([])

Body:
In your demo you are using 'a' to look stuff up in your set. It wouldn't work if you tried to use 'A', because 'A' has a different hash. Also 'A' in d.keys() would be true, but 'A' in d would be false. You've essentially created a type that violates the normal contract of all hashes, by claiming to be equal to objects that have different hashes.

You could combine this answer with the answers about creating specialised dicts, and have a dict that converted any possible key into CIstr before trying to look it up. Then all your CIstr conversions could be hidden away inside the dictionary class.

E.g.

class CaseInsensitiveDict(dict):
    def __setitem__(self, key, value):
        super(CaseInsensitiveDict, self).__setitem__(convert_to_cistr(key), value)
    def __getitem__(self, key):
        return super(CaseInsensitiveDict, self).__getitem__(convert_to_cistr(key))
    # __init__, __contains__ etc.

(Based on https://stackoverflow.com/a/2082169/3890632)


问:
C# Use an array to blacklist what someone has input
```<code>        string name;
        string[] Blacklist;
        Blacklist = new string[10];

        Blacklist[1] = "Example1";
        Blacklist[2] = "Example2";
        Blacklist[3] = "Example3";
        Blacklist[4] = "Example4";
        Blacklist[5] = "Example5";
        Blacklist[6] = "Example6";
        Blacklist[7] = "Example7";
        Blacklist[8] = "Example8";
        Blacklist[9] = "Example9";
        Blacklist[10] = "Example10";

        Console.WriteLine("Enter your name:");
        name = Console.ReadLine();
        if (name = Blacklist[])
                            ^^
</code>```

<p>This is where I'm stuck
I want to make the name blacklisted to all the values in the array
So I can use this to filter all the names that are inappropriate </p>

答:
```<code>if (Blacklist.Any(x => x.Equals(name, StringComparison.CurrentCultureIgnoreCase)))
{
    // ...
}
</code>```

Also, your variable is not named per the convention, i.e. lower camel case.  It should be blacklist.

Body:
        string name;
        string[] Blacklist;
        Blacklist = new string[10];

        Blacklist[1] = "Example1";
        Blacklist[2] = "Example2";
        Blacklist[3] = "Example3";
        Blacklist[4] = "Example4";
        Blacklist[5] = "Example5";
        Blacklist[6] = "Example6";
        Blacklist[7] = "Example7";
        Blacklist[8] = "Example8";
        Blacklist[9] = "Example9";
        Blacklist[10] = "Example10";

        Console.WriteLine("Enter your name:");
        name = Console.ReadLine();
        if (name = Blacklist[])
                            ^^

This is where I'm stuck
I want to make the name blacklisted to all the values in the array
So I can use this to filter all the names that are inappropriate

Body:
if (Blacklist.Any(x => x.Equals(name, StringComparison.CurrentCultureIgnoreCase)))
{
    // ...
}

Also, your variable is not named per the convention, i.e. lower camel case.  It should be blacklist.


问:
Android BluetoothSocket outputstream writes too slow
Basically, I've been working on a wireless mouse that utilizes bluetooth OR wifi. I've gotten everything working including reading and writing messages. However, the rate at which data transfers through bluetooth is too slow to compensate. I've looked all over the place and I can't figure out what is causing this speed. I am using a dedicated thread to do all the writing operations on.

Here is my ConnectedThread code (almost exactly like in the Android SDK example)

```<code>package com.tutorials.jurko.androidmouse;

import android.bluetooth.BluetoothSocket;
import android.net.ConnectivityManager;

import java.io.BufferedOutputStream;
import java.io.IOError;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * Created by Jurko on 14/02/2015.
 */
public class ConnectedThread extends Thread {
    private final BluetoothSocket mmSocket;
    private final InputStream mmInStream;
    private final BufferedOutputStream mmOutStream;
    public static int count = 0;

    public ConnectedThread(BluetoothSocket socket) {
        mmSocket = socket;
        InputStream tmpIn = null;
        OutputStream tmpOut = null;

        try {
            tmpIn = mmSocket.getInputStream();
            tmpOut = mmSocket.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }

        mmInStream = tmpIn;
        mmOutStream = new BufferedOutputStream(tmpOut);
    }

    public void write(Byte[] bytes) {
        count++;
        try {
            byte x = bytes[0].byteValue();
            byte y = bytes[1].byteValue();
            System.out.println("Count: " + count);
            byte buf[] = {x, y};
            mmOutStream.write(buf);
            mmOutStream.flush();

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

Here is my server code (Receiving messages)

```<code>import javax.bluetooth.LocalDevice;
import javax.bluetooth.RemoteDevice;
import javax.bluetooth.UUID;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
import javax.microedition.io.StreamConnectionNotifier;
import java.awt.*;
import java.awt.event.InputEvent;
import java.io.*;

/**
 * Class that implements an SPP Server which accepts single line of
 * message from an SPP client and sends a single line of response to the client.
 */
public class SimpleSPPServer  {

    //start server
    private void startServer() throws IOException, AWTException {
        Robot r = new Robot();
        //Create a UUID for SPP
        UUID uuid = new UUID("1101", true);
        //Create the servicve url
        String connectionString = "btspp://localhost:" + uuid +";name=Sample SPP Server";

        //open server url
        StreamConnectionNotifier streamConnNotifier = (StreamConnectionNotifier)Connector.open( connectionString );

        //Wait for client connection
        System.out.println("\nServer Started. Waiting for clients to connect...");

        StreamConnection connection=streamConnNotifier.acceptAndOpen();

        RemoteDevice dev = RemoteDevice.getRemoteDevice(connection);
        System.out.println("Remote device address: "+dev.getBluetoothAddress());
        System.out.println("Remote device name: "+dev.getFriendlyName(true));

        //read string from spp client
        InputStream inStream=connection.openInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(inStream));
        byte[] lineRead = new byte[2];

        while(inStream.read(lineRead) != -1)  {
            System.out.println(lineRead[0] + " " + lineRead[1]);
// Code to control mouse here

        }

        //send response to spp client
        OutputStream outStream=connection.openOutputStream();
        PrintWriter pWriter=new PrintWriter(new OutputStreamWriter(outStream));
        pWriter.write("Response String from SPP Server\r\n");
        pWriter.flush();

        pWriter.close();
        streamConnNotifier.close();

    }

    public static void main(String[] args) throws IOException, AWTException {

        //display local device address and name
        LocalDevice localDevice = LocalDevice.getLocalDevice();
        System.out.println("Address: "+localDevice.getBluetoothAddress());
        System.out.println("Name: "+localDevice.getFriendlyName());

        SimpleSPPServer sampleSPPServer=new SimpleSPPServer();
        sampleSPPServer.startServer();

    }
}
</code>```

答:
Someone asked for an answer, so here it is. Out of complete coincidence (and boredom I guess), I decided to fix ALL of the warnings Android Studio was giving me.

One of the warnings indicated that I was instantiating new objects in the onDraw function. Turns out that the bluetooth was not slow, but in fact the onDraw took so long it delayed the transmission of new messages, making it appear as if a consistent lag was present.

tl;dr: Don't instantiate new objects in your onDraw function.

Body:
Basically, I've been working on a wireless mouse that utilizes bluetooth OR wifi. I've gotten everything working including reading and writing messages. However, the rate at which data transfers through bluetooth is too slow to compensate. I've looked all over the place and I can't figure out what is causing this speed. I am using a dedicated thread to do all the writing operations on.

Here is my ConnectedThread code (almost exactly like in the Android SDK example)

package com.tutorials.jurko.androidmouse;

import android.bluetooth.BluetoothSocket;
import android.net.ConnectivityManager;

import java.io.BufferedOutputStream;
import java.io.IOError;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * Created by Jurko on 14/02/2015.
 */
public class ConnectedThread extends Thread {
    private final BluetoothSocket mmSocket;
    private final InputStream mmInStream;
    private final BufferedOutputStream mmOutStream;
    public static int count = 0;

    public ConnectedThread(BluetoothSocket socket) {
        mmSocket = socket;
        InputStream tmpIn = null;
        OutputStream tmpOut = null;

        try {
            tmpIn = mmSocket.getInputStream();
            tmpOut = mmSocket.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }

        mmInStream = tmpIn;
        mmOutStream = new BufferedOutputStream(tmpOut);
    }

    public void write(Byte[] bytes) {
        count++;
        try {
            byte x = bytes[0].byteValue();
            byte y = bytes[1].byteValue();
            System.out.println("Count: " + count);
            byte buf[] = {x, y};
            mmOutStream.write(buf);
            mmOutStream.flush();

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

Here is my server code (Receiving messages)

import javax.bluetooth.LocalDevice;
import javax.bluetooth.RemoteDevice;
import javax.bluetooth.UUID;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
import javax.microedition.io.StreamConnectionNotifier;
import java.awt.*;
import java.awt.event.InputEvent;
import java.io.*;

/**
 * Class that implements an SPP Server which accepts single line of
 * message from an SPP client and sends a single line of response to the client.
 */
public class SimpleSPPServer  {

    //start server
    private void startServer() throws IOException, AWTException {
        Robot r = new Robot();
        //Create a UUID for SPP
        UUID uuid = new UUID("1101", true);
        //Create the servicve url
        String connectionString = "btspp://localhost:" + uuid +";name=Sample SPP Server";

        //open server url
        StreamConnectionNotifier streamConnNotifier = (StreamConnectionNotifier)Connector.open( connectionString );

        //Wait for client connection
        System.out.println("\nServer Started. Waiting for clients to connect...");

        StreamConnection connection=streamConnNotifier.acceptAndOpen();

        RemoteDevice dev = RemoteDevice.getRemoteDevice(connection);
        System.out.println("Remote device address: "+dev.getBluetoothAddress());
        System.out.println("Remote device name: "+dev.getFriendlyName(true));

        //read string from spp client
        InputStream inStream=connection.openInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(inStream));
        byte[] lineRead = new byte[2];

        while(inStream.read(lineRead) != -1)  {
            System.out.println(lineRead[0] + " " + lineRead[1]);
// Code to control mouse here

        }

        //send response to spp client
        OutputStream outStream=connection.openOutputStream();
        PrintWriter pWriter=new PrintWriter(new OutputStreamWriter(outStream));
        pWriter.write("Response String from SPP Server\r\n");
        pWriter.flush();

        pWriter.close();
        streamConnNotifier.close();

    }

    public static void main(String[] args) throws IOException, AWTException {

        //display local device address and name
        LocalDevice localDevice = LocalDevice.getLocalDevice();
        System.out.println("Address: "+localDevice.getBluetoothAddress());
        System.out.println("Name: "+localDevice.getFriendlyName());

        SimpleSPPServer sampleSPPServer=new SimpleSPPServer();
        sampleSPPServer.startServer();

    }
}


问:
How to add comma separator to Venn diagram
In r is there a way to add the comma separator to thousands on a Venn diagram.

```<code>venn.plot <- VennDiagram::draw.pairwise.venn(10000, 7000, 3000, c("First", "Second"), scaled = FALSE)

grid::grid.draw(venn.plot)
</code>```

The resulting chart looks like the one below.

答:
You could also edit the items manually.

```<code>venn.plot[[5]][["label"]] <- "7,000"
venn.plot[[6]][["label"]] <- "4,000"
venn.plot[[7]][["label"]] <- "3,000"

grid::grid.draw(venn.plot)
</code>```

Body:
In r is there a way to add the comma separator to thousands on a Venn diagram.

venn.plot <- VennDiagram::draw.pairwise.venn(10000, 7000, 3000, c("First", "Second"), scaled = FALSE)

grid::grid.draw(venn.plot)

The resulting chart looks like the one below.

Body:
You could also edit the items manually.

venn.plot[[5]][["label"]] <- "7,000"
venn.plot[[6]][["label"]] <- "4,000"
venn.plot[[7]][["label"]] <- "3,000"

grid::grid.draw(venn.plot)


问:
visual basic 2015: how to change text of a dynamically created label with a button click event
I have a dynamically created tabpage where I have placed dynamically created a button and label. I'm trying to figure out how to change the label.text with the button.click event. Everything works correctly until I add in the With/End With to change the label text in the button click subroutine. This is my first try at dynamically programming (hobby of mine, so trying to learn), but I do have a specific end goal for this application. Any thoughts on how to fix this problem? </p>

```<code>Private Sub initialize_Button()
    Dim button_Mybutton As New Button
    With button_Mybutton
        .Name = "button_My_Button"
        .AutoSize = True
        .Text = "Calculate"
        .Visible = True
        .Top = 200
        .Left = 10
    End With
    AddHandler button_Mybutton.Click, AddressOf Me.button_Click
    Me.Controls.Add(button_Mybutton)
End Sub

Protected Sub button_Click(ByVal sender As Object, ByVal e As EventArgs)
    MsgBox("Button Clicked")
    With label_Test
        .text = "Test Confirmed"
    End With
End Sub

Private Sub label_Test_Output()
    Dim label_Test As New Label
    With label_Test
        .Name = "label_Test"
        .Top = 200
        .Left = 100
        .AutoSize = True
        .Text = "Label Test"
        .Visible = True
    End With
    Me.Controls.Add(label_Test)
End Sub
</code>```

答:
Move the declaration of the controls outside the methods, to the class level. Then you can access them from anywhere in the class.

```<code>Private button_Mybutton As Button
Private label_Test As Label

Private Sub initialize_Button()
    button_Mybutton = New Button()
    With button_Mybutton
        .Name = "button_My_Button"
        .AutoSize = True
        .Text = "Calculate"
        .Visible = True
        .Top = 200
        .Left = 10
    End With
    AddHandler button_Mybutton.Click, AddressOf Me.button_Click
    Me.Controls.Add(button_Mybutton)
End Sub

Protected Sub button_Click(ByVal sender As Object, ByVal e As EventArgs)
    MsgBox("Button Clicked")
    If label_Test IsNot Nothing Then
        With label_Test
            .text = "Test Confirmed"
        End With
    End If
End Sub

Private Sub label_Test_Output()
    label_Test = New Label()
    With label_Test
        .Name = "label_Test"
        .Top = 200
        .Left = 100
        .AutoSize = True
        .Text = "Label Test"
        .Visible = True
    End With
    Me.Controls.Add(label_Test)
End Sub
</code>```

You should also check if the label is created when accessing it, since there is a possibility that you can click the button before calling label_Test_Output. Added null check to handler.

Body:
I have a dynamically created tabpage where I have placed dynamically created a button and label. I'm trying to figure out how to change the label.text with the button.click event. Everything works correctly until I add in the With/End With to change the label text in the button click subroutine. This is my first try at dynamically programming (hobby of mine, so trying to learn), but I do have a specific end goal for this application. Any thoughts on how to fix this problem?

Private Sub initialize_Button()
    Dim button_Mybutton As New Button
    With button_Mybutton
        .Name = "button_My_Button"
        .AutoSize = True
        .Text = "Calculate"
        .Visible = True
        .Top = 200
        .Left = 10
    End With
    AddHandler button_Mybutton.Click, AddressOf Me.button_Click
    Me.Controls.Add(button_Mybutton)
End Sub

Protected Sub button_Click(ByVal sender As Object, ByVal e As EventArgs)
    MsgBox("Button Clicked")
    With label_Test
        .text = "Test Confirmed"
    End With
End Sub

Private Sub label_Test_Output()
    Dim label_Test As New Label
    With label_Test
        .Name = "label_Test"
        .Top = 200
        .Left = 100
        .AutoSize = True
        .Text = "Label Test"
        .Visible = True
    End With
    Me.Controls.Add(label_Test)
End Sub

Body:
Move the declaration of the controls outside the methods, to the class level. Then you can access them from anywhere in the class.

Private button_Mybutton As Button
Private label_Test As Label

Private Sub initialize_Button()
    button_Mybutton = New Button()
    With button_Mybutton
        .Name = "button_My_Button"
        .AutoSize = True
        .Text = "Calculate"
        .Visible = True
        .Top = 200
        .Left = 10
    End With
    AddHandler button_Mybutton.Click, AddressOf Me.button_Click
    Me.Controls.Add(button_Mybutton)
End Sub

Protected Sub button_Click(ByVal sender As Object, ByVal e As EventArgs)
    MsgBox("Button Clicked")
    If label_Test IsNot Nothing Then
        With label_Test
            .text = "Test Confirmed"
        End With
    End If
End Sub

Private Sub label_Test_Output()
    label_Test = New Label()
    With label_Test
        .Name = "label_Test"
        .Top = 200
        .Left = 100
        .AutoSize = True
        .Text = "Label Test"
        .Visible = True
    End With
    Me.Controls.Add(label_Test)
End Sub

You should also check if the label is created when accessing it, since there is a possibility that you can click the button before calling label_Test_Output. Added null check to handler.


问:
Create new TAR file in current directory to a new directory without using "mv" (shell script)
I'm currently setting up a backupmanager to automatically archive directories from webserver. I'm searching for an answer how to create a new TAR file of the current directory to a new (different) directory without using mv after the archiving process. See my command:

```<code>dcreate=$(date +%Y_%d_%m) tar -cvpzf backup_$dcreate.tar.gz plugins/folder_to_archive/
</code>```

This command works fine, but i'm struggeling now on how to move it to a new directory directly after the archiv process is terminated, for example:

plugins/plugin_name/ to plugins/backups/

Any help appreciated.

Regards

答:
The -f option of tar is the destination file for the archive; it can be anywhere you want, i.e., you can change

-cvpzf "backup_$dcreate.tar.gz"

to

-cvpzf "plugins/backups/backup_$dcreate.tar.gz"

if you want your new archive to be created in plugins/backups/

Body:
I'm currently setting up a backupmanager to automatically archive directories from webserver. I'm searching for an answer how to create a new TAR file of the current directory to a new (different) directory without using mv after the archiving process. See my command:

dcreate=$(date +%Y_%d_%m) tar -cvpzf backup_$dcreate.tar.gz plugins/folder_to_archive/

This command works fine, but i'm struggeling now on how to move it to a new directory directly after the archiv process is terminated, for example:

plugins/plugin_name/ to plugins/backups/

Any help appreciated.

Regards


问:
How to have defaults for environment variables in PyCharm
I have set a default for environment variables under Run > Edit Configurations..., and still, when I make a new PyCharm project, that default is lost, and I have to set the environment variables again.

How can I set the environment variables in such a way that they affect any new PyCharm project I make?

Thanks!

答: The defaults you are editing affect only new Run configurations for the project you presently have open.  I'm not sure that you can change the defaults for new projects.  If it's even possible, I suspect you'll need to "look under the hood" in your $HOME/.PyCharm*/config/ directory.


问:
Where to capture the $location.search() vars in the run statement? In order to rebuild the state

Goal / Expected

Rebuild the state of the app if the user directly goes to a link like this: http://localhost:8080/app/#!/tag_id=5&ticker=GOOG

Results

The app currently still redirects back to /login via $urlRouterProvider.otherwise('/login');

In my app I am storing the $state (ui-router) variables in a cookie using ngCookies.

```<code>$rootScope.$on('$stateChangeSuccess',
function(event, toState, toParams, fromState, fromParams) {
    const shareUrl = () => {
        // const base = 'https://www.tickertags.com/dashboard/#/';
        const base = 'http://localhost:8080/app/#!/';
        const cookie = $cookies.get('stateCookie');
        console.log('state vars', $httpParamSerializer(JSON.parse(cookie)));
        const parsedState = $httpParamSerializer(JSON.parse(cookie));
        return `${base}${parsedState}`;
    };
    // console.log('state.current.name', $state.current.name)
    const stateCookie = $cookies.get('stateCookie');
    $cookies.putObject('stateCookie', $state.params);
    console.log('shareUrl', shareUrl());
})
</code>```

When changing states:

The log 'state var' will log: state vars tag_id=5&ticker=GOOG

And the log 'shareUrl' will log: http://localhost:8080/app/#!/tag_id=5&ticker=GOOG

I'm trying to just print the $location.search() results of that link first. Below I put a new log in the $stateChangeStart eventListener.

```<code>.run(['$rootScope', '$location', '$state', '$cookies', '$httpParamSerializer',
function($rootScope, $location, $state, $cookies, $httpParamSerializer) {

    $rootScope.$on("$stateChangeError", console.log.bind(console));
    $rootScope.$on('$stateChangeStart',
    function(event, toState, toParams, fromState, fromParams, options) {
        const searchObject = $location.search();
        console.log('searchObject', searchObject);
    });
</code>```

Results

I got redirected back to the login, which is expected right now. However my searchObject is still empty?

Note I also put a break point on the first line inside of the .run. The debugger stopped there and I tried to log out $location.search() while the URL was correct, but it still printed out an empty object...

When I just log out $location however I do see all of this:

Where to I placed that const searchObject = $location.search(); line so I can correctly capture the pasted URL, then created new params to run a $state.go on to rebuild the state?

答:
Just figured it out!

I needed to add ? after dashboard:

const base = 'http://localhost:8080/app/#!/dashboard?';

And now it will work:

Body:
Goal / Expected

Rebuild the state of the app if the user directly goes to a link like this: http://localhost:8080/app/#!/tag_id=5&ticker=GOOG

Results

The app currently still redirects back to /login via $urlRouterProvider.otherwise('/login');

In my app I am storing the $state (ui-router) variables in a cookie using ngCookies.

$rootScope.$on('$stateChangeSuccess',
function(event, toState, toParams, fromState, fromParams) {
    const shareUrl = () => {
        // const base = 'https://www.tickertags.com/dashboard/#/';
        const base = 'http://localhost:8080/app/#!/';
        const cookie = $cookies.get('stateCookie');
        console.log('state vars', $httpParamSerializer(JSON.parse(cookie)));
        const parsedState = $httpParamSerializer(JSON.parse(cookie));
        return `${base}${parsedState}`;
    };
    // console.log('state.current.name', $state.current.name)
    const stateCookie = $cookies.get('stateCookie');
    $cookies.putObject('stateCookie', $state.params);
    console.log('shareUrl', shareUrl());
})

When changing states:

The log 'state var' will log: state vars tag_id=5&ticker=GOOG

And the log 'shareUrl' will log: http://localhost:8080/app/#!/tag_id=5&ticker=GOOG

I'm trying to just print the $location.search() results of that link first. Below I put a new log in the $stateChangeStart eventListener.

.run(['$rootScope', '$location', '$state', '$cookies', '$httpParamSerializer',
function($rootScope, $location, $state, $cookies, $httpParamSerializer) {

    $rootScope.$on("$stateChangeError", console.log.bind(console));
    $rootScope.$on('$stateChangeStart',
    function(event, toState, toParams, fromState, fromParams, options) {
        const searchObject = $location.search();
        console.log('searchObject', searchObject);
    });

Results

I got redirected back to the login, which is expected right now. However my searchObject is still empty?

Note I also put a break point on the first line inside of the .run. The debugger stopped there and I tried to log out $location.search() while the URL was correct, but it still printed out an empty object...

When I just log out $location however I do see all of this:

Where to I placed that const searchObject = $location.search(); line so I can correctly capture the pasted URL, then created new params to run a $state.go on to rebuild the state?