问:
How to enable CORS in ASP.net Core WebAPI
What I am trying to do

I have a backend ASP.Net Core Web API hosted on an Azure Free Plan (Add default security headers in .Net Core).

I also have a Client Website which I want to make consume that API. The Client Application will not be hosted on Azure, but rather will be hosted on Github Pages or on another Web Hosting Service that I have access to. Because of this the domain names won't line up.

Looking into this, I need to enable CORS on the Web API side, however I have tried just about everything for several hours now and it is refusing to work.

How I have the Client Setup
Its just a simple client written in React.js. I'm calling the APIs through AJAX in Jquery. The React site works so I know its not that. The Jquery API call works as I confirmed in Attempt 1. Here is how I make the calls

```<code>    var apiUrl = "http://andrewgodfroyportfolioapi.azurewebsites.net/api/Authentication";
    //alert(username + "|" + password + "|" + apiUrl);
    $.ajax({
        url: apiUrl,
        type: "POST",
        data: {
            username: username,
            password: password
        },
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) {
            var authenticatedUser = JSON.parse(response);
            //alert("Data Loaded: " + authenticatedUser);
            if (onComplete != null) {
                onComplete(authenticatedUser);
            }
        },
        error: function (xhr, status, error) {
            //alert(xhr.responseText);
            if (onComplete != null) {
                onComplete(xhr.responseText);
            }
        }
    });
</code>```

What I have tried

Attempt 1 - The 'proper' way

https://learn.microsoft.com/en-us/aspnet/core/security/cors

I have followed this tutorial on the Microsoft Website to a T, trying all 3 options of enabling it Globally in the Startup.cs, Setting it up on every controller and Trying it on every Action.

Following this method, the Cross Domain works, but only on a single Action on a single controller (POST to the AccountController). For everything else, the Microsoft.AspNetCore.Cors middleware refuses to set the headers.

I installed Microsoft.AspNetCore.Cors through NUGET and the version is 1.1.2

Here is how I have it setup in Startup.cs

```<code>    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        // Add Cors
        services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
        {
            builder.AllowAnyOrigin()
                   .AllowAnyMethod()
                   .AllowAnyHeader();
        }));

        // Add framework services.
        services.AddMvc();
        services.Configure<MvcOptions>(options =>
        {
            options.Filters.Add(new CorsAuthorizationFilterFactory("MyPolicy"));
        });

        ...
        ...
        ...
    }

    // This method gets called by the runtime. Use this method to configure
    //the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env,
    ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        // Enable Cors
        app.UseCors("MyPolicy");

        //app.UseMvcWithDefaultRoute();
        app.UseMvc();

        ...
        ...
        ...
    }
</code>```

As you can see, I am doing everything as told. I add Cors before MVC both times, and when that didn't work I attempted putting [EnableCors("MyPolicy")] on every controller as so

```<code>[Route("api/[controller]")]
[EnableCors("MyPolicy")]
public class AdminController : Controller
</code>```

Attempt 2 - Brute Forcing it

https://andrewlock.net/adding-default-security-headers-in-asp-net-core/

After several hours of trying on the previous attempt, I figured I would try to bruteforce it by trying to set the headers manually, forcing them to run on every response. I did this following this tutorial on how to manually add headers to every response.

These are the headers I added

```<code>.AddCustomHeader("Access-Control-Allow-Origin", "*")
.AddCustomHeader("Access-Control-Allow-Methods", "*")
.AddCustomHeader("Access-Control-Allow-Headers", "*")
.AddCustomHeader("Access-Control-Max-Age", "86400")
</code>```

These are other headers I tried which failed

```<code>.AddCustomHeader("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE")
.AddCustomHeader("Access-Control-Allow-Headers", "content-type, accept, X-PINGOTHER")
.AddCustomHeader("Access-Control-Allow-Headers", "X-PINGOTHER, Host, User-Agent, Accept, Accept: application/json, application/json, Accept-Language, Accept-Encoding, Access-Control-Request-Method, Access-Control-Request-Headers, Origin, Connection, Content-Type, Content-Type: application/json, Authorization, Connection, Origin, Referer")
</code>```

With this method, the Cross Site headers are being properly applied and they show up in my developer console and in Postman. The problem however is that while it passes the Access-Control-Allow-Origin check, the webbrowser throws a hissy fit on (I believe) Access-Control-Allow-Headers stating 415 (Unsupported Media Type)

So the brute force method doesn't work either

Finally

Has anyone gotten this to work and could lend a hand, or just be able to point me in the right direction?

EDIT

So to get the API calls to go through, I had to stop using JQuery and switch to a Pure Javascript XMLHttpRequest format.

Attempt 1

I managed to get the Microsoft.AspNetCore.Cors to work by following MindingData's answer, except within the Configure Method putting the app.UseCors before app.UseMvc.

In addition, when mixed with the Javascript API Solution options.AllowAnyOrigin() for wildcard support began to work as well.

Attempt 2

So I have managed to get Attempt 2 (brute forcing it) to work... with the only exception that the Wildcard for Access-Control-Allow-Origin doesn't work and as such I have to manually set the domains that have access to it.

Its obviously not ideal since I just want this WebAPI to be wide opened to everyone, but it atleast works for me on a separate site, which means it's a start

```<code>app.UseSecurityHeadersMiddleware(new SecurityHeadersBuilder()
    .AddDefaultSecurePolicy()
    .AddCustomHeader("Access-Control-Allow-Origin", "http://localhost:3000")
    .AddCustomHeader("Access-Control-Allow-Methods", "OPTIONS, GET, POST, PUT, PATCH, DELETE")
    .AddCustomHeader("Access-Control-Allow-Headers", "X-PINGOTHER, Content-Type, Authorization"));
</code>```

答:
Because you have a very simple CORS policy (Allow all requests from XXX domain), you don't need to make it so complicated. Try doing the following first (A very basic implementation of CORS).

If you haven't already, install the CORS nuget package.

```<code>Install-Package Microsoft.AspNetCore.Cors
</code>```

In the ConfigureServices method of your startup.cs, add the CORS services.

```<code>public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(); // Make sure you call this previous to AddMvc
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
</code>```

Then in your Configure method of your startup.cs, add the following :

```<code>public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    // Make sure you call this before calling app.UseMvc()
    app.UseCors(
        options => options.WithOrigins("http://example.com").AllowAnyMethod()
    );

    app.UseMvc();
}
</code>```

Now give it a go. Policies are for when you want different policies for different actions (e.g. different hosts or different headers). For your simple example you really don't need it. Start with this simple example and tweak as you need to from there.

Further reading : http://dotnetcoretutorials.com/2017/01/03/enabling-cors-asp-net-core/

Body:
What I am trying to do

I have a backend ASP.Net Core Web API hosted on an Azure Free Plan (Add default security headers in .Net Core).

I also have a Client Website which I want to make consume that API. The Client Application will not be hosted on Azure, but rather will be hosted on Github Pages or on another Web Hosting Service that I have access to. Because of this the domain names won't line up.

Looking into this, I need to enable CORS on the Web API side, however I have tried just about everything for several hours now and it is refusing to work.

How I have the Client Setup
Its just a simple client written in React.js. I'm calling the APIs through AJAX in Jquery. The React site works so I know its not that. The Jquery API call works as I confirmed in Attempt 1. Here is how I make the calls

    var apiUrl = "http://andrewgodfroyportfolioapi.azurewebsites.net/api/Authentication";
    //alert(username + "|" + password + "|" + apiUrl);
    $.ajax({
        url: apiUrl,
        type: "POST",
        data: {
            username: username,
            password: password
        },
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) {
            var authenticatedUser = JSON.parse(response);
            //alert("Data Loaded: " + authenticatedUser);
            if (onComplete != null) {
                onComplete(authenticatedUser);
            }
        },
        error: function (xhr, status, error) {
            //alert(xhr.responseText);
            if (onComplete != null) {
                onComplete(xhr.responseText);
            }
        }
    });

What I have tried

Attempt 1 - The 'proper' way

https://learn.microsoft.com/en-us/aspnet/core/security/cors

I have followed this tutorial on the Microsoft Website to a T, trying all 3 options of enabling it Globally in the Startup.cs, Setting it up on every controller and Trying it on every Action.

Following this method, the Cross Domain works, but only on a single Action on a single controller (POST to the AccountController). For everything else, the Microsoft.AspNetCore.Cors middleware refuses to set the headers.

I installed Microsoft.AspNetCore.Cors through NUGET and the version is 1.1.2

Here is how I have it setup in Startup.cs

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        // Add Cors
        services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
        {
            builder.AllowAnyOrigin()
                   .AllowAnyMethod()
                   .AllowAnyHeader();
        }));

        // Add framework services.
        services.AddMvc();
        services.Configure<MvcOptions>(options =>
        {
            options.Filters.Add(new CorsAuthorizationFilterFactory("MyPolicy"));
        });

        ...
        ...
        ...
    }

    // This method gets called by the runtime. Use this method to configure
    //the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env,
    ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        // Enable Cors
        app.UseCors("MyPolicy");

        //app.UseMvcWithDefaultRoute();
        app.UseMvc();

        ...
        ...
        ...
    }

As you can see, I am doing everything as told. I add Cors before MVC both times, and when that didn't work I attempted putting [EnableCors("MyPolicy")] on every controller as so

[Route("api/[controller]")]
[EnableCors("MyPolicy")]
public class AdminController : Controller

Attempt 2 - Brute Forcing it

https://andrewlock.net/adding-default-security-headers-in-asp-net-core/

After several hours of trying on the previous attempt, I figured I would try to bruteforce it by trying to set the headers manually, forcing them to run on every response. I did this following this tutorial on how to manually add headers to every response.

These are the headers I added

.AddCustomHeader("Access-Control-Allow-Origin", "*")
.AddCustomHeader("Access-Control-Allow-Methods", "*")
.AddCustomHeader("Access-Control-Allow-Headers", "*")
.AddCustomHeader("Access-Control-Max-Age", "86400")

These are other headers I tried which failed

.AddCustomHeader("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE")
.AddCustomHeader("Access-Control-Allow-Headers", "content-type, accept, X-PINGOTHER")
.AddCustomHeader("Access-Control-Allow-Headers", "X-PINGOTHER, Host, User-Agent, Accept, Accept: application/json, application/json, Accept-Language, Accept-Encoding, Access-Control-Request-Method, Access-Control-Request-Headers, Origin, Connection, Content-Type, Content-Type: application/json, Authorization, Connection, Origin, Referer")

With this method, the Cross Site headers are being properly applied and they show up in my developer console and in Postman. The problem however is that while it passes the Access-Control-Allow-Origin check, the webbrowser throws a hissy fit on (I believe) Access-Control-Allow-Headers stating 415 (Unsupported Media Type)

So the brute force method doesn't work either

Finally

Has anyone gotten this to work and could lend a hand, or just be able to point me in the right direction?

EDIT

So to get the API calls to go through, I had to stop using JQuery and switch to a Pure Javascript XMLHttpRequest format.

Attempt 1

I managed to get the Microsoft.AspNetCore.Cors to work by following MindingData's answer, except within the Configure Method putting the app.UseCors before app.UseMvc.

