问:
CORS on .Net Core API returns 401 Unauthorized from axios request
What I'm trying to do

I want to send a PATCH request to my API from a React frontend. The API uses Identity Server 4 for validation of the request.

What's happening

The request works and goes through the controller from POSTMAN but it doesn't when it's coming from my frontend. It throws an Unauthorized response when it's coming from the axios request.

Additional note, the get request works great from the frontend. The get methods are also protected by Identity Server

Postman request

```<code>http://localhost:90909/api/products/3434

    Headers =  {
       Authorization: Bearer <token>
       Content-Type: application/json-patch+json
    }

    Body:
    [
        {
         "op" : "replace",
         "path" : "/DESCRIPTION",
         "value" : "bruhhh"
        }
    ]
</code>```

React

```<code> static update(data){
            let config = {
                data : [],
                headers: {
                    'Authorization' : 'Bearer ' + data.access_token,
                    'Content-Type' : 'application/json-patch+json'
                }
            }

            config.data.push(
                    {
                     "op" : "replace",
                     "path" : "/DESCRIPTION",
                     "value" : "you da best"
                    }

            )

            return axios.patch(root + '/api/products/' + data.product.id, config);

    }
</code>```

CORS setup

```<code>services.AddCors(options =>
            {

                options.AddPolicy("JSClient", builder =>
                    builder.WithOrigins("http://localhost:9999")
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .AllowCredentials());
            });
</code>```

Logs

I have enabled a few logs. Here's some that I already posted from a few days ago

And below is what I got from now

Preflight

The following error seems to happen during the pre flight check of CORS.

```<code>System.InvalidOperationException: Writing to the response body is invalid for responses with status code 204.
   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.Frame.HandleNonBodyResponseWrite()
   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.Frame.<WriteAsyncAwaited>d__199.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at InventoryApi.Utilities.AnotherLoggingMiddleware.<Invoke>d__3.MoveNext() in F:\My Site Projects\TestProjects\InventoryApi\AnotherLoggingMiddleware.cs:line 43
Exception thrown: 'System.InvalidOperationException' in InventoryApi.dll
Application Insights Telemetry (unconfigured): {"name":"Microsoft.ApplicationInsights.Dev.Message","time":"2017-11-15T03:42:56.0180842Z","tags":{"ai.internal.nodeName":"yay-PC","ai.operation.id":"0HL9BRASKOUFU:00000003","ai.application.ver":"1.0.0.0","ai.internal.sdkVersion":"aspnet5c:2.0.0","ai.operation.name":"OPTIONS /api/products/1020","ai.location.ip":"127.0.0.1","ai.cloud.roleInstance":"yay-PC"},"data":{"baseType":"MessageData","baseData":{"ver":2,"message":"An unhandled exception has occurred while executing the request","severityLevel":"Error","properties":{"{OriginalFormat}":"An unhandled exception has occurred while executing the request","DeveloperMode":"true","CategoryName":"Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware","AspNetCoreEnvironment":"Development","Exception":"System.InvalidOperationException: Writing to the response body is invalid for responses with status code 204.\r\n   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.Frame.HandleNonBodyResponseWrite()\r\n   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.Frame.<WriteAsyncAwaited>d__199.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at InventoryApi.Utilities.AnotherLoggingMiddleware.<Invoke>d__3.MoveNext() in F:\\My Site Projects\\TestProjects\\InventoryApi\\AnotherLoggingMiddleware.cs:line 51\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.<Invoke>d__7.MoveNext()"}}}}
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware:Error: An unhandled exception has occurred while executing the request
</code>```

I checked the networking tab of the browser and I get a 204 and then immediately get a 401 after it sends the request again after the preflight request.

This is the 204

```<code>General
Request URL:http://localhost:90909/api/products/1020
Request Method:OPTIONS
Status Code:204 No Content
Remote Address:[::1]:90909
Referrer Policy:no-referrer-when-downgrade
Response:
Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:content-type
Access-Control-Allow-Methods:PATCH
Access-Control-Allow-Origin:http://localhost:99999
Date:Wed, 15 Nov 2017 04:24:24 GMT
Server:Kestrel
X-Powered-By:ASP.NET
X-SourceFiles:=?UTF-8?B?RjpcTXkgU2l0ZSBQcm9qZWN0c1xUZXN0UHJvamVjdHasdfaseemVudG9yeUFwaVxhcGlccHJvZHVjdHNcMTAyMA==?=
Request Header:
Accept:*/*
Accept-Encoding:gzip, deflate, br
Accept-Language:en-US,en;q=0.9
Access-Control-Request-Headers:content-type
Access-Control-Request-Method:PATCH
Connection:keep-alive
Host:localhost:90909
Origin:http://localhost:99999
User-Agent:Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36
</code>```

This is the 401 response for the request after the preflight

```<code>General
Request URL:http://localhost:90909/api/products/1020
Request Method:PATCH
Status Code:401 Unauthorized
Remote Address:[::1]:90909
Referrer Policy:no-referrer-when-downgrade
Response Header
Access-Control-Allow-Credentials:true
Access-Control-Allow-Origin:http://localhost:99999
Content-Length:0
Date:Wed, 15 Nov 2017 04:24:24 GMT
Server:Kestrel
X-Powered-By:ASP.NET
X-SourceFiles:=?UTF-8?B?RjpcTXkgU2l0ZSBQcm9qZWN0c1xUZXN0UHJvamVjdHasdfaseemVudG9yeUFwaVxhcGlccHJvZHVjdHNcMTAyMA==?=
Request Header
Accept:application/json, text/plain, */*
Accept-Encoding:gzip, deflate, br
Accept-Language:en-US,en;q=0.9
Connection:keep-alive
Content-Length:850
Content-Type:application/json;charset=UTF-8
Host:localhost:90909
Origin:http://localhost:99999
Referer:http://localhost:99999/inventory/products
User-Agent:Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36
Request Payload
{data: [{op: "replace", path: "/DESCRIPTION", value: "you da best"}], headers: {,…}}
data
:
[{op: "replace", path: "/DESCRIPTION", value: "you da best"}]
headers
:
{,…}
</code>```

答:
The server which is getting the request needs to have access enabled.

For example, on an apache server, in the configuration file add the Header set Access-Control-Allow-Origin:

```<code><Directory />
        Header set Access-Control-Allow-Origin "http://ipaddress:[port]"
</Directory>
</code>```

Where the origin is wherever react is being served from....

Postman, most likely, is configured to allow any origin to access...

https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

Body:
What I'm trying to do

I want to send a PATCH request to my API from a React frontend. The API uses Identity Server 4 for validation of the request.

What's happening

The request works and goes through the controller from POSTMAN but it doesn't when it's coming from my frontend. It throws an Unauthorized response when it's coming from the axios request.

Additional note, the get request works great from the frontend. The get methods are also protected by Identity Server

Postman request

http://localhost:90909/api/products/3434

    Headers =  {
       Authorization: Bearer <token>
       Content-Type: application/json-patch+json
    }

    Body:
    [
        {
         "op" : "replace",
         "path" : "/DESCRIPTION",
         "value" : "bruhhh"
        }
    ]

React

 static update(data){
            let config = {
                data : [],
                headers: {
                    'Authorization' : 'Bearer ' + data.access_token,
                    'Content-Type' : 'application/json-patch+json'
                }
            }

            config.data.push(
                    {
                     "op" : "replace",
                     "path" : "/DESCRIPTION",
                     "value" : "you da best"
                    }

            )

            return axios.patch(root + '/api/products/' + data.product.id, config);

    }

CORS setup

services.AddCors(options =>
            {

                options.AddPolicy("JSClient", builder =>
                    builder.WithOrigins("http://localhost:9999")
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .AllowCredentials());
            });

Logs

I have enabled a few logs. Here's some that I already posted from a few days ago

And below is what I got from now

Preflight

The following error seems to happen during the pre flight check of CORS.

System.InvalidOperationException: Writing to the response body is invalid for responses with status code 204.
   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.Frame.HandleNonBodyResponseWrite()
   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.Frame.<WriteAsyncAwaited>d__199.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at InventoryApi.Utilities.AnotherLoggingMiddleware.<Invoke>d__3.MoveNext() in F:\My Site Projects\TestProjects\InventoryApi\AnotherLoggingMiddleware.cs:line 43
Exception thrown: 'System.InvalidOperationException' in InventoryApi.dll
Application Insights Telemetry (unconfigured): {"name":"Microsoft.ApplicationInsights.Dev.Message","time":"2017-11-15T03:42:56.0180842Z","tags":{"ai.internal.nodeName":"yay-PC","ai.operation.id":"0HL9BRASKOUFU:00000003","ai.application.ver":"1.0.0.0","ai.internal.sdkVersion":"aspnet5c:2.0.0","ai.operation.name":"OPTIONS /api/products/1020","ai.location.ip":"127.0.0.1","ai.cloud.roleInstance":"yay-PC"},"data":{"baseType":"MessageData","baseData":{"ver":2,"message":"An unhandled exception has occurred while executing the request","severityLevel":"Error","properties":{"{OriginalFormat}":"An unhandled exception has occurred while executing the request","DeveloperMode":"true","CategoryName":"Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware","AspNetCoreEnvironment":"Development","Exception":"System.InvalidOperationException: Writing to the response body is invalid for responses with status code 204.\r\n   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.Frame.HandleNonBodyResponseWrite()\r\n   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.Frame.<WriteAsyncAwaited>d__199.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at InventoryApi.Utilities.AnotherLoggingMiddleware.<Invoke>d__3.MoveNext() in F:\\My Site Projects\\TestProjects\\InventoryApi\\AnotherLoggingMiddleware.cs:line 51\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.<Invoke>d__7.MoveNext()"}}}}
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware:Error: An unhandled exception has occurred while executing the request

I checked the networking tab of the browser and I get a 204 and then immediately get a 401 after it sends the request again after the preflight request.

This is the 204