In addition, when mixed with the Javascript API Solution options.AllowAnyOrigin() for wildcard support began to work as well.

Attempt 2

So I have managed to get Attempt 2 (brute forcing it) to work... with the only exception that the Wildcard for Access-Control-Allow-Origin doesn't work and as such I have to manually set the domains that have access to it.

Its obviously not ideal since I just want this WebAPI to be wide opened to everyone, but it atleast works for me on a separate site, which means it's a start

app.UseSecurityHeadersMiddleware(new SecurityHeadersBuilder()
    .AddDefaultSecurePolicy()
    .AddCustomHeader("Access-Control-Allow-Origin", "http://localhost:3000")
    .AddCustomHeader("Access-Control-Allow-Methods", "OPTIONS, GET, POST, PUT, PATCH, DELETE")
    .AddCustomHeader("Access-Control-Allow-Headers", "X-PINGOTHER, Content-Type, Authorization"));

Body:
Because you have a very simple CORS policy (Allow all requests from XXX domain), you don't need to make it so complicated. Try doing the following first (A very basic implementation of CORS).

If you haven't already, install the CORS nuget package.

Install-Package Microsoft.AspNetCore.Cors

In the ConfigureServices method of your startup.cs, add the CORS services.

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(); // Make sure you call this previous to AddMvc
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}

Then in your Configure method of your startup.cs, add the following :

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    // Make sure you call this before calling app.UseMvc()
    app.UseCors(
        options => options.WithOrigins("http://example.com").AllowAnyMethod()
    );

    app.UseMvc();
}

Now give it a go. Policies are for when you want different policies for different actions (e.g. different hosts or different headers). For your simple example you really don't need it. Start with this simple example and tweak as you need to from there.

Further reading : http://dotnetcoretutorials.com/2017/01/03/enabling-cors-asp-net-core/


来源: stackexchange

问:
Pandas: Pivot to True/False, drop column
I'm trying to create what I think is a simple pivot table but am having serious issues.  There are two things I'm unable to do:

Get rid of the "partner" column at the end.

Set the values to either True or False if each company has that partner.

Setup:

```<code>df = pd.DataFrame({'company':['a','b','c','b'], 'partner':['x','x','y','y'], 'str':['just','some','random','words']})
</code>```

Desired Output:

```<code>company     x      y
a        True  False
b        True   True
c       False   True
</code>```

I started with:

```<code>df = df.pivot(values = 'partner', columns = 'partner', index = 'company').reset_index()
</code>```

which gets me close, but when I try to get rid of the "partner" column, I can't even reference it, and it's not the "index".

For the second issue, I can use:

```<code>df.fillna(False, inplace = True)
df.loc[~(df['x'] == False), 'x'] = True
df.loc[~(df['y'] == False), 'y'] = True
</code>```

but that seems incredibly hacky.  Any help would be appreciated.

答:
Option 1

```<code>df.groupby(['company', 'partner']).size().unstack(fill_value=0).astype(bool)

partner      x      y
company
a         True  False
b         True   True
c        False   True
</code>```

Get rid of names on columns object

```<code>df.groupby(['company', 'partner']).size().unstack(fill_value=0).astype(bool) \
    .rename_axis(None, 1).reset_index()

  company      x      y
0       a   True  False
1       b   True   True
2       c  False   True
</code>```

Option 2

```<code>pd.crosstab(df.company, df.partner).astype(bool)

partner      x      y
company
a         True  False
b         True   True
c        False   True

pd.crosstab(df.company, df.partner).astype(bool) \
    .rename_axis(None, 1).reset_index()

  company      x      y
0       a   True  False
1       b   True   True
2       c  False   True
</code>```

Option 3

```<code>f1, u1 = pd.factorize(df.company.values)
f2, u2 = pd.factorize(df.partner.values)
n, m = u1.size, u2.size

b = np.bincount(f1 * m + f2)
pad = np.zeros(n * m - b.size, dtype=int)
b = np.append(b, pad)
v = b.reshape(n, m).astype(bool)

pd.DataFrame(np.column_stack([u1, v]), columns=np.append('company', u2))

  company      x      y
0       a   True  False
1       b   True   True
2       c  False   True
</code>```

Timing

small data

```<code>%timeit df.groupby(['company', 'partner']).size().unstack(fill_value=0).astype(bool).rename_axis(None, 1).reset_index()
%timeit pd.crosstab(df.company, df.partner).astype(bool).rename_axis(None, 1).reset_index()

%%timeit
f1, u1 = pd.factorize(df.company.values)
f2, u2 = pd.factorize(df.partner.values)
n, m = u1.size, u2.size

b = np.bincount(f1 * m + f2)
pad = np.zeros(n * m - b.size, dtype=int)
b = np.append(b, pad)
v = b.reshape(n, m).astype(bool)

pd.DataFrame(np.column_stack([u1, v]), columns=np.append('company', u2))

1000 loops, best of 3: 1.67 ms per loop
100 loops, best of 3: 5.97 ms per loop
1000 loops, best of 3: 301 µs per loop
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to create what I think is a simple pivot table but am having serious issues.  There are two things I'm unable to do:

Get rid of the "partner" column at the end.

Set the values to either True or False if each company has that partner.

Setup:

df = pd.DataFrame({'company':['a','b','c','b'], 'partner':['x','x','y','y'], 'str':['just','some','random','words']})

Desired Output:

company     x      y
a        True  False
b        True   True
c       False   True

I started with:

df = df.pivot(values = 'partner', columns = 'partner', index = 'company').reset_index()

which gets me close, but when I try to get rid of the "partner" column, I can't even reference it, and it's not the "index".

For the second issue, I can use:

df.fillna(False, inplace = True)
df.loc[~(df['x'] == False), 'x'] = True
df.loc[~(df['y'] == False), 'y'] = True

but that seems incredibly hacky.  Any help would be appreciated.

Body:
Option 1

df.groupby(['company', 'partner']).size().unstack(fill_value=0).astype(bool)

partner      x      y
company
a         True  False
b         True   True
c        False   True

Get rid of names on columns object

df.groupby(['company', 'partner']).size().unstack(fill_value=0).astype(bool) \
    .rename_axis(None, 1).reset_index()

  company      x      y
0       a   True  False
1       b   True   True
2       c  False   True

Option 2

pd.crosstab(df.company, df.partner).astype(bool)

partner      x      y
company
a         True  False
b         True   True
c        False   True

pd.crosstab(df.company, df.partner).astype(bool) \
    .rename_axis(None, 1).reset_index()

  company      x      y
0       a   True  False
1       b   True   True
2       c  False   True

Option 3

f1, u1 = pd.factorize(df.company.values)
f2, u2 = pd.factorize(df.partner.values)
n, m = u1.size, u2.size

b = np.bincount(f1 * m + f2)
pad = np.zeros(n * m - b.size, dtype=int)
b = np.append(b, pad)
v = b.reshape(n, m).astype(bool)

pd.DataFrame(np.column_stack([u1, v]), columns=np.append('company', u2))

  company      x      y
0       a   True  False
1       b   True   True
2       c  False   True

Timing

small data

%timeit df.groupby(['company', 'partner']).size().unstack(fill_value=0).astype(bool).rename_axis(None, 1).reset_index()
%timeit pd.crosstab(df.company, df.partner).astype(bool).rename_axis(None, 1).reset_index()

%%timeit
f1, u1 = pd.factorize(df.company.values)
f2, u2 = pd.factorize(df.partner.values)
n, m = u1.size, u2.size

b = np.bincount(f1 * m + f2)
pad = np.zeros(n * m - b.size, dtype=int)
b = np.append(b, pad)
v = b.reshape(n, m).astype(bool)

pd.DataFrame(np.column_stack([u1, v]), columns=np.append('company', u2))

1000 loops, best of 3: 1.67 ms per loop
100 loops, best of 3: 5.97 ms per loop
1000 loops, best of 3: 301 µs per loop


问:
convert html to image in byte array java
How can i easily convert html to image and then to byte array without create it

thanks

答:
If you do not have any complex html you can render it using a normal JLabel. The code below will produce this image:

```<code><html>
  <h1>:)</h1>
  Hello World!<br>
  <img src="http://img0.gmodules.com/ig/images/igoogle_logo_sm.png">
</html>
</code>```

```<code>public static void main(String... args) throws IOException {

    String html = "<html>" +
            "<h1>:)</h1>" +
            "Hello World!<br>" +
            "<img src=\"http://img0.gmodules.com/ig/images/igoogle_logo_sm.png\">" +
            "</html>";

    JLabel label = new JLabel(html);
    label.setSize(200, 120);

    BufferedImage image = new BufferedImage(
            label.getWidth(), label.getHeight(),
            BufferedImage.TYPE_INT_ARGB);

    {
        // paint the html to an image
        Graphics g = image.getGraphics();
        g.setColor(Color.BLACK);
        label.paint(g);
        g.dispose();
    }

    // get the byte array of the image (as jpeg)
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ImageIO.write(image, "jpg", baos);
    byte[] bytes = baos.toByteArray();

    ....
}
</code>```

If you would like to just write it to a file:

```<code>    ImageIO.write(image, "png", new File("test.png"));
</code>```

ContentLicense: CC BY-SA 2.5

Body:
If you do not have any complex html you can render it using a normal JLabel. The code below will produce this image:

<html>
  <h1>:)</h1>
  Hello World!<br>
  <img src="http://img0.gmodules.com/ig/images/igoogle_logo_sm.png">
</html>

public static void main(String... args) throws IOException {

    String html = "<html>" +
            "<h1>:)</h1>" +
            "Hello World!<br>" +
            "<img src=\"http://img0.gmodules.com/ig/images/igoogle_logo_sm.png\">" +
            "</html>";

    JLabel label = new JLabel(html);
    label.setSize(200, 120);

    BufferedImage image = new BufferedImage(
            label.getWidth(), label.getHeight(),
            BufferedImage.TYPE_INT_ARGB);

    {
        // paint the html to an image
        Graphics g = image.getGraphics();
        g.setColor(Color.BLACK);
        label.paint(g);
        g.dispose();
    }

    // get the byte array of the image (as jpeg)
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ImageIO.write(image, "jpg", baos);
    byte[] bytes = baos.toByteArray();

    ....
}

If you would like to just write it to a file:

    ImageIO.write(image, "png", new File("test.png"));


问:
Convert scipy condensed distance matrix to lower matrix read by rows
I have a condensed distance matrix from scipy that I need to pass to a C function that requires the matrix be converted to the lower triangle read by rows. For example:

```<code>0 1 2 3
  0 4 5
    0 6
      0
</code>```

The condensed form of this is: [1,2,3,4,5,6] but I need to convert it to

```<code>0
1 0
2 4 0
3 5 6 0
</code>```

The lower triangle read by rows is: [1,2,4,3,5,6].

I was hoping to convert the compact distance matrix to this form without creating a redundant matrix.

答:
Here's a quick implementation--but it creates the square redundant distance matrix as an intermediate step:

```<code>In [128]: import numpy as np

In [129]: from scipy.spatial.distance import squareform
</code>```

c is the condensed form of the distance matrix:

```<code>In [130]: c = np.array([1, 2, 3, 4, 5, 6])
</code>```

d is the redundant square distance matrix:

```<code>In [131]: d = squareform(c)
</code>```

Here's your condensed lower triangle distances:

```<code>In [132]: d[np.tril_indices(d.shape[0], -1)]
Out[132]: array([1, 2, 4, 3, 5, 6])
</code>```

Here's a method that avoids forming the redundant distance matrix.  The function condensed_index(i, j, n) takes the row i and column j of the redundant distance matrix, with j > i, and returns the corresponding index in the condensed distance array.

```<code>In [169]: def condensed_index(i, j, n):
     ...:     return n*i - i*(i+1)//2 + j - i - 1
     ...:
</code>```

As above, c is the condensed distance array.

```<code>In [170]: c
Out[170]: array([1, 2, 3, 4, 5, 6])

In [171]: n = 4

In [172]: i, j = np.tril_indices(n, -1)
</code>```

Note that the arguments are reversed in the following call:

```<code>In [173]: indices = condensed_index(j, i, n)
</code>```

indices gives the desired permutation of the condensed distance array.

```<code>In [174]: c[indices]
Out[174]: array([1, 2, 4, 3, 5, 6])
</code>```

(Basically the same function as condensed_index(i, j, n) was given in several answers to this question.)

Body:
I have a condensed distance matrix from scipy that I need to pass to a C function that requires the matrix be converted to the lower triangle read by rows. For example:

0 1 2 3
  0 4 5
    0 6
      0

The condensed form of this is: [1,2,3,4,5,6] but I need to convert it to

0
1 0
2 4 0
3 5 6 0

The lower triangle read by rows is: [1,2,4,3,5,6].

I was hoping to convert the compact distance matrix to this form without creating a redundant matrix.

Body:
Here's a quick implementation--but it creates the square redundant distance matrix as an intermediate step:

In [128]: import numpy as np

In [129]: from scipy.spatial.distance import squareform

c is the condensed form of the distance matrix:

In [130]: c = np.array([1, 2, 3, 4, 5, 6])

d is the redundant square distance matrix:

In [131]: d = squareform(c)

Here's your condensed lower triangle distances:

In [132]: d[np.tril_indices(d.shape[0], -1)]
Out[132]: array([1, 2, 4, 3, 5, 6])

Here's a method that avoids forming the redundant distance matrix.  The function condensed_index(i, j, n) takes the row i and column j of the redundant distance matrix, with j > i, and returns the corresponding index in the condensed distance array.

In [169]: def condensed_index(i, j, n):
     ...:     return n*i - i*(i+1)//2 + j - i - 1
     ...:

As above, c is the condensed distance array.

In [170]: c
Out[170]: array([1, 2, 3, 4, 5, 6])

In [171]: n = 4

In [172]: i, j = np.tril_indices(n, -1)

Note that the arguments are reversed in the following call:

In [173]: indices = condensed_index(j, i, n)

indices gives the desired permutation of the condensed distance array.

In [174]: c[indices]
Out[174]: array([1, 2, 4, 3, 5, 6])

(Basically the same function as condensed_index(i, j, n) was given in several answers to this question.)


问:
log4j 2: log file being created, but not being written to
I am using log4j 2. I am trying to determine why my log file is not being written to, but my console is. This is the output I have to the console:

```<code>2016-04-25 12:26:07,142 INFO  [main] helperCode.LogPlus (LogPlus.java:50) -
----------------------------------------------------------------------------
------------ The test is starting now at 2016-04-25-12-26-07-135 -----------
----------------------------------------------------------------------------

2016-04-25 12:26:07,151 INFO  [main] helperCode.LogPlus (LogPlus.java:50) -
--------------------------------------------------------------------------
------------ METHOD loginBadPasswordGoodUsername_3 starting:  ------------
--------------------------------------------------------------------------
</code>```

The issues I've considered already:

The output is not repeating itself, so the log output being redirected is not an issue.

I am NOT using java.util.logging.Logger anywhere in my project;

The output of the log file is formatted in log4j style rather than JUL style, so I know that JUL is not overriding it;

Here is my XML config file:

```<code><?xml version="1.0" encoding="UTF-8"?>
<Configuration>
    <Appenders>
        <File name="FileLogger" fileName="${sys:logFilePath}" append="false">
            <PatternLayout pattern="%d %t %-5p %c{2} - %m%n" />
        </File>
        <Async name="Async">
            <AppenderRef ref="FileLogger" />
        </Async>
        <Console name="STDOUT" target="SYSTEM_OUT">
            <PatternLayout pattern="%d %-5p [%t] %C{2} (%F:%L) - %m%n" />
        </Console>
    </Appenders>
    <Loggers>
        <Logger name="automationFramework" level="trace">
            <AppenderRef ref="FileLogger" />
        </Logger>
        <Root level="trace">
            <AppenderRef ref="STDOUT" />
        </Root>
    </Loggers>
</Configuration>
</code>```

I am directing the output to the file located at the system variable "logFilePath".

I am not sure what is going on, and the config files shown on answers for similar questions are not in XML format, so I am not sure how to commute the config file code to XML.

答:
For the complete noob, like myself, this line in Unknown's answer above:

```<code>    <Logger name="your package" level="trace">
</code>```

is  the key.  When it says "your package" it really means the "package foo.bar" you declared at the top of the .java file where you created the Logger, not the class name you passed to create the Logger, like:

```<code>    LOGGER = LogManager.getLogger(MyClass.class.getName());
</code>```

It took me a ridiculous amount of time today to get my log4j2 output going to a file, playing with various "name" values until the light bulb went on.

Body:
I am using log4j 2. I am trying to determine why my log file is not being written to, but my console is. This is the output I have to the console:

2016-04-25 12:26:07,142 INFO  [main] helperCode.LogPlus (LogPlus.java:50) -
----------------------------------------------------------------------------
------------ The test is starting now at 2016-04-25-12-26-07-135 -----------
----------------------------------------------------------------------------

2016-04-25 12:26:07,151 INFO  [main] helperCode.LogPlus (LogPlus.java:50) -
--------------------------------------------------------------------------
------------ METHOD loginBadPasswordGoodUsername_3 starting:  ------------
--------------------------------------------------------------------------

The issues I've considered already:

The output is not repeating itself, so the log output being redirected is not an issue.

I am NOT using java.util.logging.Logger anywhere in my project;

The output of the log file is formatted in log4j style rather than JUL style, so I know that JUL is not overriding it;

Here is my XML config file:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
    <Appenders>
        <File name="FileLogger" fileName="${sys:logFilePath}" append="false">
            <PatternLayout pattern="%d %t %-5p %c{2} - %m%n" />
        </File>
        <Async name="Async">
            <AppenderRef ref="FileLogger" />
        </Async>
        <Console name="STDOUT" target="SYSTEM_OUT">
            <PatternLayout pattern="%d %-5p [%t] %C{2} (%F:%L) - %m%n" />
        </Console>
    </Appenders>
    <Loggers>
        <Logger name="automationFramework" level="trace">
            <AppenderRef ref="FileLogger" />
        </Logger>
        <Root level="trace">
            <AppenderRef ref="STDOUT" />
        </Root>
    </Loggers>
</Configuration>

I am directing the output to the file located at the system variable "logFilePath".

I am not sure what is going on, and the config files shown on answers for similar questions are not in XML format, so I am not sure how to commute the config file code to XML.

Body:
For the complete noob, like myself, this line in Unknown's answer above:

    <Logger name="your package" level="trace">

is  the key.  When it says "your package" it really means the "package foo.bar" you declared at the top of the .java file where you created the Logger, not the class name you passed to create the Logger, like:

    LOGGER = LogManager.getLogger(MyClass.class.getName());

It took me a ridiculous amount of time today to get my log4j2 output going to a file, playing with various "name" values until the light bulb went on.


问:
How auto open infoWindow in google maps API
i have a problem with my map in my website, I want an InfoWindow to be displayed automatically when I enter the website, please i need you help, I leave the code, i hope you can help me</p>

```<code><script>
function initMap() {
  var map = new google.maps.Map(document.getElementById("mapa"), {
    center: new google.maps.LatLng(<?php echo $lat . "," . $lng ?>),
    zoom: 15,
    scrollwheel: false,
    mapTypeId: 'roadmap'
  });
  var infoWindow = new google.maps.InfoWindow;

  // Change this depending on the name of your PHP file
  downloadUrl("xmltiendas.xml", function(data) {
    var xml = data.responseXML;
    var markers = xml.documentElement.getElementsByTagName("marker");
    for (var i = 0; i < markers.length; i++) {
      var name = markers[i].getAttribute("name");
      var address = markers[i].getAttribute("address");
      var horario = markers[i].getAttribute("horario");
      var type = markers[i].getAttribute("type");
      var telefono = markers[i].getAttribute("telefono");
      var lada = markers[i].getAttribute("lada");
      var estado = markers[i].getAttribute("estado");
      var link = markers[i].getAttribute("link");
      var point = new google.maps.LatLng(
          parseFloat(markers[i].getAttribute("lat")),
          parseFloat(markers[i].getAttribute("lng")));
       var html = "<div class='infoWindow'><p class='title'>Cell Repair " + name + "</p> <p>" + address + "</p></div>";
      var icon = customIcons[type] || {};
      var marker = new google.maps.Marker({
        map: map,
        position: point,
        icon: 'images/pin-location-mobo.png'
      });
      bindInfoWindow(marker, map, infoWindow, html);

    }
  });
}
function bindInfoWindow(marker, map, infoWindow, html) {
     google.maps.event.addListener(marker, 'click', function() {
        infoWindow.setContent(html);
        infoWindow.open(map, marker);
        marker.showInfoWindow();
      });
 }
</code>```

<p>

答:
```<code>function bindInfoWindow(marker, map, infoWindow, html) {
     google.maps.event.addListener(marker, 'click', function() {
        infoWindow.setContent(html);
        infoWindow.open(map, marker);
      });
     google.maps.event.trigger(marker, 'click');
 }
</code>```

You can always use the google maps trigger event.

google.maps.event.trigger(marker, 'click');

I added this one after you set the addlistener inside the bindInfoWindow function.

Hope it helps.

Body:
function bindInfoWindow(marker, map, infoWindow, html) {
     google.maps.event.addListener(marker, 'click', function() {
        infoWindow.setContent(html);
        infoWindow.open(map, marker);
      });
     google.maps.event.trigger(marker, 'click');
 }

You can always use the google maps trigger event.

google.maps.event.trigger(marker, 'click');

I added this one after you set the addlistener inside the bindInfoWindow function.

Hope it helps.


问:
Display app theme immediately in Flutter app
Given the asynchronous nature of the Flutter shared_prefs plugin, how could one make sure that when an app is launched the correct theme settings are immediately displayed? I.e. no flash of the default theme followed by applying the correct theme once the shared_prefs have finished loading.</p>

答:
When your build method requires waiting for a Future, it's a good time to break out FutureBuilder.

```<code>void main() {
  runApp(new FutureBuilder(
    future: SharedPreferences.getInstance(),
    builder: (_, snapshot) {
      return snapshot.hasData ?
             new MyApp(preferences: snapshot.data) :
             new LoadingScreen();
    },
  ));
}
</code>```

A few tips for building apps with this pattern:

SharedPreferences.getInstance() is pretty fast. You app may look better with an empty Container as a black loading screen instead of a flash of colorful content. However, if you're loading other stuff at the same time, showing your logo makes more sense.

If you need to await multiple futures, you can use
Future.wait or nest multiple FutureBuilders together.

Body:
When your build method requires waiting for a Future, it's a good time to break out FutureBuilder.

void main() {
  runApp(new FutureBuilder(
    future: SharedPreferences.getInstance(),
    builder: (_, snapshot) {
      return snapshot.hasData ?
             new MyApp(preferences: snapshot.data) :
             new LoadingScreen();
    },
  ));
}

A few tips for building apps with this pattern:

SharedPreferences.getInstance() is pretty fast. You app may look better with an empty Container as a black loading screen instead of a flash of colorful content. However, if you're loading other stuff at the same time, showing your logo makes more sense.

If you need to await multiple futures, you can use
Future.wait or nest multiple FutureBuilders together.


问:
Casting expected value of a generic type
Surely, due to my limited knowledge in C# I believe there must be more efficient, cleaner way to dot this?

```<code>  public void Set(object nValue)
  {
      if (typeof(T) == typeof(bool))
          this.private_value = (T) (object) Convert.ToBoolean((string)nValue);
  }