General
Request URL:http://localhost:90909/api/products/1020
Request Method:OPTIONS
Status Code:204 No Content
Remote Address:[::1]:90909
Referrer Policy:no-referrer-when-downgrade
Response:
Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:content-type
Access-Control-Allow-Methods:PATCH
Access-Control-Allow-Origin:http://localhost:99999
Date:Wed, 15 Nov 2017 04:24:24 GMT
Server:Kestrel
X-Powered-By:ASP.NET
X-SourceFiles:=?UTF-8?B?RjpcTXkgU2l0ZSBQcm9qZWN0c1xUZXN0UHJvamVjdHasdfaseemVudG9yeUFwaVxhcGlccHJvZHVjdHNcMTAyMA==?=
Request Header:
Accept:*/*
Accept-Encoding:gzip, deflate, br
Accept-Language:en-US,en;q=0.9
Access-Control-Request-Headers:content-type
Access-Control-Request-Method:PATCH
Connection:keep-alive
Host:localhost:90909
Origin:http://localhost:99999
User-Agent:Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36

This is the 401 response for the request after the preflight

General
Request URL:http://localhost:90909/api/products/1020
Request Method:PATCH
Status Code:401 Unauthorized
Remote Address:[::1]:90909
Referrer Policy:no-referrer-when-downgrade
Response Header
Access-Control-Allow-Credentials:true
Access-Control-Allow-Origin:http://localhost:99999
Content-Length:0
Date:Wed, 15 Nov 2017 04:24:24 GMT
Server:Kestrel
X-Powered-By:ASP.NET
X-SourceFiles:=?UTF-8?B?RjpcTXkgU2l0ZSBQcm9qZWN0c1xUZXN0UHJvamVjdHasdfaseemVudG9yeUFwaVxhcGlccHJvZHVjdHNcMTAyMA==?=
Request Header
Accept:application/json, text/plain, */*
Accept-Encoding:gzip, deflate, br
Accept-Language:en-US,en;q=0.9
Connection:keep-alive
Content-Length:850
Content-Type:application/json;charset=UTF-8
Host:localhost:90909
Origin:http://localhost:99999
Referer:http://localhost:99999/inventory/products
User-Agent:Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36
Request Payload
{data: [{op: "replace", path: "/DESCRIPTION", value: "you da best"}], headers: {,…}}
data
:
[{op: "replace", path: "/DESCRIPTION", value: "you da best"}]
headers
:
{,…}

Body:
The server which is getting the request needs to have access enabled.

For example, on an apache server, in the configuration file add the Header set Access-Control-Allow-Origin:

<Directory />
        Header set Access-Control-Allow-Origin "http://ipaddress:[port]"
</Directory>

Where the origin is wherever react is being served from....

Postman, most likely, is configured to allow any origin to access...

https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS


来源: stackexchange

问:
PixiJS: Load custom font
i am currently learning Pixijs.
I went through the tutorial of this guy: github.com/kittykatattack/learningPixi
Nice one btw.

Environement:
Xampp, Firefox, Pixijs, HTML, CSS

Now I try to load a custom font.
The first time I load the Page where my Pixijs project should run, the fonts are not showing up and the console shows some error messages...
The second time I load the page (without deleting the cache) the text is showing up with the given font!

Why?!

Here are the snippets for loading the font:

index.html:

```<code><head>
    <meta charset='UTF-8' />
    <style>
        @font-face{
            font-family: "FFFForward";
            src: url("assets/fonts/fffforward.TTF");
        }

        * {padding: 0; margin: 0}
    </style>
</code>```

app.js:

```<code>function DrawText(){

PointsTopText = new Text(
    "P1: " + PointsTop,
    {fontFamily: 'FFFForward, Arial', fontSize: 32, fill: 'white'}
);
PointsBotText = new Text(
    "Cpu: " + PointsBot,
    {fontFamily: 'FFFForward, Arial', fontSize: 32, fill: 'white'}
);

PointsTopText.position.set(0, Renderer.height / 2 - 32 * 2);
PointsBotText.position.set(0, Renderer.height / 2);

World.addChild(PointsTopText);
World.addChild(PointsBotText);
}
</code>```

Here is the error log of the console:

console:

```<code>downloadable font: bad search range (font-family: "FFFForward" style:normal weight:normal stretch:normal src index:0) source: [path]/assets/fonts/fffforward.TTF  PixiJs:6:14
downloadable font: bad range shift (font-family: "FFFForward" style:normal weight:normal stretch:normal src index:0) source: [path]/assets/fonts/fffforward.TTF  PixiJs:6:14
downloadable font: cmap: bad id_range_offset (font-family: "FFFForward" style:normal weight:normal stretch:normal src index:0) source: [path]/assets/fonts/fffforward.TTF  PixiJs:6:14
downloadable font: hdmx: the table should not be present when bit 2 and 4 of the head->flags are not set (font-family: "FFFForward" style:normal weight:normal stretch:normal src index:0) source: [path]/assets/fonts/fffforward.TTF  PixiJs:6:14
downloadable font: hdmx: Table discarded (font-family: "FFFForward" style:normal weight:normal stretch:normal src index:0) source: [path]/assets/fonts/fffforward.TTF  PixiJs:6:14
</code>```

As i said, this message appears only the very first time i load my page.
The second time everything is fine.

What can i do to prevent this?

Why does this happen?

What is the meaning of this?

答:
Use webfontloader - https://github.com/typekit/webfontloader - to synchronously load your fonts before you do any drawing in PixiJS. This also works with other canvas-based apps.

Put the following in the  section of your HTML page:

```<code><script src="https://ajax.googleapis.com/ajax/libs/webfont/1.6.26/webfont.js"></script>
<script>
    WebFont.load({
        google: {
            families: ['Press Start 2P']
        },
        active:e=>{
            console.log("font loaded!");
            // now start setting up your PixiJS (or canvas) stuff!
        }
    });
</script>
</code>```

ContentLicense: CC BY-SA 4.0

Title: PixiJS: Load custom font

Body:
i am currently learning Pixijs.
I went through the tutorial of this guy: github.com/kittykatattack/learningPixi
Nice one btw.

Environement:
Xampp, Firefox, Pixijs, HTML, CSS

Now I try to load a custom font.
The first time I load the Page where my Pixijs project should run, the fonts are not showing up and the console shows some error messages...
The second time I load the page (without deleting the cache) the text is showing up with the given font!

Why?!

Here are the snippets for loading the font:

index.html:

    <meta charset='UTF-8' />

app.js:

function DrawText(){

PointsTopText = new Text(
    "P1: " + PointsTop,
    {fontFamily: 'FFFForward, Arial', fontSize: 32, fill: 'white'}
);
PointsBotText = new Text(
    "Cpu: " + PointsBot,
    {fontFamily: 'FFFForward, Arial', fontSize: 32, fill: 'white'}
);

PointsTopText.position.set(0, Renderer.height / 2 - 32 * 2);
PointsBotText.position.set(0, Renderer.height / 2);

World.addChild(PointsTopText);
World.addChild(PointsBotText);
}

Here is the error log of the console:

console:

downloadable font: bad search range (font-family: "FFFForward" style:normal weight:normal stretch:normal src index:0) source: [path]/assets/fonts/fffforward.TTF  PixiJs:6:14
downloadable font: bad range shift (font-family: "FFFForward" style:normal weight:normal stretch:normal src index:0) source: [path]/assets/fonts/fffforward.TTF  PixiJs:6:14
downloadable font: cmap: bad id_range_offset (font-family: "FFFForward" style:normal weight:normal stretch:normal src index:0) source: [path]/assets/fonts/fffforward.TTF  PixiJs:6:14
downloadable font: hdmx: the table should not be present when bit 2 and 4 of the head->flags are not set (font-family: "FFFForward" style:normal weight:normal stretch:normal src index:0) source: [path]/assets/fonts/fffforward.TTF  PixiJs:6:14
downloadable font: hdmx: Table discarded (font-family: "FFFForward" style:normal weight:normal stretch:normal src index:0) source: [path]/assets/fonts/fffforward.TTF  PixiJs:6:14

As i said, this message appears only the very first time i load my page.
The second time everything is fine.

What can i do to prevent this?

Why does this happen?

What is the meaning of this?

Body:
Use webfontloader - https://github.com/typekit/webfontloader - to synchronously load your fonts before you do any drawing in PixiJS. This also works with other canvas-based apps.

Put the following in the <head> section of your HTML page:

<script src="https://ajax.googleapis.com/ajax/libs/webfont/1.6.26/webfont.js"></script>
<script>
    WebFont.load({
        google: {
            families: ['Press Start 2P']
        },
        active:e=>{
            console.log("font loaded!");
            // now start setting up your PixiJS (or canvas) stuff!
        }
    });
</script>

ContentLicense: CC BY-SA 3.0


答:
If you're programmatically parsing the output of svn commands, you'll probably want to use the --xml switch:

```<code>svn log --xml
</code>```

When using this format, the date (in particular) is in standard ISO 8601 format:

```<code><date>2010-12-06T20:58:35.698893Z</date>
</code>```

ContentLicense: CC BY-SA 2.5

Title: Output of svn log -v

Body:
I just wonna know if the output of the command svn log -v is always the same. For me it looks like:

------------------------------------------------------------------------
r2 | username | 2011-01-16 16:52:23 +0100 (Sun, 16 Jan 2011) | 1 line
Changed paths:
   D /foo
Removed foo
------------------------------------------------------------------------
r1 | balzarot | 2011-01-16 16:51:03 +0100 (Sun, 16 Jan 2011) | 1 line
Changed paths:
   A /foo
created foo
------------------------------------------------------------------------

but I don't know if it is always like that, especially the format of the date!
Can you help me please
thnx

Body:
If you're programmatically parsing the output of svn commands, you'll probably want to use the --xml switch:

svn log --xml

When using this format, the date (in particular) is in standard ISO 8601 format:

<date>2010-12-06T20:58:35.698893Z</date>


问:
Swift: Sort Array of Object Property While Keeping Order Intact
as the long name of this question suggests, I am trying to sort an array of objects by those object's properties, but I am having issues with the order in which the array is returned. Basically, my database structure has each date, in order, and then entries under ascending numbers under that date's directory. Below is a visual representation of the structure:

```<code>Balances
   -11/7/17
        -0
            -name: "Name 1 Here"
        -1
            -name: "Name 2 Here"
        -2
            -name: "Name 3 Here"
   -11/8/17
        -0
            -name: "Name 1 Here"
        -1
            -name: "Name 2 Here"
        -2
            -name: "Name 3 Here"
   -11/9/17
        -0
            -name: "Name 1 Here"
        -1
            -name: "Name 2 Here"
        -2
            -name: "Name 3 Here"
</code>```

When I retrieve the data from the database through a SingleValueEvent and add it to an array of custom objects, the data in the array for some reason gets out of order, and doesn't stay in the exact order as the data is stored in the database. To solve this problem, I tried to use the following code to order the array:

```<code>self.tableArray = self.tableArray.sorted(by: { $0.date < $1.date })

self.tableArray.sort(by: { (object1, object2) -> Bool in
    if object1.date != object2.date {
        return object1.date < object2.date
    } else {
    return object1.date < object2.date
    }
})
</code>```

The array returned after using either of the two lines of code is sorted by each object's date, but the order of each of the items under the date in the database is screwed up. I know this is kind of confusing, which is why I have included a visual representation below which I hope will help.

```<code>Original Array:

 Item 1:

  date: 11/14/17
  name: Name 1

 Item 2:

  date: 11/13/17
  name: Name 1

 Item 3:

  date: 11/13/17
  name: Name 2

 Item 4:

  date: 11/7/17
  name: Name 1

Sorted Array:

 Item 1:

  date: 11/7/17
  name: Name 1

 Item 2:

  date: 11/13/17
  name: Name 2

 Item 3:

  date: 11/13/17
  name: Name 1

 Item 4:

  date: 11/14/17
  name: Name 1
</code>```

Thanks!

答:
There could be a few reasons, the way it is serialised or sorted in storage - without specific insight into if you're using CoreData, Real, SQLite or other...

TL; DR, if you want to ensure the order is exactly as per what you want, and it looks like you have multiple sorting criteria, define that criteria as an attribute. You cannot always guarantee persistence will maintain the ordering, so build it into the schema.

I.e.

```<code>{name, date}
</code>```

Add an extra attribute

```<code>{name, date, order}.
</code>```

The order property can be globally unique or just unique within items of that date.

You can either sort twice (with the second sort being stable), or  better yet define a comparison that first compares by date, and then by the other.

```<code>self.tableArray.sort(by: { (object1, object2) -> Bool in
    if object1.date != object2.date {
        return object1.date < object2.date
    } else {
        return object1.order < object2.order
    }
})
</code>```

Body:
as the long name of this question suggests, I am trying to sort an array of objects by those object's properties, but I am having issues with the order in which the array is returned. Basically, my database structure has each date, in order, and then entries under ascending numbers under that date's directory. Below is a visual representation of the structure:

Balances
   -11/7/17
        -0
            -name: "Name 1 Here"
        -1
            -name: "Name 2 Here"
        -2
            -name: "Name 3 Here"
   -11/8/17
        -0
            -name: "Name 1 Here"
        -1
            -name: "Name 2 Here"
        -2
            -name: "Name 3 Here"
   -11/9/17
        -0
            -name: "Name 1 Here"
        -1
            -name: "Name 2 Here"
        -2
            -name: "Name 3 Here"

When I retrieve the data from the database through a SingleValueEvent and add it to an array of custom objects, the data in the array for some reason gets out of order, and doesn't stay in the exact order as the data is stored in the database. To solve this problem, I tried to use the following code to order the array:

self.tableArray = self.tableArray.sorted(by: { $0.date < $1.date })

self.tableArray.sort(by: { (object1, object2) -> Bool in
    if object1.date != object2.date {
        return object1.date < object2.date
    } else {
    return object1.date < object2.date
    }
})

The array returned after using either of the two lines of code is sorted by each object's date, but the order of each of the items under the date in the database is screwed up. I know this is kind of confusing, which is why I have included a visual representation below which I hope will help.

Original Array:

 Item 1:

  date: 11/14/17
  name: Name 1

 Item 2:

  date: 11/13/17
  name: Name 1

 Item 3:

  date: 11/13/17
  name: Name 2

 Item 4:

  date: 11/7/17
  name: Name 1

Sorted Array:

 Item 1:

  date: 11/7/17
  name: Name 1

 Item 2:

  date: 11/13/17
  name: Name 2

 Item 3:

  date: 11/13/17
  name: Name 1

 Item 4:

  date: 11/14/17
  name: Name 1

Thanks!

Body:
There could be a few reasons, the way it is serialised or sorted in storage - without specific insight into if you're using CoreData, Real, SQLite or other...

TL; DR, if you want to ensure the order is exactly as per what you want, and it looks like you have multiple sorting criteria, define that criteria as an attribute. You cannot always guarantee persistence will maintain the ordering, so build it into the schema.

I.e.

{name, date}

Add an extra attribute

{name, date, order}.

The order property can be globally unique or just unique within items of that date.

You can either sort twice (with the second sort being stable), or  better yet define a comparison that first compares by date, and then by the other.

self.tableArray.sort(by: { (object1, object2) -> Bool in
    if object1.date != object2.date {
        return object1.date < object2.date
    } else {
        return object1.order < object2.order
    }
})


问:
Can PHP trigger an event on a remote Windows Server
Is there a way for PHP to send a signal to a Windows Server to run a script?

I am writing a web application which generates database entries that are later synced by a program on a remote Windows Server.  PHP & mySQL are running on AWS.
The application on the windows server syncs the mySql database with Quickbooks.  Ideally I would like to send a signal from PHP so that if PHP has updated the database, letting the remote Windows server know which script to run to in order to initiate the sync program.  I would need to be pointed in the right direction both on the PHP commands as well as how to setup the listening service on Windows.

I was thinking if I could get Windows to listen on a specific port for a short XML file, PHP could send a password and entity ID number to identify which script to run.

Any suggestions?

Thanks!

答: I would schedule a task to read a specific file from the windows server side and from the php side you could use cron jobs. This question is too broad though and there are several approaches to that. You need to be more "code" specific.</p>


问:
How to feed results of SQL statement into a GridView, not the SQL statement itself?
This has got to be close, but it's been a long day and I'm tired now so I can;t really see what the problem is.  Basically, I have a table in SQL Server with 2 columns; one has the names of reports and the other has some SQL Scripts that I want to pass into a GridView, based on what a user selects from a ListBox.  Here is my code.

```<code>Imports System.Data.SqlClient

Public Class Form1
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Try

            Dim sqlConn As New SqlClient.SqlConnection("Data Source=EXCEL-PC\SQLEXPRESS;Initial Catalog=Test;Integrated Security=True")
            sqlConn.Open()
            Dim cmd As New SqlClient.SqlCommand("Select ReportName From [Table_1] order by ReportName", sqlConn)
            Dim dsColumns As New DataSet
            Dim daAdapter As New SqlClient.SqlDataAdapter(cmd)

            daAdapter.Fill(dsColumns)
            If dsColumns.Tables(0).Rows.Count > 0 Then
                ListBox1.Items.Clear()
                For i As Integer = 0 To dsColumns.Tables(0).Rows.Count - 1
                    ListBox1.Items.Add(dsColumns.Tables(0).Rows(i)(0).ToString())
                Next
            End If
        Catch ex As Exception
        End Try

    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim connetionString As String
        Dim SqlStr As String
        Dim connection As SqlConnection
        Dim adapter As SqlDataAdapter
        Dim ds As New DataSet
        Dim myItem As String

        connetionString = "Data Source=EXCEL-PC\SQLEXPRESS;Initial Catalog=Test;Integrated Security=True"
        connection = New SqlConnection(connetionString)
        'Dim iIndex As Integer = ListBox1.SelectedIndex
        myItem = ListBox1.SelectedItem
        SqlStr = "select SqlScript from [Table_1] Where ReportName = '" & myItem & "'"
        Try
            connection.Open()
            adapter = New SqlDataAdapter(SqlStr, connection)
            adapter.Fill(ds)
            connection.Close()
            DataGridView1.DataSource = ds.Tables(0)
        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try

    End Sub

End Class
</code>```

I guess the problem is passing the SQL to the GridView.  When I select the first Item, I see this in my GridView.

```<code>SELECT [OrderID]
      ,[CustomerID]
      ,[EmployeeID]
      ,[OrderDate]
      ,[RequiredDate]
      ,[ShippedDate]
      ,[ShipVia]
      ,[Freight]
      ,[ShipName]
      ,[ShipAddress]
      ,[ShipCity]
      ,[ShipRegion]
      ,[ShipPostalCode]
      ,[ShipCountry]
  FROM [Test].[dbo].[Orders]
</code>```

That's pretty close, but I want to get that SQL fed into the GridView, and get the results of the SQL displayed in the GridView, not eh SQL statement itself.

This is what I see now.

I want to see something more like this.

Finally, I am curious to know of the GridView can be made dynamic, so if I stretch out the window the GridView shows more columns.  Now, if I stretch out the form window, the GridView stays static.

答:
You need to actually run the retrieved Sql statement:

```<code>sqlstr = "select SqlScript from [Table_1] Where ReportName = '" & myItem & "'"
Try
  connection.Open()
  Dim cmd As New SqlCommand(sqlstr, connection)
  Dim sqlstr_report As String = CStr(cmd.ExecuteScalar())
  cmd.Dispose()
  adapter = New SqlDataAdapter(sqlstr_report, connection)
  adapter.Fill(ds)
  connection.Close()
  DataGridView1.DataSource = ds.Tables(0)
</code>```

Use the .Anchor property of the DataGridView to make it resize with the form

Body:
This has got to be close, but it's been a long day and I'm tired now so I can;t really see what the problem is.  Basically, I have a table in SQL Server with 2 columns; one has the names of reports and the other has some SQL Scripts that I want to pass into a GridView, based on what a user selects from a ListBox.  Here is my code.

Imports System.Data.SqlClient

Public Class Form1
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Try

            Dim sqlConn As New SqlClient.SqlConnection("Data Source=EXCEL-PC\SQLEXPRESS;Initial Catalog=Test;Integrated Security=True")
            sqlConn.Open()
            Dim cmd As New SqlClient.SqlCommand("Select ReportName From [Table_1] order by ReportName", sqlConn)
            Dim dsColumns As New DataSet
            Dim daAdapter As New SqlClient.SqlDataAdapter(cmd)

            daAdapter.Fill(dsColumns)
            If dsColumns.Tables(0).Rows.Count > 0 Then
                ListBox1.Items.Clear()
                For i As Integer = 0 To dsColumns.Tables(0).Rows.Count - 1
                    ListBox1.Items.Add(dsColumns.Tables(0).Rows(i)(0).ToString())
                Next
            End If
        Catch ex As Exception
        End Try

    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim connetionString As String
        Dim SqlStr As String
        Dim connection As SqlConnection
        Dim adapter As SqlDataAdapter
        Dim ds As New DataSet
        Dim myItem As String

        connetionString = "Data Source=EXCEL-PC\SQLEXPRESS;Initial Catalog=Test;Integrated Security=True"
        connection = New SqlConnection(connetionString)
        'Dim iIndex As Integer = ListBox1.SelectedIndex
        myItem = ListBox1.SelectedItem
        SqlStr = "select SqlScript from [Table_1] Where ReportName = '" & myItem & "'"
        Try
            connection.Open()
            adapter = New SqlDataAdapter(SqlStr, connection)
            adapter.Fill(ds)
            connection.Close()
            DataGridView1.DataSource = ds.Tables(0)
        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try

    End Sub

End Class

I guess the problem is passing the SQL to the GridView.  When I select the first Item, I see this in my GridView.

SELECT [OrderID]
      ,[CustomerID]
      ,[EmployeeID]
      ,[OrderDate]
      ,[RequiredDate]
      ,[ShippedDate]
      ,[ShipVia]
      ,[Freight]
      ,[ShipName]
      ,[ShipAddress]
      ,[ShipCity]
      ,[ShipRegion]
      ,[ShipPostalCode]
      ,[ShipCountry]
  FROM [Test].[dbo].[Orders]

That's pretty close, but I want to get that SQL fed into the GridView, and get the results of the SQL displayed in the GridView, not eh SQL statement itself.

This is what I see now.

I want to see something more like this.

Finally, I am curious to know of the GridView can be made dynamic, so if I stretch out the window the GridView shows more columns.  Now, if I stretch out the form window, the GridView stays static.

Body:
You need to actually run the retrieved Sql statement:

sqlstr = "select SqlScript from [Table_1] Where ReportName = '" & myItem & "'"
Try
  connection.Open()
  Dim cmd As New SqlCommand(sqlstr, connection)
  Dim sqlstr_report As String = CStr(cmd.ExecuteScalar())
  cmd.Dispose()
  adapter = New SqlDataAdapter(sqlstr_report, connection)
  adapter.Fill(ds)
  connection.Close()
  DataGridView1.DataSource = ds.Tables(0)

Use the .Anchor property of the DataGridView to make it resize with the form


问:
What to write so that when "enter" is pressed, then code proceeds further?
Please help me in the below code :

```<code>import java.util.Scanner;
class A
{
    public static void main(String args[])
    {
        Scanner Sc = new Scanner(System.in);
        System.out.print("Enter first number : ");
        a = Sc.nextInt();
        System.out.print("Enter second number : ");
        b = Sc.nextInt();
        System.out.print("Sum is : " + (a + b));
        System.out.print("Press enter to continue...");
        /* HERE IS MY DOUBT */
        /* WHAT TO WRITE HERE SO THAT WHEN "ENTER" IS PRESSED THEN CODE PROCEEDS */
    }
}
</code>```

Like in C language we can use getch() to hold a program. Is there something similar in Java too?

I have already tried Sc.nextLine(). The problem with Sc.nextLine() is that, in it first I have to enter a value and then press enter and then the code proceeds.
But what I want is to just press enter and proceed.

答:
Do the following,

```<code>public static void main(String args[]) {
    //your code...

    while (true) {

        System.out.println("press enter to exit...");
        String keyPressed = sc.nextLine();
        sc.nextLine();

        if (keyPressed.isEmpty()) break;
    }
}
</code>```

Hope this your work!

Body:
Please help me in the below code :

import java.util.Scanner;
class A
{
    public static void main(String args[])
    {
        Scanner Sc = new Scanner(System.in);
        System.out.print("Enter first number : ");
        a = Sc.nextInt();
        System.out.print("Enter second number : ");
        b = Sc.nextInt();
        System.out.print("Sum is : " + (a + b));
        System.out.print("Press enter to continue...");
        /* HERE IS MY DOUBT */
        /* WHAT TO WRITE HERE SO THAT WHEN "ENTER" IS PRESSED THEN CODE PROCEEDS */
    }
}

Like in C language we can use getch() to hold a program. Is there something similar in Java too?

I have already tried Sc.nextLine(). The problem with Sc.nextLine() is that, in it first I have to enter a value and then press enter and then the code proceeds.
But what I want is to just press enter and proceed.

Body:
Do the following,

public static void main(String args[]) {
    //your code...

    while (true) {

        System.out.println("press enter to exit...");
        String keyPressed = sc.nextLine();
        sc.nextLine();

        if (keyPressed.isEmpty()) break;
    }
}

Hope this your work!


答:
I think this will work for a single key stroke event

```<code>public class EnterKeyEvent {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.println("Press a key");
        String entry = sc.nextLine();
        if(!"".equals(entry)) {
            System.out.println("Enter key not pressed");
        }
        else {
            System.out.println("Enter key pressed");
        }
    }
}
</code>```

Like if you press Enter key then else block will be executed, but if Enter key is pressed after pressing some other key [like asdf and then Enter key] if block will be executed.

When I tried this code I was expecting the value of entry to come as \n but it was getting an empty String value. And that's what I did in the code.

Title: What to write so that when "enter" is pressed, then code proceeds further?

Body:
I think this will work for a single key stroke event

public class EnterKeyEvent {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.println("Press a key");
        String entry = sc.nextLine();
        if(!"".equals(entry)) {
            System.out.println("Enter key not pressed");
        }
        else {
            System.out.println("Enter key pressed");
        }
    }
}

Like if you press Enter key then else block will be executed, but if Enter key is pressed after pressing some other key [like asdf and then Enter key] if block will be executed.

When I tried this code I was expecting the value of entry to come as \n but it was getting an empty String value. And that's what I did in the code.


问:
Looking for a drop-in replacement for a java.util.Map

Problem

Following up on this question, it seems that a file- or disk-based Map implementation may be the right solution to the problems I mentioned there. Short version:

Right now, I have a Map implemented as a ConcurrentHashMap.

Entries are added to it continually, at a fairly fixed rate. Details on this later.

Eventually, no matter what, this means the JVM runs out of heap space.

At work, it was (strongly) suggested that I solve this problem using SQLite, but after asking that previous question, I don't think that a database is the right tool for this job. So - let me know if this sounds crazy - I think a better solution would be a Map stored on disk.

Bad idea: implement this myself. Better idea: use someone else's library! Which one?

Requirements

Must-haves:

Free.

Persistent. The data needs to stick around between JVM restarts.

Some sort of searchability. Yes, I need the ability to retrieve this darn data as well as put it away. Basic result set filtering is a plus.

Platform-independent. Needs to be production-deployable on Windows or Linux machines.

Purgeable. Disk space is finite, just like heap space. I need to get rid of entries that are n days old. It's not a big deal if I have to do this manually.

Nice-to-haves:

Easy to use. It would be great if I could get this working by the end of the week.

Better still: the end of the day. It would be really, really great if I could add one JAR to my classpath, change new ConcurrentHashMap<Foo, Bar>(); to new SomeDiskStoredMap<Foo, Bar>();

and be done.

Decent scalability and performance. Worst case: new entries are added (on average) 3 times per second, every second, all day long, every day. However, inserts won't always happen that smoothly. It might be (no inserts for an hour) then (insert 10,000 objects at once).

Possible Solutions

Ehcache? I've never used it before. It was a suggested solution to my previous question.

Berkeley DB? Again, I've never used it, and I really don't know anything about it.

Hadoop (and which subproject)? Haven't used it. Based on these docs, its cross-platform-readiness is ambiguous to me. I don't need distributed operation in the foreseeable future.

A SQLite JDBC driver after all?

???

Ehcache and Berkeley DB both look reasonable right now. Any particular recommendations in either direction?

答:
The google-collections library, part of http://code.google.com/p/guava-libraries/, has some really useful Map tools. MapMaker in particular lets you make concurrent HashMaps with timed evictions, soft values that will be swept up by the garbage collector if you're running out of heap, and computing functions.

```<code>Map<String, String> cache = new MapMaker()
    .softValues()
    .expiration(30, TimeUnit.MINUTES)
    .makeComputingMap(new Function<String, String>() {
        @Override
        public String apply(String input) {
            // Work out what the value should be
            return null;
        }
    });
</code>```

That will give you a Map cache that will clean up after itself and can work out its values. If you're able to compute values like that then great, otherwise it would map perfectly onto http://redis.io/ which you'd be writing into (to be fair, redis would probably be fast enough on its own!).

Body:
The google-collections library, part of http://code.google.com/p/guava-libraries/, has some really useful Map tools. MapMaker in particular lets you make concurrent HashMaps with timed evictions, soft values that will be swept up by the garbage collector if you're running out of heap, and computing functions.

Map<String, String> cache = new MapMaker()
    .softValues()
    .expiration(30, TimeUnit.MINUTES)
    .makeComputingMap(new Function<String, String>() {
        @Override
        public String apply(String input) {
            // Work out what the value should be
            return null;
        }
    });

That will give you a Map cache that will clean up after itself and can work out its values. If you're able to compute values like that then great, otherwise it would map perfectly onto http://redis.io/ which you'd be writing into (to be fair, redis would probably be fast enough on its own!).


问:
Radiobutton only works on one form and other form can not
I am trying to modify the input style of the input type radio and I have the radio input in two different forms. but the radio input only works on the first form only while the second does not. I am still confused by the problem why not work on the second.

Please help me. Thanks in advance

ex : https://jsfiddle.net/devefrontend/vaqdsmjk/10/

```<code><input type="radio" name="roundtrip" id="oneway" value="oneway" checked="">
<label for="oneway">Oneway</label>
</code>```

[type="radio"]:checked,
[type="radio"]:not(:checked) {
  position: absolute;
  left: -9999px;
}

[type="radio"]:checked + label,
[type="radio"]:not(:checked) + label {
  position: relative;
  padding-left: 28px;
  cursor: pointer;
  line-height: 20px;
  display: inline-block;
  color: #666;
}

[type="radio"]:checked + label:before,
[type="radio"]:not(:checked) + label:before {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  width: 18px;
  height: 18px;
  border: 1px solid #ddd;
  border-radius: 100%;
  background: #fff;
}

[type="radio"]:checked + label:after,
[type="radio"]:not(:checked) + label:after {
  content: '';
  width: 12px;
  height: 12px;
  background: #F87DA9;
  position: absolute;
  top: 4px;
  left: 4px;
  border-radius: 100%;
  -webkit-transition: all 0.2s ease;
  transition: all 0.2s ease;
}

[type="radio"]:not(:checked) + label:after {
  opacity: 0;
  -webkit-transform: scale(0);
  transform: scale(0);
}