</code>```

where T is a value type for private_value. Usually bool or int.

Is there a better way to achieve this efficiently?

答:
You can use Convert.ChangeType instead:

```<code>this.private_value = (T)Convert.ChangeType(nValue, typeof(T));
</code>```

Demo.

Body:
Surely, due to my limited knowledge in C# I believe there must be more efficient, cleaner way to dot this?

  public void Set(object nValue)
  {
      if (typeof(T) == typeof(bool))
          this.private_value = (T) (object) Convert.ToBoolean((string)nValue);
  }

where T is a value type for private_value. Usually bool or int.

Is there a better way to achieve this efficiently?

Body:
You can use Convert.ChangeType instead:

this.private_value = (T)Convert.ChangeType(nValue, typeof(T));

Demo.


问:
The most efficient way to delete millions of files based on modified date, in windows
Goal: Use a script to run through 5 million - 10 million XML files and evaluate their date, if older than 90 days delete the file. The script would be run daily.

Problem: Using powershell Get-ChildItem -recurse, causes the script to lock up and fail to delete any files, I assume this is because of the way Get-ChildItem needs to build the whole array before taking any action on any file.

Solution ?: After lots of research I found that [System.IO.Directory]::EnumerateFiles will be able to take action on items in the array before the array is completely built so that should make things more efficient (https://msdn.microsoft.com/library/dd383458%28v=vs.100%29.aspx). After more testing I found that foreach ($1 in $2) is more efficient than $1 | % {}
Before I run this new code and potentially crash this server again is there any adjustment anyone can suggest for a more efficient way to script this?

For testing I just created 15,000 x 0.02KB txt files in 15,000 directories with random data in them and ran the below code, I used 90 seconds instead of 90 days on the $date variable just for the test, it took 6 seconds to delete all the txt files.

```<code>$getfiles = [System.IO.Directory]::EnumerateFiles("C:\temp", "*.txt", "AllDirectories")
$date = ([System.DateTime]::Now).AddSeconds(-90)
foreach ($2 in $getfiles) {
if ([System.IO.File]::GetLastWriteTime($2) -le $date) {
[System.IO.File]::Delete($2)
} #if
} #foreach
</code>```

答:
Powershell one-liner that does 100,000 files >= 90 days old.

```<code>[IO.Directory]::EnumerateFiles("C:\FOLDER_WITH_FILES_TO_DELETE") |
select -first 100000 | where { [IO.File]::GetLastWriteTime($_) -lt
(Get-Date).AddDays(-90) } | foreach { rm $_ }
</code>```

or with progress shown:

```<code>[IO.Directory]::EnumerateFiles("C:\FOLDER_WITH_FILES_TO_DELETE") |
select -first 100000 | where { [IO.File]::GetLastWriteTime($_) -lt
(Get-Date).AddDays(-90) } | foreach { $c = 0 } { Write-Progress
-Activity "Delete Files" -CurrentOperation $_ -PercentComplete
((++$c/100000)*100); rm $_ }
</code>```

This works on folders that have a very large number of files. Thanks to my co-worker Doug!

Body:
Goal: Use a script to run through 5 million - 10 million XML files and evaluate their date, if older than 90 days delete the file. The script would be run daily.

Problem: Using powershell Get-ChildItem -recurse, causes the script to lock up and fail to delete any files, I assume this is because of the way Get-ChildItem needs to build the whole array before taking any action on any file.

Solution ?: After lots of research I found that [System.IO.Directory]::EnumerateFiles will be able to take action on items in the array before the array is completely built so that should make things more efficient (https://msdn.microsoft.com/library/dd383458%28v=vs.100%29.aspx). After more testing I found that foreach ($1 in $2) is more efficient than $1 | % {}
Before I run this new code and potentially crash this server again is there any adjustment anyone can suggest for a more efficient way to script this?

For testing I just created 15,000 x 0.02KB txt files in 15,000 directories with random data in them and ran the below code, I used 90 seconds instead of 90 days on the $date variable just for the test, it took 6 seconds to delete all the txt files.

$getfiles = [System.IO.Directory]::EnumerateFiles("C:\temp", "*.txt", "AllDirectories")
$date = ([System.DateTime]::Now).AddSeconds(-90)
foreach ($2 in $getfiles) {
if ([System.IO.File]::GetLastWriteTime($2) -le $date) {
[System.IO.File]::Delete($2)
} #if
} #foreach

Body:
Powershell one-liner that does 100,000 files >= 90 days old.

[IO.Directory]::EnumerateFiles("C:\FOLDER_WITH_FILES_TO_DELETE") |
select -first 100000 | where { [IO.File]::GetLastWriteTime($_) -lt
(Get-Date).AddDays(-90) } | foreach { rm $_ }

or with progress shown:

[IO.Directory]::EnumerateFiles("C:\FOLDER_WITH_FILES_TO_DELETE") |
select -first 100000 | where { [IO.File]::GetLastWriteTime($_) -lt
(Get-Date).AddDays(-90) } | foreach { $c = 0 } { Write-Progress
-Activity "Delete Files" -CurrentOperation $_ -PercentComplete
((++$c/100000)*100); rm $_ }

This works on folders that have a very large number of files. Thanks to my co-worker Doug!


问:
CSV string handling
Typical way of creating a CSV string (pseudocode):

Create a CSV container object (like a StringBuilder in C#).

Loop through the strings you want to add appending a comma after each one.

After the loop, remove that last superfluous comma.

Code sample:

```<code>public string ReturnAsCSV(ContactList contactList)
{
    StringBuilder sb = new StringBuilder();
    foreach (Contact c in contactList)
    {
        sb.Append(c.Name + ",");
    }

    sb.Remove(sb.Length - 1, 1);
    //sb.Replace(",", "", sb.Length - 1, 1)

    return sb.ToString();
}
</code>```

I like the idea of adding the comma by checking if the container is empty, but doesn't that mean more processing as it needs to check the length of the string on each occurrence?

I feel that there should be an easier/cleaner/more efficient way of removing that last comma. Any ideas?

答:
How about tracking whether you are on the first item, and only add a comma before the item if it is not the first one.

```<code>public string ReturnAsCSV(ContactList contactList)
{
    StringBuilder sb = new StringBuilder();
    bool isFirst = true;

    foreach (Contact c in contactList) {
        if (!isFirst) {
          // Only add comma before item if it is not the first item
          sb.Append(",");
        } else {
          isFirst = false;
        }

        sb.Append(c.Name);
    }

    return sb.ToString();
}
</code>```

Title: CSV string handling

Body:
Typical way of creating a CSV string (pseudocode):

Create a CSV container object (like a StringBuilder in C#).

Loop through the strings you want to add appending a comma after each one.

After the loop, remove that last superfluous comma.

Code sample:

public string ReturnAsCSV(ContactList contactList)
{
    StringBuilder sb = new StringBuilder();
    foreach (Contact c in contactList)
    {
        sb.Append(c.Name + ",");
    }

    sb.Remove(sb.Length - 1, 1);
    //sb.Replace(",", "", sb.Length - 1, 1)

    return sb.ToString();
}

I like the idea of adding the comma by checking if the container is empty, but doesn't that mean more processing as it needs to check the length of the string on each occurrence?

I feel that there should be an easier/cleaner/more efficient way of removing that last comma. Any ideas?

LastEditorDisplayName: aussieviking

Body:
How about tracking whether you are on the first item, and only add a comma before the item if it is not the first one.

public string ReturnAsCSV(ContactList contactList)
{
    StringBuilder sb = new StringBuilder();
    bool isFirst = true;

    foreach (Contact c in contactList) {
        if (!isFirst) {
          // Only add comma before item if it is not the first item
          sb.Append(",");
        } else {
          isFirst = false;
        }

        sb.Append(c.Name);
    }

    return sb.ToString();
}


问:
Simple Message Client golang
So I've started a project which involves modules sending and receiving messages from a server via websockets. However I wanted a simple way for me to interact and send messages to the modules.

So I have the program ask for my message in a goroutine, when I hit enter, it sends the message and prompts me for another. In the main goroutine it will wait until it receives a message and when it does, write over the current line and replace what was on the line before on a new line.

There is only one problem, however. It don't know how to keep my input to place on the new line. In my testing with the following example, it seems that os.Stdin.Read halts until it receives a new-line character.

```<code>package main

import (
    "bufio"
    "fmt"
    "os"
    "time"
)

func main() {
    // Input Buffer
    var msg string

    scanner := bufio.NewScanner(os.Stdin)
    scanner.Split(bufio.ScanBytes)

    go func() {
        for {
            // Prompt the user for a message
            fmt.Print("client1: ")

            // Scan os.Stdin, splitting on bytes
            for scanner.Scan() {
                if scanner.Text() == "\n" {
                    break
                } else {
                    // If the character is not \n, add to the input buffer
                    msg += scanner.Text()
                }
            }

            // Do something with the input buffer then clear it
            fmt.Println(msg)
            msg = ""
        }
    }()

    for {
        select {
        // Receive a message from a client
        case <-time.After(5 * time.Second):
            // Write the message over the current line
            fmt.Println("\rclient2: Hello")

            // Prompt the user again for their message
            // proving the current input buffer
            fmt.Print("client1: " + msg)
        }
    }
}
</code>```

An example output:

```<code>client1: Hello!
Hello!
client2: Hello
client1: Bye!
Bye!
client2: Hello
client2: Hello // Was "client1: Good " before being overwritten
client1: Bye!
Good Bye!
</code>```

Any ideas are greatly appreciated. Thank you in advanced.

答:
It seems like IO race condition. Your goroutine is not synced with main. Btw ScanLines do the same for you. Consider this:

```<code>package main

import (
    "bufio"
    "fmt"
    "os"
)