[type="radio"]:checked + label:after {
  opacity: 1;
  -webkit-transform: scale(1);
  transform: scale(1);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<div role="tabpanel" class="tab-pane active" id="flights">
  <form name="flight" method="GET" action="" id="searchFlights" class="form-inline">
    <ul class="radio-list">
      <li id="radioFlights">
        <input type="radio" name="roundtrip" id="oneway" value="oneway" checked="">
        <label for="oneway">Oneway</label>
      </li>
      <li id="radioFlights">
        <input type="radio" name="roundtrip" id="return" value="return">
        <label for="return">Return</label>
      </li>
    </ul>
  </form>
</div>
<div role="tabpanel" class="tab-pane" id="trains">
  <form name="train" method="GET" action="" id="searchTrains" class="form-inline">
    <ul class="radio-list">
      <li id="radioTrains">
        <input type="radio" name="roundtrip" id="oneway" value="oneway" checked="">
        <label for="oneway">Oneway</label>
      </li>
      <li id="radioTrains">
        <input type="radio" name="roundtrip" id="return" value="return">
        <label for="return">Return</label>
      </li>
    </ul>
  </form>
</div></code>```

答:
If I understand this correctly, you would like the first two radios in You need to set different the "searchFlights" form to work together and the other two in "searchTrain" form to work together.

If that is the case, you would need different names for the radio inputs in each form. Radios work by matching the "name" part of the input.

You could try changing each set to use a different name. For example, using "roundtripFlight"  for "searchFlights" form and "roundtripTrain" for "searchTrains" form.

```<code><div role="tabpanel" class="tab-pane active" id="flights">
  <form name="flight" method="GET" action="" id="searchFlights" class="form-inline">
    <ul class="radio-list">
      <li id="radioFlights">
        <input type="radio" name="roundtripFlight" id="oneway" value="oneway" checked="">
        <label for="oneway">Oneway</label>
      </li>
      <li id="radioFlights">
        <input type="radio" name="roundtripFlight" id="return" value="return">
        <label for="return">Return</label>
      </li>
    </ul>
  </form>
</div>
<div role="tabpanel" class="tab-pane" id="trains">
  <form name="train" method="GET" action="" id="searchTrains" class="form-inline">
    <ul class="radio-list">
      <li id="radioTrains">
        <input type="radio" name="roundtripTrain" id="oneway" value="oneway" checked="">
        <label for="oneway">Oneway</label>
      </li>
      <li id="radioTrains">
        <input type="radio" name="roundtripTrain" id="return" value="return">
        <label for="return">Return</label>
      </li>
    </ul>
  </form>
</div>
</code>```

Body:
I am trying to modify the input style of the input type radio and I have the radio input in two different forms. but the radio input only works on the first form only while the second does not. I am still confused by the problem why not work on the second.

Please help me. Thanks in advance

ex : https://jsfiddle.net/devefrontend/vaqdsmjk/10/

<input type="radio" name="roundtrip" id="oneway" value="oneway" checked="">
Oneway

[type="radio"]:checked,
[type="radio"]:not(:checked) {
  position: absolute;
  left: -9999px;
}

[type="radio"]:checked + label,
[type="radio"]:not(:checked) + label {
  position: relative;
  padding-left: 28px;
  cursor: pointer;
  line-height: 20px;
  display: inline-block;
  color: #666;
}

[type="radio"]:checked + label:before,
[type="radio"]:not(:checked) + label:before {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  width: 18px;
  height: 18px;
  border: 1px solid #ddd;
  border-radius: 100%;
  background: #fff;
}

[type="radio"]:checked + label:after,
[type="radio"]:not(:checked) + label:after {
  content: '';
  width: 12px;
  height: 12px;
  background: #F87DA9;
  position: absolute;
  top: 4px;
  left: 4px;
  border-radius: 100%;
  -webkit-transition: all 0.2s ease;
  transition: all 0.2s ease;
}

[type="radio"]:not(:checked) + label:after {
  opacity: 0;
  -webkit-transform: scale(0);
  transform: scale(0);
}

[type="radio"]:checked + label:after {
  opacity: 1;
  -webkit-transform: scale(1);
  transform: scale(1);
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

  <form name="flight" method="GET" action="" id="searchFlights" class="form-inline">

        <input type="radio" name="roundtrip" id="oneway" value="oneway" checked="">
        Oneway

        <input type="radio" name="roundtrip" id="return" value="return">
        Return

  </form>

  <form name="train" method="GET" action="" id="searchTrains" class="form-inline">

        <input type="radio" name="roundtrip" id="oneway" value="oneway" checked="">
        Oneway

        <input type="radio" name="roundtrip" id="return" value="return">
        Return

  </form>

Body:
If I understand this correctly, you would like the first two radios in You need to set different the "searchFlights" form to work together and the other two in "searchTrain" form to work together.

If that is the case, you would need different names for the radio inputs in each form. Radios work by matching the "name" part of the input.

You could try changing each set to use a different name. For example, using "roundtripFlight"  for "searchFlights" form and "roundtripTrain" for "searchTrains" form.

<div role="tabpanel" class="tab-pane active" id="flights">
  <form name="flight" method="GET" action="" id="searchFlights" class="form-inline">
    <ul class="radio-list">
      <li id="radioFlights">
        <input type="radio" name="roundtripFlight" id="oneway" value="oneway" checked="">
        <label for="oneway">Oneway</label>
      </li>
      <li id="radioFlights">
        <input type="radio" name="roundtripFlight" id="return" value="return">
        <label for="return">Return</label>
      </li>
    </ul>
  </form>
</div>
<div role="tabpanel" class="tab-pane" id="trains">
  <form name="train" method="GET" action="" id="searchTrains" class="form-inline">
    <ul class="radio-list">
      <li id="radioTrains">
        <input type="radio" name="roundtripTrain" id="oneway" value="oneway" checked="">
        <label for="oneway">Oneway</label>
      </li>
      <li id="radioTrains">
        <input type="radio" name="roundtripTrain" id="return" value="return">
        <label for="return">Return</label>
      </li>
    </ul>
  </form>
</div>


问:
Individual plots worked but once added subplot, nothing shows up
I am trying to put together four subplots that are made using pandas.plot() method. When plotting separately, they show up fine as below:

But once I started using subplot, it became this:

I know there might be something to do with either naming the plot objects or using pyplot instead of the pandas .plot method, but couldn't figure out after tried different things. Any hint is appreciated.

答:
Use the ax argument.

```<code>df = pd.DataFrame({"foo":[4,5,6], "bar":[1,4,2]})

f, (ax1, ax2) = plt.subplots(2, 1, figsize=(4,3))

df.foo.plot(ax=ax1)
df.bar.plot(ax=ax2)
</code>```

Body:
Use the ax argument.

df = pd.DataFrame({"foo":[4,5,6], "bar":[1,4,2]})

f, (ax1, ax2) = plt.subplots(2, 1, figsize=(4,3))

df.foo.plot(ax=ax1)
df.bar.plot(ax=ax2)


问:
How do I change x-axis from numeric to custom ggplot?
I have data that looks like:

```<code>require(ggplot2); require(lubridate); require(data.table); require(dplyr)

Date  <- rep(seq.Date(as.Date("2014-01-01"), as.Date("2016-12-31"), by = "days"), 3)
Index <- rep(c(rep(1:365, times = 2), 1:366), 3)
Counts<- sample(1:25, size = length(Index), replace = TRUE)
City  <- rep(c("Dallas", "San Antonio", "Houston"), each = length(Index)/3)

df    <- data.frame(Date = Date, Index = Index, Counts = Counts, City = City)

df    <- df %>% mutate(Year = year(as.Date(Date)))
</code>```

I graphed the data using the following code:

```<code>ggplot(df, aes(x = Index, y = Counts, colour = City)) +
  geom_line(aes(group = City))+
  geom_vline(xintercept = c(31, 59.5, 90, 120, 151, 181, 212, 243, 273, 304, 334))+
  facet_grid(Year~.) +
  theme(legend.position = "bottom")
</code>```

My goal is to actually label the x-axis as Jan Feb ... Dec. I have tried scale_x_continuous and scale_x_discrete with no avail. Any suggestions?

Thanks in advance

答:
A quick option to make use of what you've already got is to pass your vector of x intercepts to scale_x_continuous as breaks, and use month.abb to name them:

library(tidyverse)

df <- data_frame(
    Date = rep(seq.Date(as.Date("2014-01-01"), as.Date("2016-12-31"), by = "days"), 3),
    Index = rep(c(rep(1:365, times = 2), 1:366), 3),
    Counts = sample(1:25, size = length(Index), replace = TRUE),
    City = rep(c("Dallas", "San Antonio", "Houston"), each = length(Index) / 3),
    Year = lubridate::year(Date)
)

month_breaks <- c(31, 59.5, 90, 120, 151, 181, 212, 243, 273, 304, 334)

ggplot(df, aes(x = Index, y = Counts, colour = City)) +
    geom_line() +
    geom_vline(xintercept = month_breaks) +
    scale_x_continuous(breaks = month_breaks, labels = month.abb[-1]) +
    facet_grid(Year ~ .) +
    theme(legend.position = "bottom")
```

Body:
I have data that looks like:

require(ggplot2); require(lubridate); require(data.table); require(dplyr)

Date  <- rep(seq.Date(as.Date("2014-01-01"), as.Date("2016-12-31"), by = "days"), 3)
Index <- rep(c(rep(1:365, times = 2), 1:366), 3)
Counts<- sample(1:25, size = length(Index), replace = TRUE)
City  <- rep(c("Dallas", "San Antonio", "Houston"), each = length(Index)/3)

df    <- data.frame(Date = Date, Index = Index, Counts = Counts, City = City)

df    <- df %>% mutate(Year = year(as.Date(Date)))

I graphed the data using the following code:

ggplot(df, aes(x = Index, y = Counts, colour = City)) +
  geom_line(aes(group = City))+
  geom_vline(xintercept = c(31, 59.5, 90, 120, 151, 181, 212, 243, 273, 304, 334))+
  facet_grid(Year~.) +
  theme(legend.position = "bottom")

My goal is to actually label the x-axis as Jan Feb ... Dec. I have tried scale_x_continuous and scale_x_discrete with no avail. Any suggestions?

Thanks in advance


问:
Unable to create shader program OpenGL LWJGL3
I am unable to create a shader program to bind to the program id of openGL.
my ShaderProgram class looks as follows:

```<code>public abstract class ShaderProgram {

private int programID;
private int vertexShaderID;
private int fragmentShaderID;

public ShaderProgram(String vertexFile, String fragmentFile) {                  // Constructor takes the file names for both shaders and loads them into memory
                                                                                // --- Vertex shader does points in 3d space --- fragment shader does colour ---

    if (programID == -1) {                                                      // Error checking for shader program
        programID = GL20.glCreateProgram();
    }
    if (programID == 0) {
        System.out.println("Could not create shader program");
        System.exit(-1);
    }

    vertexShaderID = loadShader(vertexFile, GL20.GL_VERTEX_SHADER);
    fragmentShaderID = loadShader(fragmentFile, GL20.GL_FRAGMENT_SHADER);

    GL20.glAttachShader(programID, vertexShaderID);                             // Bind shader to programID
    GL20.glAttachShader(programID, fragmentShaderID);
    bindAttributes();
    GL20.glLinkProgram(programID);
    GL20.glValidateProgram(programID);
}

protected abstract void bindAttributes();

protected void bindAttribute(String variableName, int attribute) {              // Takes vao to bind to vertex shader
    GL20.glBindAttribLocation(programID, attribute, variableName);

}

public void start() {                                                           // Start shader program bound to programID
    GL20.glUseProgram(programID);
}

public void stop() {                                                            // Stop shader program
    GL20.glUseProgram(0);
}

public void cleanUp() {                                                         // Unbind shaderID's and delete program from memory
    stop();
    GL20.glDetachShader(programID, vertexShaderID);
    GL20.glDetachShader(programID, fragmentShaderID);
    GL20.glDeleteShader(vertexShaderID);
    GL20.glDeleteShader(fragmentShaderID);
    GL20.glDeleteProgram(programID);
}

private int loadShader(String file, int type) {                                 // Read shader file input by filename and shader type
                                                                                //      and store it in a string buffer
    StringBuilder shaderSource = new StringBuilder();

    InputStream in = Class.class.getResourceAsStream(file);
    BufferedReader reader = new BufferedReader(new InputStreamReader(in));

    String line;
    try {
        while((line = reader.readLine()) != null) {
            shaderSource.append(line).append("//\n");
        }
        reader.close();
    } catch (IOException e) {
        e.printStackTrace();
        System.err.println("Could not Load Shader File");
        System.exit(-1);
    }

    int shaderID = GL20.glCreateShader(type);
    GL20.glShaderSource(shaderID, shaderSource);                            // Creates shader by file and loads it into a new id
    GL20.glCompileShader(shaderID);

    if (GL20.glGetShaderi(shaderID, GL20.GL_COMPILE_STATUS) == GL11.GL_FALSE) {             // Get gl compile status of shader

        System.out.println(GL20.glGetShaderInfoLog(shaderID, 1000));                // In case of error, force close and print what went wrong
        System.err.println("Could not compile shader!");
        System.exit(-1);
    }

    return shaderID;

}

}
</code>```

it is returning with a java heap error as follows:
error

I have attached a link to my github repository for all of the accompanying code.  I believe it is a mishandle with glfw.  All engine files are in the boundary package in renderEngine.  Thanks in advance!
GitHub KR0N05

答: I have solved the problem. @BDL was correct, I was not loading the context in render.prepare before I called the shader create. Thanks! </p>

Body:
I am unable to create a shader program to bind to the program id of openGL.
my ShaderProgram class looks as follows:

public abstract class ShaderProgram {

private int programID;
private int vertexShaderID;
private int fragmentShaderID;

public ShaderProgram(String vertexFile, String fragmentFile) {                  // Constructor takes the file names for both shaders and loads them into memory
                                                                                // --- Vertex shader does points in 3d space --- fragment shader does colour ---

    if (programID == -1) {                                                      // Error checking for shader program
        programID = GL20.glCreateProgram();
    }
    if (programID == 0) {
        System.out.println("Could not create shader program");
        System.exit(-1);
    }

    vertexShaderID = loadShader(vertexFile, GL20.GL_VERTEX_SHADER);
    fragmentShaderID = loadShader(fragmentFile, GL20.GL_FRAGMENT_SHADER);

    GL20.glAttachShader(programID, vertexShaderID);                             // Bind shader to programID
    GL20.glAttachShader(programID, fragmentShaderID);
    bindAttributes();
    GL20.glLinkProgram(programID);
    GL20.glValidateProgram(programID);
}

protected abstract void bindAttributes();

protected void bindAttribute(String variableName, int attribute) {              // Takes vao to bind to vertex shader
    GL20.glBindAttribLocation(programID, attribute, variableName);

}

public void start() {                                                           // Start shader program bound to programID
    GL20.glUseProgram(programID);
}

public void stop() {                                                            // Stop shader program
    GL20.glUseProgram(0);
}

public void cleanUp() {                                                         // Unbind shaderID's and delete program from memory
    stop();
    GL20.glDetachShader(programID, vertexShaderID);
    GL20.glDetachShader(programID, fragmentShaderID);
    GL20.glDeleteShader(vertexShaderID);
    GL20.glDeleteShader(fragmentShaderID);
    GL20.glDeleteProgram(programID);
}

private int loadShader(String file, int type) {                                 // Read shader file input by filename and shader type
                                                                                //      and store it in a string buffer
    StringBuilder shaderSource = new StringBuilder();

    InputStream in = Class.class.getResourceAsStream(file);
    BufferedReader reader = new BufferedReader(new InputStreamReader(in));

    String line;
    try {
        while((line = reader.readLine()) != null) {
            shaderSource.append(line).append("//\n");
        }
        reader.close();
    } catch (IOException e) {
        e.printStackTrace();
        System.err.println("Could not Load Shader File");
        System.exit(-1);
    }

    int shaderID = GL20.glCreateShader(type);
    GL20.glShaderSource(shaderID, shaderSource);                            // Creates shader by file and loads it into a new id
    GL20.glCompileShader(shaderID);

    if (GL20.glGetShaderi(shaderID, GL20.GL_COMPILE_STATUS) == GL11.GL_FALSE) {             // Get gl compile status of shader

        System.out.println(GL20.glGetShaderInfoLog(shaderID, 1000));                // In case of error, force close and print what went wrong
        System.err.println("Could not compile shader!");
        System.exit(-1);
    }

    return shaderID;

}

}

it is returning with a java heap error as follows:
error

I have attached a link to my github repository for all of the accompanying code.  I believe it is a mishandle with glfw.  All engine files are in the boundary package in renderEngine.  Thanks in advance!
GitHub KR0N05


问:
How do I show unique constraints of a table in MySQL?
I created them, but I forgot which ones they are.

I just want to

show them.

remove all the constraints on a table.

答:
This doesn't produce elegant output but is easy to remember:</p>

```<code>SHOW CREATE TABLE table_name;
</code>```

Body:
This doesn't produce elegant output but is easy to remember:

SHOW CREATE TABLE table_name;


问:
Azure Triggered Webjob - Detecting when webjob stops
I am developing a triggered webjob that use TimerTrigger.

Before the webjob stops, I need to dispose some objects but I don't know how to trigger the "webjob stop".

Having a NoAutomaticTrigger function, I know that I can use the WebJobsShutdownWatcher class to handle when the webjob is stopping but with a triggered job I need some help...

I had a look at Extensible Triggers and Binders with Azure WebJobs SDK 1.1.0-alpha1.

Is it a good idea to create a custom trigger (StopTrigger) that used the WebJobsShutdownWatcher class to fire action before the webjob stops ?

答:
I was recently trying to figure out how to do this without the
  WebJobs SDK which contains the WebJobShutdownWatcher, this is what I
  found out.

What the underlying runtime does (and what the WebJobsShutdownWatcher referenced above checks), is create a local file at the location specified by the environment variable %WEBJOBS_SHUTDOWN_FILE%. If this file exists, it is essentially the runtime's signal to the webjob that it must shutdown within a configurable wait period (default of 5 seconds for continuous jobs, 30 for triggered jobs), otherwise the runtime will kill the job.

The net effect is, if you are not using the Azure WebJobs SDK, which contains the WebJobsShutdownWatcher as described above, you can still achieve graceful shutdown of your Azure Web Job by monitoring for the shutdown file on an interval shorter than the configured wait period.

Additional details, including how to configure the wait period, are described here: https://github.com/projectkudu/kudu/wiki/WebJobs#graceful-shutdown


问:
Adding Home button in html page
In my webapplication I am trying to add home button in all the sub pages which on clicking will trigger ActionResult Index()
Any suggestions?

I have simply added a button in my Sub page DetailsForm. Which is next to the submit button. After user is done saving user can click on home button to directly got to the Index.cshtml. Avoiding any Browser back button.
Below code definitely doesn't work for me!

```<code>  <input type="button" class="btn btn-lg btn-success" onclick="location.href='index.cshtml';" value="Home" />
</code>```

答:
You can disable browser back button after saving using

```<code>history.pushState(null, null, document.title);
window.addEventListener('popstate', function () {
    history.pushState(null, null, document.title);
});
</code>```

then you can go back to your home page using the button

```<code><input type="button" class="btn btn-lg btn-success" onclick="goToHome()" value="Home" />
</code>```

and you can add function in js as

```<code> function goToHome () {
    window.location.href = "@Url.Action("Index", "ControllerName")"
};
</code>```

Title: Adding Home button in html page

Body:
In my webapplication I am trying to add home button in all the sub pages which on clicking will trigger ActionResult Index()
Any suggestions?

I have simply added a button in my Sub page DetailsForm. Which is next to the submit button. After user is done saving user can click on home button to directly got to the Index.cshtml. Avoiding any Browser back button.
Below code definitely doesn't work for me!

  <input type="button" class="btn btn-lg btn-success" onclick="location.href='index.cshtml';" value="Home" />

Body:
You can disable browser back button after saving using

history.pushState(null, null, document.title);
window.addEventListener('popstate', function () {
    history.pushState(null, null, document.title);
});

then you can go back to your home page using the button

<input type="button" class="btn btn-lg btn-success" onclick="goToHome()" value="Home" />

and you can add function in js as

 function goToHome () {
    window.location.href = "@Url.Action("Index", "ControllerName")"
};


问:
How to bind counter value to the textblock?
I'd like to be able to see the counter value in the textblock which incremented on a click of the button. I need to bind it to the textblock. I am wondering what will be the correct way to do it.

XAML:

```<code><TextBlock Text="{Binding Path=counter}" />
<Button x:Name="Nextbt" Content="Next" Click="ClickNextButton"/>
</code>```

C#:

```<code>private void ClickNextButton(object sender, System.Windows.RoutedEventArgs e){
counter += 1;
if (counter == 1)
{

}
if (counter == 2)
{

}}
</code>```

Thank you in advance.

答: Counter needs to be exposed as a public property in order for your TextBlock to bind to it. Preferably, the property should implement change notification. See MSDN's Data Binding overview for starters!

Body:
I'd like to be able to see the counter value in the textblock which incremented on a click of the button. I need to bind it to the textblock. I am wondering what will be the correct way to do it.

XAML:

<TextBlock Text="{Binding Path=counter}" />
<Button x:Name="Nextbt" Content="Next" Click="ClickNextButton"/>

C#:

private void ClickNextButton(object sender, System.Windows.RoutedEventArgs e){
counter += 1;
if (counter == 1)
{

}
if (counter == 2)
{

}}

Thank you in advance.


问:
Getting refresh token each time
I am trying to get the refresh token every time the following uri is called,

```<code>String link = "https://www.googleapis.com/oauth2/v4/token/?code=" + code + "&" + "client_id=" + client_id + "&" + "client_secret=" + client_secret + "&redirect_uri=" + redirect_uri + "app/email/emailSetupController/gmailutil&" + "grant_type=authorization_code&" + "access_type=offline&" + "approval_prompt=force";
</code>```

However the approval_prompt=force is not working as it should ask for users approval every time in order to get a refresh token.
I also tried prompt=consent. If the user has already logged in the gmail account then it does not show the approval page and redirects automatically resulting in refresh token as null.

答:
My Bad, actually the above URI is for "Exchange authorization code for refresh and access tokens" instead the prompt=consent is to be used in the first step while setting the authorization parametersGoogle docs.

Thank you.

Title: Getting refresh token each time

Body:
I am trying to get the refresh token every time the following uri is called,

String link = "https://www.googleapis.com/oauth2/v4/token/?code=" + code + "&" + "client_id=" + client_id + "&" + "client_secret=" + client_secret + "&redirect_uri=" + redirect_uri + "app/email/emailSetupController/gmailutil&" + "grant_type=authorization_code&" + "access_type=offline&" + "approval_prompt=force";

However the approval_prompt=force is not working as it should ask for users approval every time in order to get a refresh token.
I also tried prompt=consent. If the user has already logged in the gmail account then it does not show the approval page and redirects automatically resulting in refresh token as null.


问:
How do I add constraints to a subview loaded from a nib file?
I'm trying to load a sub view on to every single page of my app from a nib file. Right now I'm using a somewhat unusual approach to loading this sub view in that I am doing it through an extension of UIStoryboard (probably not relevant to my problem, but I'm not sure). So this is how the code looks when I load the nib file:

```<code>extension UIStoryboard {
    public func appendCustomView(to viewController: UIViewController) {
        if let myCustomSubview = Bundle.main.loadNibNamed("MyCustomSubview", owner: nil, options: nil)![0] as? MyCustomSubview {
            viewController.view.addSubview(myCustomSubview)
        }
    }
}
</code>```

This code does what it's supposed to do and adds "MyCustomSubview" to the view controller (I won't go in to detail on exactly how this method gets called because it works so it doesn't seem important). The problem is I can't for the life of me figure out how to add constraints that effect the size of myCustomSubview. I have tried putting code in the function I showed above as well as in the MyCustomSubview swift file to add constraints but no matter what I do the subview never changes.

Ideally the constraints would pin "MyCustomSubview" to the bottom of the ViewController, with width set to the size of the screen and a hard coded height constraint.

Here are the two main methods I tried (with about 100 minor variations for each) that did NOT work:

Method 1 - Add constraint directly from "appendCustomView"

```<code>public func appendCustomView(to viewController: UIViewController) {
    if let myCustomSubview = Bundle.main.loadNibNamed("MyCustomSubview", owner: nil, options: nil)![0] as? MyCustomSubview {

        let top = NSLayoutConstraint(item: myCustomSubview, attribute: .top, relatedBy: .equal
        , toItem: viewController.view, attribute: .top, multiplier: 1, constant: 50.0)

        viewController.view.addSubview(myCustomSubview)
        viewController.view.addConstraint(top)
    }
}
</code>```

Method 2 - Add constraint outlets and setter method in MyCustomSubview

```<code>class MyCustomSubview: UIView {
    @IBOutlet weak var widthConstraint: NSLayoutConstraint!
    @IBOutlet weak var heightConstraint: NSLayoutConstraint!

    func setConstraints(){
        self.widthConstraint.constant = UIScreen.main.bounds.size.width
        self.heightConstraint.constant = 20
    }
}
</code>```

And call setter method in "appendCustomView"

```<code>public func appendCustomView(to viewController: UIViewController) {
    if let myCustomSubview = Bundle.main.loadNibNamed("MyCustomSubview", owner: nil, options: nil)![0] as? MyCustomSubview {

        myCustomSubview.setConstraints()
        viewController.view.addSubview(myCustomSubview)
    }
}
</code>```

(*note: the actual constraints of these examples are irrelevant and I wasn't trying to meet the specs I mentioned above, I was just trying to make any sort of change to the view to know that the constraints were updating. They weren't.)

Edit : Changed "MyCustomNib" to "MyCustomSubview" for clarity.

答:
You can use this extension for anywhere you're going to add a subview to a existing UIView.

```<code>extension UIView {

  func setConstraintsFor(contentView: UIView, left: Bool = true, top: Bool = true, right: Bool = true, bottom: Bool = true) {

      contentView.translatesAutoresizingMaskIntoConstraints = false
      self.addSubview(contentView)

      var constraints         : [NSLayoutConstraint] = []
      if left {
          let constraintLeft      = NSLayoutConstraint(item: contentView, attribute: .left, relatedBy: .equal, toItem: self, attribute: .left, multiplier: 1, constant: 0)
          constraints.append(constraintLeft)
      }

      if top {
          let constraintTop       = NSLayoutConstraint(item: contentView, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 0)
          constraints.append(constraintTop)
      }

      if right {
          let constraintRight     = NSLayoutConstraint(item: contentView, attribute: .right, relatedBy: .equal, toItem: self, attribute: .right, multiplier: 1, constant: 0)
          constraints.append(constraintRight)
      }

      if bottom {
          let constraintBottom    = NSLayoutConstraint(item: contentView, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1, constant: 0)
          constraints.append(constraintBottom)
      }

      self.addConstraints(constraints)
  }
}
</code>```

You can call this method like this:

```<code>containerView.setConstraintsFor(contentView: subView!, top: false)
</code>```

This will add subView to the containerView and constraint to all sides except top side.
You can modify this method to pass left, top, right, bottom Constant value if you want.

Body:
I'm trying to load a sub view on to every single page of my app from a nib file. Right now I'm using a somewhat unusual approach to loading this sub view in that I am doing it through an extension of UIStoryboard (probably not relevant to my problem, but I'm not sure). So this is how the code looks when I load the nib file:

extension UIStoryboard {
    public func appendCustomView(to viewController: UIViewController) {
        if let myCustomSubview = Bundle.main.loadNibNamed("MyCustomSubview", owner: nil, options: nil)![0] as? MyCustomSubview {
            viewController.view.addSubview(myCustomSubview)
        }
    }
}

This code does what it's supposed to do and adds "MyCustomSubview" to the view controller (I won't go in to detail on exactly how this method gets called because it works so it doesn't seem important). The problem is I can't for the life of me figure out how to add constraints that effect the size of myCustomSubview. I have tried putting code in the function I showed above as well as in the MyCustomSubview swift file to add constraints but no matter what I do the subview never changes.

Ideally the constraints would pin "MyCustomSubview" to the bottom of the ViewController, with width set to the size of the screen and a hard coded height constraint.

Here are the two main methods I tried (with about 100 minor variations for each) that did NOT work:

Method 1 - Add constraint directly from "appendCustomView"

public func appendCustomView(to viewController: UIViewController) {
    if let myCustomSubview = Bundle.main.loadNibNamed("MyCustomSubview", owner: nil, options: nil)![0] as? MyCustomSubview {

        let top = NSLayoutConstraint(item: myCustomSubview, attribute: .top, relatedBy: .equal
        , toItem: viewController.view, attribute: .top, multiplier: 1, constant: 50.0)

        viewController.view.addSubview(myCustomSubview)
        viewController.view.addConstraint(top)
    }
}

Method 2 - Add constraint outlets and setter method in MyCustomSubview

class MyCustomSubview: UIView {
    @IBOutlet weak var widthConstraint: NSLayoutConstraint!
    @IBOutlet weak var heightConstraint: NSLayoutConstraint!

    func setConstraints(){
        self.widthConstraint.constant = UIScreen.main.bounds.size.width
        self.heightConstraint.constant = 20
    }
}

And call setter method in "appendCustomView"

public func appendCustomView(to viewController: UIViewController) {
    if let myCustomSubview = Bundle.main.loadNibNamed("MyCustomSubview", owner: nil, options: nil)![0] as? MyCustomSubview {

        myCustomSubview.setConstraints()
        viewController.view.addSubview(myCustomSubview)
    }
}

(*note: the actual constraints of these examples are irrelevant and I wasn't trying to meet the specs I mentioned above, I was just trying to make any sort of change to the view to know that the constraints were updating. They weren't.)

Edit : Changed "MyCustomNib" to "MyCustomSubview" for clarity.

Body:
You can use this extension for anywhere you're going to add a subview to a existing UIView.

extension UIView {

  func setConstraintsFor(contentView: UIView, left: Bool = true, top: Bool = true, right: Bool = true, bottom: Bool = true) {

      contentView.translatesAutoresizingMaskIntoConstraints = false
      self.addSubview(contentView)

      var constraints         : [NSLayoutConstraint] = []
      if left {
          let constraintLeft      = NSLayoutConstraint(item: contentView, attribute: .left, relatedBy: .equal, toItem: self, attribute: .left, multiplier: 1, constant: 0)
          constraints.append(constraintLeft)
      }

      if top {
          let constraintTop       = NSLayoutConstraint(item: contentView, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 0)
          constraints.append(constraintTop)
      }

      if right {
          let constraintRight     = NSLayoutConstraint(item: contentView, attribute: .right, relatedBy: .equal, toItem: self, attribute: .right, multiplier: 1, constant: 0)
          constraints.append(constraintRight)
      }

      if bottom {
          let constraintBottom    = NSLayoutConstraint(item: contentView, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1, constant: 0)
          constraints.append(constraintBottom)
      }

      self.addConstraints(constraints)
  }
}

You can call this method like this:

containerView.setConstraintsFor(contentView: subView!, top: false)

This will add subView to the containerView and constraint to all sides except top side.
You can modify this method to pass left, top, right, bottom Constant value if you want.


问:
Passing different class objects into a function and getting it's properties in Haxe?
Passing different class objects into a function and getting it's properties ?

For example:

I have two different class objects :

```<code>screenA = new ScreenA();
screenB = new ScreenB();
</code>```

I pass the objects in the tween:

```<code>switch (state)
{

    case States.SCREEN_A:
        {
            Actuate.tween(screenA, 0.6, {alpha: 1} ).ease(Sine.easeIn).autoVisible (true).onComplete(onComp, [screenA]);
        }
    case States.SCREEN_B:
        {
            Actuate.tween(screenB, 0.6, {alpha: 1} ).ease(Sine.easeIn).autoVisible (true).onComplete(onComp, [screenB]);
        }
}
</code>```

Now i want to access a method of the passed object here, when tween completes.

Tween is passing the object but i am unable to cast it in the function to get the object methods.

```<code>private function onComp(screen:?)
{
    screen.load();
}
</code>```

And compiler is always asking for the type. I have tried Dynamic / Any but then it says "load method not found", If i pass the object without any type arguments in the function then it is getting it as an object but not the class object.

答:
In this exact example, you can use load in the onComplete callback to simplify your code:

```<code>Actuate.tween (screenA, 0.6, { alpha: 1 }).ease (Sine.easeIn).onComplete (screenA.load);
</code>```

Body:
Passing different class objects into a function and getting it's properties ?

For example:

I have two different class objects :

screenA = new ScreenA();
screenB = new ScreenB();

I pass the objects in the tween:

switch (state)
{

    case States.SCREEN_A:
        {
            Actuate.tween(screenA, 0.6, {alpha: 1} ).ease(Sine.easeIn).autoVisible (true).onComplete(onComp, [screenA]);
        }
    case States.SCREEN_B:
        {
            Actuate.tween(screenB, 0.6, {alpha: 1} ).ease(Sine.easeIn).autoVisible (true).onComplete(onComp, [screenB]);
        }
}

Now i want to access a method of the passed object here, when tween completes.

Tween is passing the object but i am unable to cast it in the function to get the object methods.

private function onComp(screen:?)
{
    screen.load();
}

And compiler is always asking for the type. I have tried Dynamic / Any but then it says "load method not found", If i pass the object without any type arguments in the function then it is getting it as an object but not the class object.

Body:
In this exact example, you can use load in the onComplete callback to simplify your code:

Actuate.tween (screenA, 0.6, { alpha: 1 }).ease (Sine.easeIn).onComplete (screenA.load);


问:
Getting custom tooltips with JQuery
I'm looking for a JQuery code sample or library for displaying tooltips when the cursor hovers over an element. Specifically, what I want to do is display my own
 element on hover, not an automatically-constructed or loaded-from-the-host-element tooltip. I've looked at a couple JQuery tooltip plugins and they all seem to be unable to do this, but are very complex in other ways. This seems like something that should be only a couple of lines of JS/JQuery to do, yet I also haven't been able to find any working tutorials.

An ideal solution would also deal with tooltips near borders, have a 'sticky tooltip' option, have the option to load the HTML to be displayed as the tooltip using AJAX (as opposed to inline in the HTML/JS), and deal well with large numbers of tooltips (only showing one at a time of course).

答:
Well, I can't offer you an entire solution but getting a div to appear as a tooltip is pretty simple:

```<code>(function($){

    var $div = $('<div/>').css({
        position: 'absolute',
        background: 'white',
        border: '1px solid black',
        padding: '10px',
        zIndex: 999,
        display: 'none'
    }).appendTo('body');

    $('a.tooltip')
        .mousemove(function(e){
            $div.css({
                top: e.pageY + 10 + 'px',
                left: e.pageX + 10 + 'px'
            });
        })
        .hover(function(){
            $div.show().html('Text to display...');
        }, function(){
            $div.hide();
        });

})(jQuery);
</code>```

An example -> http://jsbin.com/emoso

OwnerDisplayName: kquinn

Title: Getting custom tooltips with JQuery

Body:
Well, I can't offer you an entire solution but getting a div to appear as a tooltip is pretty simple:

(function($){

    var $div = $('<div/>').css({
        position: 'absolute',
        background: 'white',
        border: '1px solid black',
        padding: '10px',
        zIndex: 999,
        display: 'none'
    }).appendTo('body');

    $('a.tooltip')
        .mousemove(function(e){
            $div.css({
                top: e.pageY + 10 + 'px',
                left: e.pageX + 10 + 'px'
            });
        })
        .hover(function(){
            $div.show().html('Text to display...');
        }, function(){
            $div.hide();
        });

})(jQuery);

An example -> http://jsbin.com/emoso

OwnerDisplayName: JimmyP

LastEditorDisplayName: JimmyP


问:
Why doesn't this crash?
I'm attempting to narrow down a bug to a minimum reproducible case and found something odd.

Consider this code:

```<code>static NSString *staticString = nil;
int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    if (staticString == nil) {
        staticString = [[NSArray arrayWithObjects:@"1", @"2", @"3", nil] componentsJoinedByString:@","];
    }

    [pool drain];

    NSLog(@"static: %@", staticString);
    return 0;
}
</code>```

I'm expecting this code to crash.  Instead, it logs:

```<code>2011-01-18 14:41:06.311 EmptyFoundation[61419:a0f] static: static:
</code>```

However, if I change the NSLog() to:

```<code>NSLog(@"static: %s", [staticString UTF8String]);
</code>```

Then it does crash.

edit a bit more info:

After draining the pool:

```<code>NSLog(@"static: %@", staticString);  //this logs "static: static: "
NSLog(@"static: %@", [staticString description]); //this crashes
</code>```

So apparently invoking a method on the string is good enough to get it to crash.  In that case, why doesn't logging the string directly cause it to crash?  Shouldn't NSLog() be invoking the -description method?

Where is the second "static: " coming from?  Why isn't this crashing?

Results:

Both Kevin Ballard and Graham Lee are correct.  Graham's correct in realizing that NSLog() is not invoking -description (as I was erroneously assuming), and Kevin is almost definitely correct that this is a weird stack-related issue with copying a format string and a va_list around.

NSLogging and NSString does not invoke -description.  Graham elegantly showed this, and if you trace through the Core Foundation sources that do the logging, you'll see that this is the case.  Any backtrace originating inside NSLog shows that it invokes NSLogv => _CFLogvEx => _CFStringCreateWithFormatAndArgumentsAux => _CFStringAppendFormatAndArgumentsAux.  _CFStringAppendFormatAndArgumentsAux() (line 5365) is where all of the magic is going on.  You can see that it's manually going through to find all the % substitutions.  It only ends up invoking the description copy function if the type of the substitution is a CFFormatObjectType, the description function is non-nil, and the substitution hasn't already been handled by another type.  Since we've shown that the description is not getting copied, it's reasonable to assume that an NSString gets handled earlier (in which case it's probably going to be doing a raw byte copy), which leads us to believe...

There's a stack error going on here, as Kevin surmises.  Somehow the pointer that was pointing to the autoreleased string is getting substituted to a different object, which happens to be an NSString.  So, it doesn't crash.  Weird.  However, if we change the type of the static variable to something else, like an NSArray, then the -description method does get called, and the program does crash as expected.

How truly and utterly strange.  Points go to Kevin for being the most correct about the root cause of the behavior, and kudos to Graham for correcting my fallacious thinking.  I wish I could accept two answers...

答: Accessing dealocated memory does not necessarily cause a crash. The behavior is undefined. You are expecting too much!

Title: Why doesn't this crash?

Body:
I'm attempting to narrow down a bug to a minimum reproducible case and found something odd.

Consider this code:

static NSString *staticString = nil;
int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    if (staticString == nil) {
        staticString = [[NSArray arrayWithObjects:@"1", @"2", @"3", nil] componentsJoinedByString:@","];
    }

    [pool drain];

    NSLog(@"static: %@", staticString);
    return 0;
}

I'm expecting this code to crash.  Instead, it logs:

2011-01-18 14:41:06.311 EmptyFoundation[61419:a0f] static: static:

However, if I change the NSLog() to:

NSLog(@"static: %s", [staticString UTF8String]);

Then it does crash.

edit a bit more info:

After draining the pool:

NSLog(@"static: %@", staticString);  //this logs "static: static: "
NSLog(@"static: %@", [staticString description]); //this crashes

So apparently invoking a method on the string is good enough to get it to crash.  In that case, why doesn't logging the string directly cause it to crash?  Shouldn't NSLog() be invoking the -description method?

Where is the second "static: " coming from?  Why isn't this crashing?

Results:

Both Kevin Ballard and Graham Lee are correct.  Graham's correct in realizing that NSLog() is not invoking -description (as I was erroneously assuming), and Kevin is almost definitely correct that this is a weird stack-related issue with copying a format string and a va_list around.

NSLogging and NSString does not invoke -description.  Graham elegantly showed this, and if you trace through the Core Foundation sources that do the logging, you'll see that this is the case.  Any backtrace originating inside NSLog shows that it invokes NSLogv => _CFLogvEx => _CFStringCreateWithFormatAndArgumentsAux => _CFStringAppendFormatAndArgumentsAux.  _CFStringAppendFormatAndArgumentsAux() (line 5365) is where all of the magic is going on.  You can see that it's manually going through to find all the % substitutions.  It only ends up invoking the description copy function if the type of the substitution is a CFFormatObjectType, the description function is non-nil, and the substitution hasn't already been handled by another type.  Since we've shown that the description is not getting copied, it's reasonable to assume that an NSString gets handled earlier (in which case it's probably going to be doing a raw byte copy), which leads us to believe...