func main() {
    scanner := bufio.NewScanner(os.Stdin)
    msgQ := make(chan string)

    defer close(msgQ)

    go func() {
        for {
            // Prompt the user for a message
            fmt.Print("client1: ")
            msg, ok := <-msgQ
            if !ok {
                return
            }
            fmt.Println("\rclient1 said: " + msg)
            // Write the message over the current line
            fmt.Println("client2: Hello")
        }
    }()

    // Scan os.Stdin, splitting on bytes
    for scanner.Scan() {
        msgQ <- scanner.Text()
    }

}
</code>```

EDIT: According to comments, this code shows what is wrong with that idea. When you write something and dont hit ENTER, client2 overwrites current line.. You can save(CTRL-U) and restore(CTRL-Y) current line but I did not find either ANSI signature or Signal to call it programatically.

```<code>package main

import (
    "bufio"
    "fmt"
    "os"
    "time"
)

func main() {

    scanner := bufio.NewScanner(os.Stdin)
    sendQ := make(chan struct{})

    defer close(sendQ)

    //simulate local client1 console
    go func() {
        for {
            fmt.Print("client1: ")
            select {
            case _, ok := <-sendQ:
                if !ok {
                    return
                }
            case <-time.After(5 * time.Second):
                fmt.Printf("\r\033[K") // delete current line from right
                fmt.Println("client2: Hello")
            }
        }
    }()

    for scanner.Scan() {
        sendQ <- struct{}{}
    }

}
</code>```

Title: Simple Message Client golang

Body:
So I've started a project which involves modules sending and receiving messages from a server via websockets. However I wanted a simple way for me to interact and send messages to the modules.

So I have the program ask for my message in a goroutine, when I hit enter, it sends the message and prompts me for another. In the main goroutine it will wait until it receives a message and when it does, write over the current line and replace what was on the line before on a new line.

There is only one problem, however. It don't know how to keep my input to place on the new line. In my testing with the following example, it seems that os.Stdin.Read halts until it receives a new-line character.

package main

import (
    "bufio"
    "fmt"
    "os"
    "time"
)

func main() {
    // Input Buffer
    var msg string

    scanner := bufio.NewScanner(os.Stdin)
    scanner.Split(bufio.ScanBytes)

    go func() {
        for {
            // Prompt the user for a message
            fmt.Print("client1: ")

            // Scan os.Stdin, splitting on bytes
            for scanner.Scan() {
                if scanner.Text() == "\n" {
                    break
                } else {
                    // If the character is not \n, add to the input buffer
                    msg += scanner.Text()
                }
            }

            // Do something with the input buffer then clear it
            fmt.Println(msg)
            msg = ""
        }
    }()

    for {
        select {
        // Receive a message from a client
        case <-time.After(5 * time.Second):
            // Write the message over the current line
            fmt.Println("\rclient2: Hello")

            // Prompt the user again for their message
            // proving the current input buffer
            fmt.Print("client1: " + msg)
        }
    }
}

An example output:

client1: Hello!
Hello!
client2: Hello
client1: Bye!
Bye!
client2: Hello
client2: Hello // Was "client1: Good " before being overwritten
client1: Bye!
Good Bye!

Any ideas are greatly appreciated. Thank you in advanced.

Body:
It seems like IO race condition. Your goroutine is not synced with main. Btw ScanLines do the same for you. Consider this:

package main

import (
    "bufio"
    "fmt"
    "os"
)

func main() {
    scanner := bufio.NewScanner(os.Stdin)
    msgQ := make(chan string)

    defer close(msgQ)

    go func() {
        for {
            // Prompt the user for a message
            fmt.Print("client1: ")
            msg, ok := <-msgQ
            if !ok {
                return
            }
            fmt.Println("\rclient1 said: " + msg)
            // Write the message over the current line
            fmt.Println("client2: Hello")
        }
    }()

    // Scan os.Stdin, splitting on bytes
    for scanner.Scan() {
        msgQ <- scanner.Text()
    }

}

EDIT: According to comments, this code shows what is wrong with that idea. When you write something and dont hit ENTER, client2 overwrites current line.. You can save(CTRL-U) and restore(CTRL-Y) current line but I did not find either ANSI signature or Signal to call it programatically.

package main

import (
    "bufio"
    "fmt"
    "os"
    "time"
)

func main() {

    scanner := bufio.NewScanner(os.Stdin)
    sendQ := make(chan struct{})

    defer close(sendQ)

    //simulate local client1 console
    go func() {
        for {
            fmt.Print("client1: ")
            select {
            case _, ok := <-sendQ:
                if !ok {
                    return
                }
            case <-time.After(5 * time.Second):
                fmt.Printf("\r\033[K") // delete current line from right
                fmt.Println("client2: Hello")
            }
        }
    }()

    for scanner.Scan() {
        sendQ <- struct{}{}
    }

}


答:
You can also use a StatefulWidget with setState to update the root widget after the application configuration is complete.

You can use something like (in short):

```<code>@override
Widget build(BuildContext context) {
    _return mainWidget;
}
</code>```

In conjunction with:

```<code>mainWidget = loadingWidget();
someMethodThatDoesAppConfig().then((Widget configuredWidget) {
    setState(() {
        _mainWidget = configuredWidget;
    });
});
</code>```

Title: Display app theme immediately in Flutter app

Body: Given the asynchronous nature of the Flutter shared_prefs plugin, how could one make sure that when an app is launched the correct theme settings are immediately displayed? I.e. no flash of the default theme followed by applying the correct theme once the shared_prefs have finished loading.

Body:
You can also use a StatefulWidget with setState to update the root widget after the application configuration is complete.

You can use something like (in short):

@override
Widget build(BuildContext context) {
    _return mainWidget;
}

In conjunction with:

mainWidget = loadingWidget();
someMethodThatDoesAppConfig().then((Widget configuredWidget) {
    setState(() {
        _mainWidget = configuredWidget;
    });
});


问:
Python - Selenium - select an element from a dropdown menu
I need to select an element from a dropdown menu.

For example:

```<code>    <div class="col-sm-4 col-lg-2">
       <label for="rangeFilter" class="sr-only">Date Range</label>
       <select class="selectpicker" id="rangeFilter" data-none-selected-text="Range" name="range">
              <option value="">View by</option>
              <option value="6month">6 months</option>
              <option value="1year">1 Year</option>
              <option value="2year">2 Year</option>
              <option value="all">All time</option>
         </select>
     </div>
</code>```

but i have always some kind of error.

My code is so easy:

```<code>driver = webdriver.Chrome("D:\Python27\selenium\webdriver\chrome\chromedriver.exe")
driver.implicitly_wait(5)
driver.maximize_window()
driver.get("https://ispspeedindex.netflix.com/country/norway/")
time.sleep(15)
select = Select(driver.find_element_by_id('rangeFilter'))
select.select_by_visible_text('All time')
</code>```

but it don´t work. It appears a message about "element not visible: Element is not currently visible and may not be manipulated"

```<code>Traceback (most recent call last):
File "scraping.py", line 23, in <module>
select.select_by_visible_text('All time')
File "D:\Python27\lib\site-packages\selenium\webdriver\support\select.py", line 120, in select_by_visible_text
...
selenium.common.exceptions.ElementNotVisibleException: Message: element not visible: Element is not currently visible and may not be manipulated
</code>```

any idea? i was trying with some fixes from another stackoverflow questions but i didn´t find the way...

答:
The drop down that you tries to interact is not visible to the user unless we scroll up and that's why the error. Try to scroll up and then interact with the drop down. The below code might give you some idea.

```<code>element=find_element_by_xpath("xpath of the element you are trying to access")

element.location_once_scrolled_into_view
</code>```

Hope this helps. Thanks.

Body:
I need to select an element from a dropdown menu.

For example:

       Date Range
       <select class="selectpicker" id="rangeFilter" data-none-selected-text="Range" name="range">
              <option value="">View by</option>
              <option value="6month">6 months</option>
              <option value="1year">1 Year</option>
              <option value="2year">2 Year</option>
              <option value="all">All time</option>
         </select>

but i have always some kind of error.

My code is so easy:

driver = webdriver.Chrome("D:\Python27\selenium\webdriver\chrome\chromedriver.exe")
driver.implicitly_wait(5)
driver.maximize_window()
driver.get("https://ispspeedindex.netflix.com/country/norway/")
time.sleep(15)
select = Select(driver.find_element_by_id('rangeFilter'))
select.select_by_visible_text('All time')

but it don´t work. It appears a message about "element not visible: Element is not currently visible and may not be manipulated"

Traceback (most recent call last):
File "scraping.py", line 23, in <module>
select.select_by_visible_text('All time')
File "D:\Python27\lib\site-packages\selenium\webdriver\support\select.py", line 120, in select_by_visible_text
...
selenium.common.exceptions.ElementNotVisibleException: Message: element not visible: Element is not currently visible and may not be manipulated

any idea? i was trying with some fixes from another stackoverflow questions but i didn´t find the way...

Body:
The drop down that you tries to interact is not visible to the user unless we scroll up and that's why the error. Try to scroll up and then interact with the drop down. The below code might give you some idea.

element=find_element_by_xpath("xpath of the element you are trying to access")

element.location_once_scrolled_into_view

Hope this helps. Thanks.


问:
SQL Server : how do I find the change in percentage from the date prior?
I have a table similar to the one below. I'm looking to find the change in percentage from the most recent week to the week prior going back to inception. I'm not entirely sure what the best way to identify what the week prior is with respect to the ItemID in order to make the subtraction. I assume I can't get around this without a subquery or creating a TEMP table and assigning some sort of rank ID to identify which date is the prior date for this ItemID. Any help?

Current table:

```<code>SalesDate   ItemID  COUNT   TotCount    PERC
----------------------------------------------------
3/11/2017   1       7       755         0.009271523
1/11/2017   1       6       670         0.008955224
12/31/2016  1       5       655         0.007633588
12/17/2016  1       4       635         0.006299213
11/9/2016   1       3       580         0.005172414
10/22/2016  1       2       555         0.003603604
9/21/2016   1       1       510         0.001960784
</code>```

Desired table with newest PERC minus prior date PERC (ie 3/11/2017 PERC minus 1/11/2017 PERC will equal 0.000316299):

```<code>SalesDate   ItemID  COUNT   TotCount    PERC         change
----------------------------------------------------------------
3/11/2017   1       7       755         0.009271523  0.000316299
1/11/2017   1       6       670         0.008955224  0.001321636
12/31/2016  1       5       655         0.007633588  0.001334375
12/17/2016  1       4       635         0.006299213  0.001126799
11/9/2016   1       3       580         0.005172414  0.00156881
10/22/2016  1       2       555         0.003603604  0.001642819
9/21/2016   1       1       510         0.001960784  0.001960784
</code>```

Edit: to be clear, I have multiple ItemID's in this table so the subquery would need to factor in that the date prior is specific to the ItemID

答:
You would use lag().  I would write this as:

```<code>select t.*,
       (perc - lag(perc) over (partition by itemId order by SalesDate)) as diff
from t;
</code>```

This would return NULL for the last row.  You can fix that by doing:

```<code>select t.*,
       (perc - lag(perc, 1, 0) over (partition by itemId order by SalesDate)) as diff
from t;
</code>```

Body:
I have a table similar to the one below. I'm looking to find the change in percentage from the most recent week to the week prior going back to inception. I'm not entirely sure what the best way to identify what the week prior is with respect to the ItemID in order to make the subtraction. I assume I can't get around this without a subquery or creating a TEMP table and assigning some sort of rank ID to identify which date is the prior date for this ItemID. Any help?

Current table:

SalesDate   ItemID  COUNT   TotCount    PERC
----------------------------------------------------
3/11/2017   1       7       755         0.009271523
1/11/2017   1       6       670         0.008955224
12/31/2016  1       5       655         0.007633588
12/17/2016  1       4       635         0.006299213
11/9/2016   1       3       580         0.005172414
10/22/2016  1       2       555         0.003603604
9/21/2016   1       1       510         0.001960784

Desired table with newest PERC minus prior date PERC (ie 3/11/2017 PERC minus 1/11/2017 PERC will equal 0.000316299):

SalesDate   ItemID  COUNT   TotCount    PERC         change
----------------------------------------------------------------
3/11/2017   1       7       755         0.009271523  0.000316299
1/11/2017   1       6       670         0.008955224  0.001321636
12/31/2016  1       5       655         0.007633588  0.001334375
12/17/2016  1       4       635         0.006299213  0.001126799
11/9/2016   1       3       580         0.005172414  0.00156881
10/22/2016  1       2       555         0.003603604  0.001642819
9/21/2016   1       1       510         0.001960784  0.001960784

Edit: to be clear, I have multiple ItemID's in this table so the subquery would need to factor in that the date prior is specific to the ItemID

Body:
You would use lag().  I would write this as:

select t.*,
       (perc - lag(perc) over (partition by itemId order by SalesDate)) as diff
from t;

This would return NULL for the last row.  You can fix that by doing:

select t.*,
       (perc - lag(perc, 1, 0) over (partition by itemId order by SalesDate)) as diff
from t;


问:
java export variable output to csv
Any idea why this code not printing a blank output file??

`BufferedWriter out = new BufferedWriter(new FileWriter(new File(path)));

```<code>while (rs.next()) {
                        String id = rs.getString("id");
                        String title = rs.getString("title");
                        String content = rs.getString("introtext");
                        String parsed = Jsoup.parse(content).select("body").text();
                        data.add(id + " " + title + " " + parsed);
                        System.out.println(id + "\t" +title + "\t" + parsed );
                        out.write(rs.getString(id));
                        out.write(rs.getString(title));
                        out.write(rs.getString(parsed));
                    }

                rs.close();
                stmt.close();
                out.close();
            } catch (Exception e) {
                System.out.println(e);
            }
        }`
</code>```

答:
Your output seems to be flawed, because you first fetch id, title and parsed and then attempt to write fetching those values from the query (and they probably aren't there). This

```<code>out.write(rs.getString(id));
out.write(rs.getString(title));
out.write(rs.getString(parsed));
</code>```

should very probably be

```<code>out.write(id);
out.write(title);
out.write(parsed);
</code>```

And you might also want to write a comma as well (between those fields).

Title: java export variable output to csv

Body:
Any idea why this code not printing a blank output file??

`BufferedWriter out = new BufferedWriter(new FileWriter(new File(path)));

while (rs.next()) {
                        String id = rs.getString("id");
                        String title = rs.getString("title");
                        String content = rs.getString("introtext");
                        String parsed = Jsoup.parse(content).select("body").text();
                        data.add(id + " " + title + " " + parsed);
                        System.out.println(id + "\t" +title + "\t" + parsed );
                        out.write(rs.getString(id));
                        out.write(rs.getString(title));
                        out.write(rs.getString(parsed));
                    }

                rs.close();
                stmt.close();
                out.close();
            } catch (Exception e) {
                System.out.println(e);
            }
        }`

Body:
Your output seems to be flawed, because you first fetch id, title and parsed and then attempt to write fetching those values from the query (and they probably aren't there). This

out.write(rs.getString(id));
out.write(rs.getString(title));
out.write(rs.getString(parsed));

should very probably be

out.write(id);
out.write(title);
out.write(parsed);

And you might also want to write a comma as well (between those fields).


问:
2 Elements fill remaining height
I have a div in the middle with content inside.

I wish to have the top and bottom divs fill the remaining space.

Something like this

```<code><div class="container">
    <div class="top">

    </div>
    <div class="middle">
        Content
    </div>
    <div class="bottom">

    </div>
</div>
</code>```

If possible I would like the set a min height for the top and bottom containers.

答:
.top{
 min-height:100px;
}
.bottom{
 min-height:100px;
}```

or you can use different meseurment - like vh - for view height and so on
Forgot to add - it will go into your css file

Title: 2 Elements fill remaining height

Body:
I have a div in the middle with content inside.

I wish to have the top and bottom divs fill the remaining space.

Something like this

        Content

If possible I would like the set a min height for the top and bottom containers.

Body:
.top{
 min-height:100px;
}
.bottom{
 min-height:100px;
}

or you can use different meseurment - like vh - for view height and so on
Forgot to add - it will go into your css file


问:
Setting up Git for existing drupal directory
I need help working out how to setup a git (bitbucket) repository in an existing Drupal html folder.  I should point out I'm also new to coding, Drupal and Git.  I've fallen into this role and I'm well over my head.

We use Drupal features to manage the configuration of the site and it's these changes which are pushed to the bitbucket repository.  The Drupal folder has lots of additional files which aren't part of the repository as they are images, downloads etc...  and won't ever be part of the bitbucket repository.