There's a stack error going on here, as Kevin surmises.  Somehow the pointer that was pointing to the autoreleased string is getting substituted to a different object, which happens to be an NSString.  So, it doesn't crash.  Weird.  However, if we change the type of the static variable to something else, like an NSArray, then the -description method does get called, and the program does crash as expected.

How truly and utterly strange.  Points go to Kevin for being the most correct about the root cause of the behavior, and kudos to Graham for correcting my fallacious thinking.  I wish I could accept two answers...


问:
Jupyter installation on Mac OS El Capitan
I want to install jupyter, but am trying to this locally.

I don't want to use anaconda or install an additional python with

```<code>brew install python
</code>```

I write

```<code>pip install --user jupyter
</code>```

That succeeds. But the installation jupyter is not in $PATH, so I get

```<code>$ jupyter notebook
zsh: command not found: jupyter
</code>```

I am using zsh, btw...

What should I do? What to add to $PATH?

答:
jupyter notebook sets it path depending how you have installed. Either conda or pip/pip3 I installed my notebook from pip3
For Instance you can temporarily switch to bash by exec bash -l and locate the bin by the following

```<code>which jupyter
/Library/Frameworks/Python.framework/Versions/3.6/bin/jupyter
</code>```

copy the bin path and switch to zsh, edit the .zshrc and the the following