So I need to work out the following (I've managed to work out bits myself):

Setup git in the new folder

Connecting to the bitbucket repository

Pulling changes from the repository to the new directory and ensuring it is all up to date

It seems straight forward but I keep running into errors

Git Init Sets up the folder

git remote add -t dev origin <bitbucket repository> Connects to the remote repository branch dev

I then try a git pull, but get an error because files already exist in the local folder.

I want to overwrite the local files which are part of the bitbucket repo but I also want to keep the files which aren't part of the bitbucket repository.

I've tried applying suggestions I've seen from other situations and I'm now in a bit of a mess with a detached head file etc...  Which I'll fix separately.

If a suggested workflow could be made that would be great.

Error Message as requested

```<code>git pull <repository> <branch>
  ...
    themes/seven/reset.css
    themes/seven/screenshot.png
    themes/seven/seven.info
    themes/seven/style-rtl.css
    themes/seven/style.css
    themes/seven/template.php
    themes/seven/vertical-tabs-rtl.css
    themes/seven/vertical-tabs.css
    themes/stark/README.txt
    themes/stark/layout.css
    themes/stark/logo.png
    themes/stark/screenshot.png
    themes/stark/stark.info
    update.php
    web.config
    xmlrpc.php
Please move or remove them before you can merge.
Aborting
</code>```

答:
I strongly advise reading chapters 1-3 of Pro Git, which will help you learn the Git model, which is hands-down the most important thing here.

That being said, it sounds like you're in a weird situation:

You have an existing repository which tracks Drupal configuration on Bitbucket.

You have a directory on a server which contains a Drupal configuration that

is not set up with version control, and

also contains multiple assets  (e.g. images, downloads) which version control should not track.

You want to bring the directory under version control.

Here's the problem: because the directory is not currently being version controlled, it is not easily reconciled with the version controlled copy on Bitbucket. Moreover, when you run git init, that creates a new repository, with a completely separate and independent history. You can technically merge the two together in a brute-force fashion, but that is less than ideal.

Keep in mind that the solution I am about to suggest is not necessarily recommended, and that it also assumes the current Drupal config on the server is derived from dev on the Bitbucket repo.

What you need to do is manually craft a new repository - one whose history corresponds to the Bitbucket repo but whose working tree is your current directory. In the root of the configuration directory, do this (this assumes foo/ does not previously exist):

```<code>rm -rf .git/
git clone --no-checkout <bitbucket_repo> foo/
mv foo/.git/ .
rm -rf foo/
</code>```

and this should, in theory, leave you in a position to integrate your existing config dir with the Bitbucket repo. Of course, I'm not 100% sure if this is what you were aiming to do, but it does sound like it.

Body:
I need help working out how to setup a git (bitbucket) repository in an existing Drupal html folder.  I should point out I'm also new to coding, Drupal and Git.  I've fallen into this role and I'm well over my head.

We use Drupal features to manage the configuration of the site and it's these changes which are pushed to the bitbucket repository.  The Drupal folder has lots of additional files which aren't part of the repository as they are images, downloads etc...  and won't ever be part of the bitbucket repository.

So I need to work out the following (I've managed to work out bits myself):

Setup git in the new folder

Connecting to the bitbucket repository

Pulling changes from the repository to the new directory and ensuring it is all up to date

It seems straight forward but I keep running into errors

Git Init Sets up the folder

git remote add -t dev origin <bitbucket repository> Connects to the remote repository branch dev

I then try a git pull, but get an error because files already exist in the local folder.

I want to overwrite the local files which are part of the bitbucket repo but I also want to keep the files which aren't part of the bitbucket repository.

I've tried applying suggestions I've seen from other situations and I'm now in a bit of a mess with a detached head file etc...  Which I'll fix separately.

If a suggested workflow could be made that would be great.

Error Message as requested

git pull <repository> <branch>
  ...
    themes/seven/reset.css
    themes/seven/screenshot.png
    themes/seven/seven.info
    themes/seven/style-rtl.css
    themes/seven/style.css
    themes/seven/template.php
    themes/seven/vertical-tabs-rtl.css
    themes/seven/vertical-tabs.css
    themes/stark/README.txt
    themes/stark/layout.css
    themes/stark/logo.png
    themes/stark/screenshot.png
    themes/stark/stark.info
    update.php
    web.config
    xmlrpc.php
Please move or remove them before you can merge.
Aborting

Body:
I strongly advise reading chapters 1-3 of Pro Git, which will help you learn the Git model, which is hands-down the most important thing here.

That being said, it sounds like you're in a weird situation:

You have an existing repository which tracks Drupal configuration on Bitbucket.

You have a directory on a server which contains a Drupal configuration that

is not set up with version control, and

also contains multiple assets  (e.g. images, downloads) which version control should not track.

You want to bring the directory under version control.

Here's the problem: because the directory is not currently being version controlled, it is not easily reconciled with the version controlled copy on Bitbucket. Moreover, when you run git init, that creates a new repository, with a completely separate and independent history. You can technically merge the two together in a brute-force fashion, but that is less than ideal.

Keep in mind that the solution I am about to suggest is not necessarily recommended, and that it also assumes the current Drupal config on the server is derived from dev on the Bitbucket repo.

What you need to do is manually craft a new repository - one whose history corresponds to the Bitbucket repo but whose working tree is your current directory. In the root of the configuration directory, do this (this assumes foo/ does not previously exist):

rm -rf .git/
git clone --no-checkout <bitbucket_repo> foo/
mv foo/.git/ .
rm -rf foo/

and this should, in theory, leave you in a position to integrate your existing config dir with the Bitbucket repo. Of course, I'm not 100% sure if this is what you were aiming to do, but it does sound like it.


问:
How to pass Dictionary parameters in SqlCommand
I have a dictionary(Dictionary dic); the key and value change dynamically.

How to use the Insert command to add record to SQL Server depends on the dic's content?

For example:

```<code>if dic={{"KeyA", "ValueA"}}
</code>```

then do Insert into tblTest(KeyA) values(ValueA)

```<code>if dic={{"KeyA", "ValueA"}, {"KeyX", "ValueX"}}
</code>```

then do Insert into tblTest(KeyA,KeyX) values(ValueA,ValueX)

```<code>if dic={{"KeyA", "ValueA"}, {"KeyC", "ValueC"}, {"KeyX", "ValueX"}}
</code>```

then do Insert into tblTest(KeyA,KeyC,KeyX) values(ValueA,ValueC,ValueX)

and so on...

Does anyone have good idea?

答:
You have a couple of options.

1. Dynamic SQL

Assuming you're okay with using raw SQL, then you can build a Dynamic-SQL string - while you can parameterise values you cannot parameterise database object names (such as column names), so there is a risk of SQL-injection there - but surrounding all identifiers with the escape characters '[' and ']' will mitigate this.

However, fortunately, the values themselves can still be parameterised - just dynamically add parameters.

I would generate my own list of column names from your dictionary to build the INSERT list, then set parameters accordingly:

Here's how I would do it:

```<code>var safeNames = dict.Select( pair =>
    new {
        ColumnName = pair.Key.Replace("[", "").Replace("]", ""), // assuming this is sufficient to prevent injection
        Value      = pair.Value
    }
);

StringBuilder sb = new StringBuilder("INSERT INTO [table] (");

Boolean first = true;
foreach( var pair in safeNames  ) {

    if( !first ) sb.Append(", ");
    first = false;

    sb.Append("[");
    sb.Append( pair.ColumnName );
    sb.Append("]");
}

sb.Append( " ) VALUES ( " );

first = false;
foreach( var pair in safeNames ) {

    if( !first ) sb.Append(", ");
    first = false;

    sb.Append("@");
    sb.Append( pair.ColumnName );
}

sb.Append( ");" );

using( SqlCommand cmd = connection.CreateCommand() ) {

    cmd.CommandText = sb.ToString();

    foreach( var pair in safeNames ) {
        cmd.Parameters.Add( '@' + pair.ColumnName ).Value = pair.Value;
    }

    cmd.ExecuteNonQuery();
}
</code>```

2. Using Entity Framework

If you're using Entity Framework, you can use a detached entity to perform an INSERT though note you cannot easily optionally exclude columns - the Entity Framework by default will always include all entity members in the INSERT, so if you have columns that have non-NULL default values which are otherwise undefined in your new detached Entity objects then they will be saved with NULL values, thus overriding your non-NULL defaults, so be warned:

```<code>MyEntity detached = new MyEntity();

Type entityType = typeof(MyEntity);

IEnumerable<PropertyInfo> properties = entityType
    .GetProperties()
    // Exclude inherited and special properties:
    .Where( pi => pi.DeclaringType == entityType && !pi.IsSpecialName )
    // Exclude non-read/write properties:
    .Where( pi => pi.CanRead && pi.CanWrite )
    // Exclude non-scalar properties:
    .Where( pi => pi.PropertyType.IsPrimitive || pi.PropertyType == typeof(String) );

foreach( PropertyInfo property in properties ) {

    Object value;
    if( dict.TryGetValue( property.Name, out value ) ) {

        property.SetValue( detached, value );
    }
}

MyDBContext dbContext = ...

// Attach the entity:
dbContext.TableName.Add( detached );

// Execute the INSERT:
dbContext.SaveChanges();
</code>```

If you want to exclude certain columns from the operation you need to use the dbContext.Entry( $entity ).Property( e = e.PropertyName ).IsModified = false method (though I don't know if this works for INSERT operations or just UPDATE).

Body:
I have a dictionary(Dictionary dic); the key and value change dynamically.

How to use the Insert command to add record to SQL Server depends on the dic's content?

For example:

if dic={{"KeyA", "ValueA"}}

then do Insert into tblTest(KeyA) values(ValueA)

if dic={{"KeyA", "ValueA"}, {"KeyX", "ValueX"}}

then do Insert into tblTest(KeyA,KeyX) values(ValueA,ValueX)

if dic={{"KeyA", "ValueA"}, {"KeyC", "ValueC"}, {"KeyX", "ValueX"}}

then do Insert into tblTest(KeyA,KeyC,KeyX) values(ValueA,ValueC,ValueX)

and so on...

Does anyone have good idea?

Body:
You have a couple of options.

1. Dynamic SQL

Assuming you're okay with using raw SQL, then you can build a Dynamic-SQL string - while you can parameterise values you cannot parameterise database object names (such as column names), so there is a risk of SQL-injection there - but surrounding all identifiers with the escape characters '[' and ']' will mitigate this.

However, fortunately, the values themselves can still be parameterised - just dynamically add parameters.

I would generate my own list of column names from your dictionary to build the INSERT list, then set parameters accordingly:

Here's how I would do it:

var safeNames = dict.Select( pair =>
    new {
        ColumnName = pair.Key.Replace("[", "").Replace("]", ""), // assuming this is sufficient to prevent injection
        Value      = pair.Value
    }
);

StringBuilder sb = new StringBuilder("INSERT INTO [table] (");

Boolean first = true;
foreach( var pair in safeNames  ) {

    if( !first ) sb.Append(", ");
    first = false;

    sb.Append("[");
    sb.Append( pair.ColumnName );
    sb.Append("]");
}

sb.Append( " ) VALUES ( " );

first = false;
foreach( var pair in safeNames ) {

    if( !first ) sb.Append(", ");
    first = false;

    sb.Append("@");
    sb.Append( pair.ColumnName );
}

sb.Append( ");" );

using( SqlCommand cmd = connection.CreateCommand() ) {

    cmd.CommandText = sb.ToString();

    foreach( var pair in safeNames ) {
        cmd.Parameters.Add( '@' + pair.ColumnName ).Value = pair.Value;
    }

    cmd.ExecuteNonQuery();
}

2. Using Entity Framework

If you're using Entity Framework, you can use a detached entity to perform an INSERT though note you cannot easily optionally exclude columns - the Entity Framework by default will always include all entity members in the INSERT, so if you have columns that have non-NULL default values which are otherwise undefined in your new detached Entity objects then they will be saved with NULL values, thus overriding your non-NULL defaults, so be warned:

MyEntity detached = new MyEntity();

Type entityType = typeof(MyEntity);

IEnumerable<PropertyInfo> properties = entityType
    .GetProperties()
    // Exclude inherited and special properties:
    .Where( pi => pi.DeclaringType == entityType && !pi.IsSpecialName )
    // Exclude non-read/write properties:
    .Where( pi => pi.CanRead && pi.CanWrite )
    // Exclude non-scalar properties:
    .Where( pi => pi.PropertyType.IsPrimitive || pi.PropertyType == typeof(String) );

foreach( PropertyInfo property in properties ) {

    Object value;
    if( dict.TryGetValue( property.Name, out value ) ) {

        property.SetValue( detached, value );
    }
}

MyDBContext dbContext = ...

// Attach the entity:
dbContext.TableName.Add( detached );

// Execute the INSERT:
dbContext.SaveChanges();

If you want to exclude certain columns from the operation you need to use the dbContext.Entry( $entity ).Property( e = e.PropertyName ).IsModified = false method (though I don't know if this works for INSERT operations or just UPDATE).


问:
How to comment SQL statements in Notepad++?
How can I "block comment" SQL statements in Notepad++?

For example:

```<code>CREATE TABLE gmr_virtuemart_calc_categories (
  id int(1) UNSIGNED NOT NULL,
  virtuemart_calc_id int(1) UNSIGNED NOT NULL DEFAULT '0',
  virtuemart_category_id int(1) UNSIGNED NOT NULL DEFAULT '0'
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
</code>```

It should be wrapped with /* at the start and */ at the end using regex in Notepad++ to produce:

```<code>/*CREATE TABLE ... (...) ENGINE=MyISAM DEFAULT CHARSET=utf8;*/
</code>```

答:
You only offer one sample input, so I am forced to build the pattern literally.  If this pattern isn't suitable because there are alternative queries and/or other interfering text, then please update your question.
Tick the "Match case" box.

Find what: (CREATE[^;]+;) Replace with: /*$1*/

Otherwise, you can use this for sql query blocks that start with a capital and end in semicolon:

Find what: ([A-Z][^;]+;) Replace with: /*$1*/

To improve accuracy, you might include ^ start of line anchors or add \r\n after the semi-colon or match the CHARSET portion before the semi-colon.  There are several adjustments that can be made.  I cannot be confident of accuracy without knowing more about the larger body of text.

ContentLicense: CC BY-SA 4.0

Body:
How can I "block comment" SQL statements in Notepad++?

For example:

CREATE TABLE gmr_virtuemart_calc_categories (
  id int(1) UNSIGNED NOT NULL,
  virtuemart_calc_id int(1) UNSIGNED NOT NULL DEFAULT '0',
  virtuemart_category_id int(1) UNSIGNED NOT NULL DEFAULT '0'
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

It should be wrapped with /* at the start and */ at the end using regex in Notepad++ to produce:

/*CREATE TABLE ... (...) ENGINE=MyISAM DEFAULT CHARSET=utf8;*/


问:
?? Operator - Using in one liner condition
Can someone explain how the below statement operates. I know that the ?? operator returns the first argument if it is not null. But I was a little confused when I saw the ? following the 'file' variable.</p>

```<code>return file?.ImportStatus ?? ImportStatusEnum.Unknown;
</code>```

答:
@dasblinkenlight is correct, just to show it a different way, it could be written like this (in order of evaluation):</p>

```<code>if (file == null) return ImportStatusEnum.Unknown;
if (file.ImportStatus  != null)
    return file.ImportStatus;
else
    return ImportStatusEnum.Unknown;
</code>```

Body:
Can someone explain how the below statement operates. I know that the ?? operator returns the first argument if it is not null. But I was a little confused when I saw the ? following the 'file' variable.

return file?.ImportStatus ?? ImportStatusEnum.Unknown;

Body:
@dasblinkenlight is correct, just to show it a different way, it could be written like this (in order of evaluation):

if (file == null) return ImportStatusEnum.Unknown;
if (file.ImportStatus  != null)
    return file.ImportStatus;
else
    return ImportStatusEnum.Unknown;


问:
Emit each item from Flowable Room ORM
I have a list of items in the Room ORM which I would like to display in a Recycler view. The data is being added from the network to the db. The problem is I am getting every time the whole list emited from the Flowable and not each item. I have tried with .distinctUntilChanged with no difference.

```<code>@Query("SELECT * FROM items")
Flowable<List<Item>> getItems();
</code>```

I have tried also to return only a single item which loads only the first one that is the db.

答: Yes, Flowable<List<Item>> means you'll get a single callback when the list changes: this is how Room works. Generally, you'd pass that list into DiffUtil, which then generates the set of changes needed to update your RecyclerView.

Title: Emit each item from Flowable Room ORM

Body:
I have a list of items in the Room ORM which I would like to display in a Recycler view. The data is being added from the network to the db. The problem is I am getting every time the whole list emited from the Flowable and not each item. I have tried with .distinctUntilChanged with no difference.

@Query("SELECT * FROM items")
Flowable<List<Item>> getItems();

I have tried also to return only a single item which loads only the first one that is the db.


问:
Android SeekBar setOnSeekBarChangeListener
I'm wondering about the behavior of the android SeekBars OnSeekBarChangeListener. In particular, is the onProgressChanged-method notified only for the first and the last touch on the seekbar?

I'm trying to refresh a TextView that should show the current progress of the SeekBar. But the TextView is just updated on first touch and last touch. Debugging this confirms my assumption that this method is called just twice :( What I would like to have is that the TextView shows every progress change in the SeekBar.

In short: I am searching for a possibility to get a progress listener that is called for every little progress change.

答:
All answers are correct, but you need to convert a long big fat number into a timer first:

```<code>    public String toTimer(long milliseconds){
    String finalTimerString = "";
    String secondsString;
    // Convert total duration into time
    int hours = (int)( milliseconds / (1000*60*60));
    int minutes = (int)(milliseconds % (1000*60*60)) / (1000*60);
    int seconds = (int) ((milliseconds % (1000*60*60)) % (1000*60) / 1000);
    // Add hours if there
    if(hours > 0){
        finalTimerString = hours + ":";
    }
    // Prepending 0 to seconds if it is one digit
    if(seconds < 10){
        secondsString = "0" + seconds;
    }else{
        secondsString = "" + seconds;}
    finalTimerString = finalTimerString + minutes + ":" + secondsString;
    // return timer string
    return finalTimerString;
}
</code>```

And this is how you use it:

```<code>@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
textView.setText(String.format("%s", toTimer(progress)));
}
</code>```

Body:
All answers are correct, but you need to convert a long big fat number into a timer first:

    public String toTimer(long milliseconds){
    String finalTimerString = "";
    String secondsString;
    // Convert total duration into time
    int hours = (int)( milliseconds / (1000*60*60));
    int minutes = (int)(milliseconds % (1000*60*60)) / (1000*60);
    int seconds = (int) ((milliseconds % (1000*60*60)) % (1000*60) / 1000);
    // Add hours if there
    if(hours > 0){
        finalTimerString = hours + ":";
    }
    // Prepending 0 to seconds if it is one digit
    if(seconds < 10){
        secondsString = "0" + seconds;
    }else{
        secondsString = "" + seconds;}
    finalTimerString = finalTimerString + minutes + ":" + secondsString;
    // return timer string
    return finalTimerString;
}

And this is how you use it:

@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
textView.setText(String.format("%s", toTimer(progress)));
}


问:
Parent fragment to Child Fragment communication
I have been searching and haven't found the best way for nested fragments to communicate with parent fragment. The Android documentation states that:

All Fragment-to-Fragment communication is done through the associated Activity. Two Fragments should never communicate directly.

Suppose I have a Gallery app, there is a ViewPagerFragment (parent) and ImageFragment(child) that is used to show images full screen when they are clicked. I need to pass an ArrayList of Files from my parent fragment to the child fragment. What is a proper way to do it?

1) Create a getter for the ArrayList in parent fragment and use the getParentFragment() in a child fragment to access this method?

2) Implement an interface and go through the Activity, but how will I locate the child fragment from the Activity if it doesn't have an ID?

3) Or use this in parent fragment:

ChildFragment fragment =(ChildFragment)getChildFragmentManager().findFragmentById(R.id.child_fragment_id);

And just use a setter in child fragment.

But again how do I get the ID of the childFragment?

Thanks everyone in advance

答: Data should be passed to fragments using Bundle as arguments. So just pass the Arraylist(serialized or otherwise) to your child fragment when launching it</p>


问:
How to get File Type of a file
Is there a way to get the file type displayed in windows explorer in VB.net

i.e in windows explorer in details view one can see for example

```
Name          Date Modified           Type                           Size
A.PDF         05/06/2017 5:54PM       Adobe Acrobat reader           150kb
B.DOCX        05/06/2017 5:00PM       Microsoft Word Document        100kb
etc.
```

I want to get the type.  I cant seem to find a way to get there.  It feels like this should be very easy.

```<code>Dim infoReader As System.IO.FileInfo
infoReader = My.Computer.FileSystem.GetFileInfo(txtFileName.Text)
</code>```

FileInfo gets me modified data and size of the file.. but not the type.

Appreciate forums help!

. I.e. for .pdf file the display with would "adobe acrobat document" .xls file would be "Microsoft excel worksheet"

答:
Honestly this is all you would need...

```<code>Public Shared Function GetFileType(ByVal Extention As String) As String
   Return My.Computer.Registry.GetValue("HKEY_CLASSES_ROOT\" & My.Computer.Registry.GetValue("HKEY_CLASSES_ROOT\" & Extention, "", Extention).ToString, "", Extention).ToString
End Function
</code>```

To use it just get the extension of your file and then pass that into the function.  Below will get your extension you would need.

```<code>IO.Path.GetExtension(YOUR FILE PATH HERE)
</code>```

So all wrapped up...

```<code> Dim strName As String = GetFileType(IO.Path.GetExtension(YOUR FILE PATH HERE))
</code>```

Title: How to get File Type of a file

Body:
Is there a way to get the file type displayed in windows explorer in VB.net

i.e in windows explorer in details view one can see for example

Name          Date Modified           Type                           Size
A.PDF         05/06/2017 5:54PM       Adobe Acrobat reader           150kb
B.DOCX        05/06/2017 5:00PM       Microsoft Word Document        100kb
etc.

I want to get the type.  I cant seem to find a way to get there.  It feels like this should be very easy.

Dim infoReader As System.IO.FileInfo
infoReader = My.Computer.FileSystem.GetFileInfo(txtFileName.Text)

FileInfo gets me modified data and size of the file.. but not the type.

Appreciate forums help!

. I.e. for .pdf file the display with would "adobe acrobat document" .xls file would be "Microsoft excel worksheet"

Body:
Honestly this is all you would need...

Public Shared Function GetFileType(ByVal Extention As String) As String
   Return My.Computer.Registry.GetValue("HKEY_CLASSES_ROOT\" & My.Computer.Registry.GetValue("HKEY_CLASSES_ROOT\" & Extention, "", Extention).ToString, "", Extention).ToString
End Function

To use it just get the extension of your file and then pass that into the function.  Below will get your extension you would need.

IO.Path.GetExtension(YOUR FILE PATH HERE)

So all wrapped up...

 Dim strName As String = GetFileType(IO.Path.GetExtension(YOUR FILE PATH HERE))


问:
Reduced VS 2017 IDE interactivity in MVC 5 Razor views in 2015 project
I just installed VS 2017 and am opening an MVC 5 project created in VS 2015.  The application runs fine, but I am experiencing reduced interactivity between my MVC Razor view code and the 2017 IDE.

Here's is the context menu when I right-click on an HTML helper method in VS 2015:

However, I only see this in 2017:

Also notice the lack of syntax color-coding in the 2017 verison.  It's like it's not recognizing Razor syntax at all.

I did not do any special solution/project upgrades.  I just opened the solution in 2017 and expected it to prompt me to upgrade any files that needed upgrading.

答: Repair your Visual Studio installation. This happened to me as well.</p>


问:
Counting Sheep (Beatrix Trotter) Javascript
I am trying to solve a question on CodeWars that was part of the Google CodeJam 2016 qualification rounds.
https://www.codewars.com/kata/bleatrix-trotter-the-counting-sheep/train/javascript

I believe my code accounts for all test cases, my only issue is that it cannot be submitted on codewars because it has a runtime greater than 12000 ms.

How Can I make my Code more efficient?? also is there a best practice for testing whether the loop will be infinite.

```<code>function trotter(n) {
  var tracker = [];
  var sum = [];
  var snacker = n;
  for(var i = 0; tracker.length < 10; i++){
    sum = snacker.toString().split('');
    sum.forEach(function(num) {
        if (tracker.indexOf(num) == -1) {
             tracker.push(num);
        }
    });
    snacker += n;
  }
  return tracker.length === 10 ? snacker - n : "INSOMNIA";
}
</code>```

答:
Another approach:

    function trotter(n){
      var unseen = '0123456789', last = 0;
      while (unseen != '' && last < 72*n) {
        last += n;
        var reg = new RegExp('[' + last + ']+', 'g');
        unseen = unseen.replace(reg, '');
      }
      return unseen != '' ? 'INSOMNIA' : last;
    };

    console.log('0   : ' + trotter(0));
    console.log('125 : ' + trotter(125));
    console.log('1625: ' + trotter(1625));```

Body:
I am trying to solve a question on CodeWars that was part of the Google CodeJam 2016 qualification rounds.
https://www.codewars.com/kata/bleatrix-trotter-the-counting-sheep/train/javascript

I believe my code accounts for all test cases, my only issue is that it cannot be submitted on codewars because it has a runtime greater than 12000 ms.

How Can I make my Code more efficient?? also is there a best practice for testing whether the loop will be infinite.

function trotter(n) {
  var tracker = [];
  var sum = [];
  var snacker = n;
  for(var i = 0; tracker.length < 10; i++){
    sum = snacker.toString().split('');
    sum.forEach(function(num) {
        if (tracker.indexOf(num) == -1) {
             tracker.push(num);
        }
    });
    snacker += n;
  }
  return tracker.length === 10 ? snacker - n : "INSOMNIA";
}


问:
find and replace string in a file
I'm trying to find and replace a string in a folder of files.

Could someone possibly help me?

My script is as follows:

```<code>#!/bin/bash
OLD="This is a"
NEW="I am a"
DPATH="/home/user/test/*.txt"
BPATH="/home/user/test/backup/foo"
[ ! -d $BPATH ] && mkdir -p $BPATH || :
for f in $DPATH
do
  if [ -f $f -a -r $f ]; then
    /bin/cp -f $f $BPATH
    sed "s/$OLD/$NEW/g" "$f"
   else
    echo "Error: Cannot read $f"
  fi
done
</code>```

Now this seems to find the string 'This is a' and replaces with 'I am a', but this only prints to screen.

I need it to replace in the files themselves.

Thanks

答:
this is a snippet i use, it removes all stuff between APA and BEPA (across multiple lines, including removing APA, BEPA) in all files below current directory, exclude the .svn directory</p>

```<code>find . \! -path '*.svn*' -type f -exec sed -i -n '1h;1!H;${;g;s/APA[ \t\r\n]*BEPA//g;p}' {} \;
</code>```

Title: find and replace string in a file

Body:
I'm trying to find and replace a string in a folder of files.

Could someone possibly help me?

My script is as follows:

#!/bin/bash
OLD="This is a"
NEW="I am a"
DPATH="/home/user/test/*.txt"
BPATH="/home/user/test/backup/foo"
[ ! -d $BPATH ] && mkdir -p $BPATH || :
for f in $DPATH
do
  if [ -f $f -a -r $f ]; then
    /bin/cp -f $f $BPATH
    sed "s/$OLD/$NEW/g" "$f"
   else
    echo "Error: Cannot read $f"
  fi
done

Now this seems to find the string 'This is a' and replaces with 'I am a', but this only prints to screen.

I need it to replace in the files themselves.

Thanks

Body:
this is a snippet i use, it removes all stuff between APA and BEPA (across multiple lines, including removing APA, BEPA) in all files below current directory, exclude the .svn directory

find . \! -path '*.svn*' -type f -exec sed -i -n '1h;1!H;${;g;s/APA[ \t\r\n]*BEPA//g;p}' {} \;