```<code>export PATH=/Library/Frameworks/Python.framework/Versions/3.6/bin:$PATH
</code>```

Or append to your existing $PATH. Restart terminal. Make sure the jupyter bin is correct, it should be different if you have used conda to install jupyter.

Body:
I want to install jupyter, but am trying to this locally.

I don't want to use anaconda or install an additional python with

brew install python

I write

pip install --user jupyter

That succeeds. But the installation jupyter is not in $PATH, so I get

$ jupyter notebook
zsh: command not found: jupyter

I am using zsh, btw...

What should I do? What to add to $PATH?

Body:
jupyter notebook sets it path depending how you have installed. Either conda or pip/pip3 I installed my notebook from pip3
For Instance you can temporarily switch to bash by exec bash -l and locate the bin by the following

which jupyter
/Library/Frameworks/Python.framework/Versions/3.6/bin/jupyter

copy the bin path and switch to zsh, edit the .zshrc and the the following

export PATH=/Library/Frameworks/Python.framework/Versions/3.6/bin:$PATH

Or append to your existing $PATH. Restart terminal. Make sure the jupyter bin is correct, it should be different if you have used conda to install jupyter.


问:
Detailed Sentiment Score in Stanford CoreNLP
On the StanfordCore NLP website there is the following demo:http://nlp.stanford.edu:8080/sentiment/rntnDemo.html

The demo gives a sentence a detailed sentiment score from 0 to 4.

I understand how to get a "positive" or "negative" assessment using command line, similar to this:
Screenshot from corenlp.run showing a positive sentiment analysis

I have seen this question already, but I am interested how the analysis shown in the attached screenshot is created. Getting sentiment analysis result using stanford core nlp java code

Is there a way in Stanford CoreNLP to return a score (i.e. 0-4) for a given sentence so show its degree of positivity or negativity?

Thanks!

答:
There are multiple ways to get that kind of info.

Also I should note that the there is a direct mapping:

"Very negative" = 0
"Negative" = 1
"Neutral" = 2
"Positive" = 3
"Very positive" = 4

Here is a sample command:

```<code>java -Xmx8g edu.stanford.nlp.pipeline.StanfordCoreNLP -annotators tokenize,ssplit,pos,lemma,ner,parse,sentiment -file example-1.txt -outputFormat json
</code>```

In the file example-1.txt.json you'll see a lot of sentiment related fields for the sentence, including sentimentValue.

There is more info about this at this GitHub issue:

https://github.com/stanfordnlp/CoreNLP/issues/465

Body:
There are multiple ways to get that kind of info.

Also I should note that the there is a direct mapping:

"Very negative" = 0
"Negative" = 1
"Neutral" = 2
"Positive" = 3
"Very positive" = 4

Here is a sample command:

java -Xmx8g edu.stanford.nlp.pipeline.StanfordCoreNLP -annotators tokenize,ssplit,pos,lemma,ner,parse,sentiment -file example-1.txt -outputFormat json

In the file example-1.txt.json you'll see a lot of sentiment related fields for the sentence, including sentimentValue.

There is more info about this at this GitHub issue:

https://github.com/stanfordnlp/CoreNLP/issues/465