问:
Realm Object Server on Digital Ocean using Ubuntu Server
I am using Realm Object Server running on Digital Ocean the lowest option ($5/month) on Ubuntu server. I keep getting connection refused errors; and I don't know if the error is from DO or ROS.

I am no expert on Ubuntu; therefore, I went in and cleared all the logs from /var/log and tried to reconnect. When there are large records to sync I keep getting the following error (on iOS, the client side):

```<code>2017-07-05 18:55:46.983543+0300 Torba[1783:2024434] Sync: Connection[1]: Resolving '207.154.251.37:9080'
2017-07-05 18:55:46.986087+0300 Torba[1783:2024434] Sync: Connection[1]: Connecting to endpoint '207.154.251.37:9080' (1/1)
2017-07-05 18:55:47.045242+0300 Torba[1783:2024434] Sync: Connection[1]: Failed to connect to endpoint '207.154.251.37:9080': Connection refused
2017-07-05 18:55:47.045387+0300 Torba[1783:2024434] Sync: Connection[1]: Failed to connect to '207.154.251.37:9080': All endpoints failed
2017-07-05 18:55:47.125378+0300 Torba[1783:2024434] Sync: Connection[3]: Resolving '207.154.251.37:9080'
2017-07-05 18:55:47.126805+0300 Torba[1783:2024434] Sync: Connection[3]: Connecting to endpoint '207.154.251.37:9080' (1/1)
2017-07-05 18:55:47.178626+0300 Torba[1783:2024434] Sync: Connection[3]: Failed to connect to endpoint '207.154.251.37:9080': Connection refused
2017-07-05 18:55:47.178830+0300 Torba[1783:2024434] Sync: Connection[3]: Failed to connect to '207.154.251.37:9080': All endpoints failed
2017-07-05 18:55:49.677104+0300 Torba[1783:2024434] Sync: Connection[1]: Resolving '207.154.251.37:9080'
2017-07-05 18:55:49.678640+0300 Torba[1783:2024434] Sync: Connection[1]: Connecting to endpoint '207.154.251.37:9080' (1/1)
2017-07-05 18:55:49.727078+0300 Torba[1783:2024434] Sync: Connection[1]: Failed to connect to endpoint '207.154.251.37:9080': Connection refused
2017-07-05 18:55:49.727283+0300 Torba[1783:2024434] Sync: Connection[1]: Failed to connect to '207.154.251.37:9080': All endpoints failed
</code>```

On the ubuntu side, after clearing all the logs, there is one log created again when I try to connect to the server, appport.log, here are the contents:

```<code>ERROR: apport (pid 32499) Wed Jul  5 15:55:15 2017: called for pid 32448, signal 6, core limit 18446744073709551615
ERROR: apport (pid 32499) Wed Jul  5 15:55:15 2017: ignoring implausibly big core limit, treating as unlimited
ERROR: apport (pid 32499) Wed Jul  5 15:55:15 2017: executable: /usr/lib/realm-object-server-developer/node/bin/node (command line "/usr/lib/realm-object-server-developer/node/bin/node /usr/bin/realm-object-server -c /etc/realm/configuration.yml")
ERROR: apport (pid 32499) Wed Jul  5 15:55:15 2017: is_closing_session(): no DBUS_SESSION_BUS_ADDRESS in environment
ERROR: apport (pid 32499) Wed Jul  5 15:55:15 2017: apport: report /var/crash/_usr_lib_realm-object-server-developer_node_bin_node.999.crash already
</code>```

From the logs I can't figure out if the error is on the Realm side or the Digital Ocean side. Can anybody help, any ideas?

答:
After reading the logs carefully, I found out that Realm Object Server was crashing. I don't know why yet, but now I know the problem is with the ROS.

* EDIT *
The app was crashing due to not enough memory. By increasing the server's memory everything started work as expected.

```<code>Jul 05 15:55:33 torba-test systemd[1]: realm-object-server.service: Main process exited, code=killed, status=6/ABRT
Jul 05 15:55:33 torba-test systemd[1]: realm-object-server.service: Unit entered failed state.
Jul 05 15:55:33 torba-test systemd[1]: realm-object-server.service: Failed with result 'signal'.
Jul 05 15:55:34 torba-test systemd[1]: realm-object-server.service: Service hold-off time over, scheduling restart.
Jul 05 15:55:34 torba-test systemd[1]: Stopped Realm Object Server.
</code>```

Body:
I am using Realm Object Server running on Digital Ocean the lowest option ($5/month) on Ubuntu server. I keep getting connection refused errors; and I don't know if the error is from DO or ROS.

I am no expert on Ubuntu; therefore, I went in and cleared all the logs from /var/log and tried to reconnect. When there are large records to sync I keep getting the following error (on iOS, the client side):

2017-07-05 18:55:46.983543+0300 Torba[1783:2024434] Sync: Connection[1]: Resolving '207.154.251.37:9080'
2017-07-05 18:55:46.986087+0300 Torba[1783:2024434] Sync: Connection[1]: Connecting to endpoint '207.154.251.37:9080' (1/1)
2017-07-05 18:55:47.045242+0300 Torba[1783:2024434] Sync: Connection[1]: Failed to connect to endpoint '207.154.251.37:9080': Connection refused
2017-07-05 18:55:47.045387+0300 Torba[1783:2024434] Sync: Connection[1]: Failed to connect to '207.154.251.37:9080': All endpoints failed
2017-07-05 18:55:47.125378+0300 Torba[1783:2024434] Sync: Connection[3]: Resolving '207.154.251.37:9080'
2017-07-05 18:55:47.126805+0300 Torba[1783:2024434] Sync: Connection[3]: Connecting to endpoint '207.154.251.37:9080' (1/1)
2017-07-05 18:55:47.178626+0300 Torba[1783:2024434] Sync: Connection[3]: Failed to connect to endpoint '207.154.251.37:9080': Connection refused
2017-07-05 18:55:47.178830+0300 Torba[1783:2024434] Sync: Connection[3]: Failed to connect to '207.154.251.37:9080': All endpoints failed
2017-07-05 18:55:49.677104+0300 Torba[1783:2024434] Sync: Connection[1]: Resolving '207.154.251.37:9080'
2017-07-05 18:55:49.678640+0300 Torba[1783:2024434] Sync: Connection[1]: Connecting to endpoint '207.154.251.37:9080' (1/1)
2017-07-05 18:55:49.727078+0300 Torba[1783:2024434] Sync: Connection[1]: Failed to connect to endpoint '207.154.251.37:9080': Connection refused
2017-07-05 18:55:49.727283+0300 Torba[1783:2024434] Sync: Connection[1]: Failed to connect to '207.154.251.37:9080': All endpoints failed

On the ubuntu side, after clearing all the logs, there is one log created again when I try to connect to the server, appport.log, here are the contents:

ERROR: apport (pid 32499) Wed Jul  5 15:55:15 2017: called for pid 32448, signal 6, core limit 18446744073709551615
ERROR: apport (pid 32499) Wed Jul  5 15:55:15 2017: ignoring implausibly big core limit, treating as unlimited
ERROR: apport (pid 32499) Wed Jul  5 15:55:15 2017: executable: /usr/lib/realm-object-server-developer/node/bin/node (command line "/usr/lib/realm-object-server-developer/node/bin/node /usr/bin/realm-object-server -c /etc/realm/configuration.yml")
ERROR: apport (pid 32499) Wed Jul  5 15:55:15 2017: is_closing_session(): no DBUS_SESSION_BUS_ADDRESS in environment
ERROR: apport (pid 32499) Wed Jul  5 15:55:15 2017: apport: report /var/crash/_usr_lib_realm-object-server-developer_node_bin_node.999.crash already

From the logs I can't figure out if the error is on the Realm side or the Digital Ocean side. Can anybody help, any ideas?

Body:
After reading the logs carefully, I found out that Realm Object Server was crashing. I don't know why yet, but now I know the problem is with the ROS.

* EDIT *
The app was crashing due to not enough memory. By increasing the server's memory everything started work as expected.

Jul 05 15:55:33 torba-test systemd[1]: realm-object-server.service: Main process exited, code=killed, status=6/ABRT
Jul 05 15:55:33 torba-test systemd[1]: realm-object-server.service: Unit entered failed state.
Jul 05 15:55:33 torba-test systemd[1]: realm-object-server.service: Failed with result 'signal'.
Jul 05 15:55:34 torba-test systemd[1]: realm-object-server.service: Service hold-off time over, scheduling restart.
Jul 05 15:55:34 torba-test systemd[1]: Stopped Realm Object Server.


来源: stackexchange

问:
SpringBoot @RequestBody pojo not mapping to my json
Can anyone help me fix this. I have hard coded json object which is suppposed to map to my POJO but I'm getting null values in my Spring Controller. I've checked my getters and setters. They seems to be correct. What am i doing wrong here ?

Controller

```<code>@PostMapping("/dashboard")
public Dashboard getDashboard(@RequestBody PaginationRequest paginationRequest) {
      return topcatService.getDashboard(paginationRequest);
}
</code>```

json

```<code> var paginationRequest = { grouping  : e.target.value ,total : "1", currentPage : "1", pageSize : "5"};
</code>```

POJO

```<code> public class PaginationRequest {
        private String grouping;
        private String total;
        private String  currentPage;
        private String pageSize;

       //setter/getter
    }
</code>```

答:
I would say you have to create a valid json first and test if you data comes correctly to your controller.

Just try to send an example json like that:

```<code>var paginationRequest = '{\"grouping\":\"anyValue\",\"total\":\"1\",\"currentPage\":\"1\",\"pageSize\": \"5\"}';
</code>```

this means you send only a String in a json format.

If you have an Object you maybe have to convert your Object to a json String:

```<code>var somejson =  JSON.stringify(someobject);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Can anyone help me fix this. I have hard coded json object which is suppposed to map to my POJO but I'm getting null values in my Spring Controller. I've checked my getters and setters. They seems to be correct. What am i doing wrong here ?

Controller

@PostMapping("/dashboard")
public Dashboard getDashboard(@RequestBody PaginationRequest paginationRequest) {
      return topcatService.getDashboard(paginationRequest);
}

json

 var paginationRequest = { grouping  : e.target.value ,total : "1", currentPage : "1", pageSize : "5"};

POJO

 public class PaginationRequest {
        private String grouping;
        private String total;
        private String  currentPage;
        private String pageSize;

       //setter/getter
    }

Body:
I would say you have to create a valid json first and test if you data comes correctly to your controller.

Just try to send an example json like that:

var paginationRequest = '{\"grouping\":\"anyValue\",\"total\":\"1\",\"currentPage\":\"1\",\"pageSize\": \"5\"}';

this means you send only a String in a json format.

If you have an Object you maybe have to convert your Object to a json String:

var somejson =  JSON.stringify(someobject);


问:
ASP.NET Core 1.1 runs fine locally but when publishing to Azure says "An error occurred while starting the application."
I've been developing an ASP.NET Core web app, based largely on the MVC template provided in Visual Studio 2017 RC2. It runs just fine in local debug mode, but when I try to publish it to an Azure hosted web app, I get this error:

An error occurred while starting the application.

.NET Core X86 v4.1.1.0    |   Microsoft.AspNetCore.Hosting version
  1.1.0-rtm-22752    |    Microsoft Windows 6.2.9200

I've tried setting stdoutLogEnabled="true" in the web.config file, but it seems to have no effect, the error is the same.

Update:

With some help I managed to retrieve the log, and it says:

```<code>Application startup exception: System.TypeLoadException: Could not load type 'System.IO.File' from assembly 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e'.
   at Microsoft.Extensions.DependencyModel.FileWrapper.OpenRead(String path)
   at Microsoft.Extensions.DependencyModel.DependencyContextLoader.LoadEntryAssemblyContext(IDependencyContextReader reader)
   at Microsoft.Extensions.DependencyModel.DependencyContextLoader.Load(Assembly assembly)
   at Microsoft.Extensions.DependencyModel.DependencyContext.Load(Assembly assembly)
   at Microsoft.AspNetCore.Mvc.Internal.DefaultAssemblyPartDiscoveryProvider.DiscoverAssemblyParts(String entryPointAssemblyName)
   at Microsoft.Extensions.DependencyInjection.MvcCoreServiceCollectionExtensions.GetApplicationPartManager(IServiceCollection services)
   at Microsoft.Extensions.DependencyInjection.MvcCoreServiceCollectionExtensions.AddMvcCore(IServiceCollection services)
   at Microsoft.Extensions.DependencyInjection.MvcServiceCollectionExtensions.AddMvc(IServiceCollection services)
   at Bla.Api.Startup.ConfigureServices(IServiceCollection services) in C:\Users\user\Source\Workspaces\Bla\Bla.Api\src\Bla.Api\Startup.cs:line 73
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.AspNetCore.Hosting.ConventionBasedStartup.ConfigureServices(IServiceCollection services)
   at Microsoft.AspNetCore.Hosting.Internal.WebHost.EnsureApplicationServices()
   at Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()

Hosting environment: Production
Content root path: D:\home\site\wwwroot
Now listening on: http://localhost:1264
Application started. Press Ctrl+C to shut down.
</code>```

The line of code it refers to at line 73 is:

```<code>services.AddMvc();
</code>```

Update:

My global.json file looks like this (where Bla.Api is the name of the project, and the file sits in the solution root folder).

```<code>{
  "projects": [ "Bla.Api" ],
  "sdk": {
    "version": "1.1.0"
  }
}
</code>```

答:
DELETE all existing dll from wwwroot/your_application_folder, then copy all of the publish output files&folders.

The problem occurs when the NUGETS update it self. If you don't clean the existing files under wwwroot/your_application_folder IIS gives the error above.

Body:
I've been developing an ASP.NET Core web app, based largely on the MVC template provided in Visual Studio 2017 RC2. It runs just fine in local debug mode, but when I try to publish it to an Azure hosted web app, I get this error:

An error occurred while starting the application.

.NET Core X86 v4.1.1.0    |   Microsoft.AspNetCore.Hosting version
  1.1.0-rtm-22752    |    Microsoft Windows 6.2.9200

I've tried setting stdoutLogEnabled="true" in the web.config file, but it seems to have no effect, the error is the same.

Update:

With some help I managed to retrieve the log, and it says:

Application startup exception: System.TypeLoadException: Could not load type 'System.IO.File' from assembly 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e'.
   at Microsoft.Extensions.DependencyModel.FileWrapper.OpenRead(String path)
   at Microsoft.Extensions.DependencyModel.DependencyContextLoader.LoadEntryAssemblyContext(IDependencyContextReader reader)
   at Microsoft.Extensions.DependencyModel.DependencyContextLoader.Load(Assembly assembly)
   at Microsoft.Extensions.DependencyModel.DependencyContext.Load(Assembly assembly)
   at Microsoft.AspNetCore.Mvc.Internal.DefaultAssemblyPartDiscoveryProvider.DiscoverAssemblyParts(String entryPointAssemblyName)
   at Microsoft.Extensions.DependencyInjection.MvcCoreServiceCollectionExtensions.GetApplicationPartManager(IServiceCollection services)
   at Microsoft.Extensions.DependencyInjection.MvcCoreServiceCollectionExtensions.AddMvcCore(IServiceCollection services)
   at Microsoft.Extensions.DependencyInjection.MvcServiceCollectionExtensions.AddMvc(IServiceCollection services)
   at Bla.Api.Startup.ConfigureServices(IServiceCollection services) in C:\Users\user\Source\Workspaces\Bla\Bla.Api\src\Bla.Api\Startup.cs:line 73
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.AspNetCore.Hosting.ConventionBasedStartup.ConfigureServices(IServiceCollection services)
   at Microsoft.AspNetCore.Hosting.Internal.WebHost.EnsureApplicationServices()
   at Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()

Hosting environment: Production
Content root path: D:\home\site\wwwroot
Now listening on: http://localhost:1264
Application started. Press Ctrl+C to shut down.

The line of code it refers to at line 73 is:

services.AddMvc();

Update:

My global.json file looks like this (where Bla.Api is the name of the project, and the file sits in the solution root folder).

{
  "projects": [ "Bla.Api" ],
  "sdk": {
    "version": "1.1.0"
  }
}


问:
Error while calling Discovery service in conversation-with-discoveryapplication
I have used https://github.com/watson-developer-cloud/conversation-with-discovery code and deployed application in Bluemix, when I am testing the application conversation is working but discovery service is not working .

I have added OUT_OF_Scope intent with call_discovery action.

I am getting server is busy error when we give out scope question in chatbot.

below is the  the log error , please help me to resolve this error.
Exception thrown by application class 'com.ibm.watson.apis.conversation_with_discovery.rest.ProxyResource.postMessage:192'
java.lang.NullPointerException
    at com.ibm.watson.apis.conversation_with_discovery.rest.ProxyResource.pos

答:
When I used the conversation-with-discovery I had the same problem, but I see within the Github the solution for this: Switch to the liberty-for-java_v3_7-20170118-2046 buildpack that doesn't have problems with the Java SDK.

Reference: IBM Developer


问:
websocketd with json over STDIN/STDOUT
We have built software that consists of two parts, a GUI (front-end) running in the browser and a kernel (back-end) with Go compiled into exe.

To glue these two pieces together, we used nodejs+expressjs+socket.io running on the local machine. Nodejs talks to the browser over http/socket.io, and it also "spawn" Go exe as child_process.

Now with websocketd, we can skip the nodejs+expressjs+socket.io part. That is great.

The difficulty is: the GUI in the browser used to send JSON to nodejs, which is then written into a configuration file. Our kernel exe will read that JSON configuration file to determine what to do.

I guess one cannot send JSON over STDIN/STDOUT. I can certainly do command line "flag" for Go to parse.

Question: Is there a better way doing this?

答:
This is very late to the party and probably won't help at this point, but it might help future people who see this.

Websocketd supports a binary transfer type and removes the /n line endings. This might be used by just buffering in and outbound binary streams and just reading them as json on either end.

https://github.com/joewalnes/websocketd/issues/38

```<code>websocketd --devconsole --port 8080 --binary --devconsole stdbuf -i0 -io0 cat
</code>```

The --binary flag being the important part of that link. (Copied in the even the link ever dies).

Title: websocketd with json over STDIN/STDOUT

Body:
This is very late to the party and probably won't help at this point, but it might help future people who see this.

Websocketd supports a binary transfer type and removes the /n line endings. This might be used by just buffering in and outbound binary streams and just reading them as json on either end.

https://github.com/joewalnes/websocketd/issues/38

websocketd --devconsole --port 8080 --binary --devconsole stdbuf -i0 -io0 cat

The --binary flag being the important part of that link. (Copied in the even the link ever dies).


问:
Python 3.5 xlsxwriter assistance
How can can I convert "Daily Return" and "MTD Return" into percentages if I am using xlsxwriter?

*Current code being used with xlsxwriter

```<code>worksheet.write('B10', df2.loc[4,["NAV"]])
worksheet.write('C10', df2.loc[4,["Daily_DVA"]])
worksheet.write('D10', df2.loc[4,["MTD_DVA"]])
</code>```

Image 1

Also how am I able to add colors to the "Trading Activity" and "Performance Data" columns along with making the text bold like the following image attached? I would also like to keep the text centered as well.

*Current code being used with xlsxwriter

```<code>worksheet.merge_range('A2:B2', 'Trading Activity', center_format)
worksheet.merge_range('A8:D8', 'Performance Data', center_format)
</code>```

Image 2

答:
You just need to add appropriate formats. Like this:

```<code>import xlsxwriter

workbook = xlsxwriter.Workbook('example.xlsx')
worksheet = workbook.add_worksheet()

# Add a format for percentages.
percent_format = workbook.add_format({'num_format': '0%'})

worksheet.write('B1', .5)
worksheet.write('B2', .5, percent_format)

# Add a format for a merged range.
merge_format = workbook.add_format({
    'bold': True,
    'border': 1,
    'align': 'center',
    'valign': 'vcenter',
    'fg_color': '#16DDFF'})

worksheet.merge_range('B4:D4', 'Trading Activity', merge_format)

workbook.close()
</code>```

Output:

Title: Python 3.5 xlsxwriter assistance

Body:
How can can I convert "Daily Return" and "MTD Return" into percentages if I am using xlsxwriter?

*Current code being used with xlsxwriter

worksheet.write('B10', df2.loc[4,["NAV"]])
worksheet.write('C10', df2.loc[4,["Daily_DVA"]])
worksheet.write('D10', df2.loc[4,["MTD_DVA"]])

Image 1

Also how am I able to add colors to the "Trading Activity" and "Performance Data" columns along with making the text bold like the following image attached? I would also like to keep the text centered as well.

*Current code being used with xlsxwriter

worksheet.merge_range('A2:B2', 'Trading Activity', center_format)
worksheet.merge_range('A8:D8', 'Performance Data', center_format)

Image 2

Body:
You just need to add appropriate formats. Like this:

import xlsxwriter

workbook = xlsxwriter.Workbook('example.xlsx')
worksheet = workbook.add_worksheet()

# Add a format for percentages.
percent_format = workbook.add_format({'num_format': '0%'})

worksheet.write('B1', .5)
worksheet.write('B2', .5, percent_format)

# Add a format for a merged range.
merge_format = workbook.add_format({
    'bold': True,
    'border': 1,
    'align': 'center',
    'valign': 'vcenter',
    'fg_color': '#16DDFF'})

worksheet.merge_range('B4:D4', 'Trading Activity', merge_format)

workbook.close()

Output:


问:
How to disable printing reports after each epoch in Keras?
After each epoch I have printout like below:

```<code>Train on 102 samples, validate on 26 samples
Epoch 1/1
Epoch 00000: val_acc did not improve
102/102 [==============================] - 3s - loss: 0.4934 - acc: 0.8997 - val_loss: 0.4984 - val_acc: 0.9231
</code>```

I am not using built-in epochs, so I would like to disable these printouts and print something myself.

How to do that?

I am using tensorflow backend if it matters.

答: Set verbose=0 to the fit method of your model.

Body:
After each epoch I have printout like below:

Train on 102 samples, validate on 26 samples
Epoch 1/1
Epoch 00000: val_acc did not improve
102/102 [==============================] - 3s - loss: 0.4934 - acc: 0.8997 - val_loss: 0.4984 - val_acc: 0.9231

I am not using built-in epochs, so I would like to disable these printouts and print something myself.

How to do that?

I am using tensorflow backend if it matters.

ContentLicense: CC BY-SA 4.0


问:
Need suggestion of Apache_beam learning materials for beginners
I need to learn Apache Beam for a project. I have gone through the
 Apache Beam documentation and I think this is not enough. Can someone recommend resources to learn Apache Beam?</p>

答:
Have you tried running through the Python/Java quick start tutorials?

You can also go through an explanation of the wordcount pipelines, so you'll become more familiar with some of the transforms available in beam.

Once you have a look at the specific wordcount example, you can dive in the programming guide to get a more detailed understanding of the framework.


问:
Simulink & Masks: Dynamic access to parameters "evaluate" and "tunable"
First of all, matlab version is 2011b, so I cannot use Simulink.MaskParameters class.

I have one simulink mask and some parameters inside. I need to determine in my function for each parameter if it is "evaluable" or "tunable".

Those two things are two checkboxes in the mask parameters dialog which you can select for any parameter.

For "tunable", there's the MaskTunableValues property. For "enable", there's the "MaskEnables" property.

Do you know if there's a way to programmatically access the same property but for "evaluate" ?
Thanks

答:
Answer for versions > 2011b (tested on 2014b):

Ok found it, actually the matlab documentation is REALLY unclear regarding the Simulink.MaskParameter class and here is how it works:

First, get the Mask class from your block:

```<code>mask = Simulink.Mask.get(gcb)
</code>```

The Mask class is a structure containing all mask parameters:

```<code>parameters = mask.Parameters(:)
</code>```

parameters is a (array of) Simulink.MaskParameter object which will contains all the necessary properties, including Evaluate.

Body:
Answer for versions > 2011b (tested on 2014b):

Ok found it, actually the matlab documentation is REALLY unclear regarding the Simulink.MaskParameter class and here is how it works:

First, get the Mask class from your block:

mask = Simulink.Mask.get(gcb)

The Mask class is a structure containing all mask parameters:

parameters = mask.Parameters(:)

parameters is a (array of) Simulink.MaskParameter object which will contains all the necessary properties, including Evaluate.


问:
Python Issue Making a Game
Im a new python learner and Im reading Zed Shaw book called :
Learn python the hardway
Im doing very well at following the instructions and doing the study drills as well .
Recently I've tried to make a little game by myself but i got stuck and i need a little help
this is my script :

```<code>from sys import exit

def starting():
    print "Welcome to the abyss of dark"
    print "The game is about choosing"
    print "if you lose you die if you win you live"

    choose_door = raw_input("> ")

    if "1" in choose_door or "door 1" or "D1" or "d1":
        no_weapon()
    elif "2" in choose_door or "door 2" or "D2" or "d2":
        Weapon_room()
    elif "3" in choose_door or "door 3" or "D3" or "d3":
        shortcut()
    elif "4" in choose_door or "door 4" or "D4" or "d4":
        princess_room()
    elif "5" in choose_door or "door 5" or "D5" or "d5":
        princess_room()
    elif "6" in choose_door or "door 6" or "D6" or "d6":
        gards_room()
    else:
        "7" in choose_door or "door7" or "D7" or "d7"
        suicide_room()

start()

def map():
    print """"
    |------------------------------------------------------------------------------------|
    |   shortcut     D|room of the | room of the|                                        |
    |     to D4      O|princess    | gards      | S U I C I D E      R O  O M            |
    |                O|            |            |                                        |
    |                R|            |            |                                        |
    |                4|            |            |                                        |
    |-----DOOR 3---|------DOOR 5-------DOOR 6---------------------DOOR 7----------------|
    |Weapon ROOM |                                                                      |
    |            | DOOR 2               YOUR                                            |
    |            |                            ARE                                       |
    |            |                                 HERE                                 |
    |------------|                                                                      |
    |No Weapon   | DOOR 1                                                               |
    |            |                                                                      |
    |------------|------------------------------------------------------------------------

    """
    start()

def no_weapon():
    print "You've choosed to continue with no Weapons"
    print "What a BRAVE PLAYER!"
    print "Choose your door"
    print "3 , 5 , 6 , 7"
    no_weapon_door = raw_input("> ")
    if no_weapon_door == "3":
        shortcut
    elif no_weapon_door == "5":
        princess_room
    elif no_weapon_door == "6":
        gards_room
    else:
        suicide_room

def Weapon_room():
    print "You are armed now"
    print "Which door you choose type just the number"
    print "Door 3 or Door 4"
    Weapon_room_door = raw_input("> ")
    if Weapon_room_door == "3":
        shortcut
    else:
        princess_room

def shortcut():
    princess_room

def princess_room():
    print "You won"

def gards_room():
    print "fight with gards"
    print "Yes or No"
    fighting = raw_input("> ")
    if fighing == "Yes":
            princess_room
    else:
        fighting == "No"
        lost
def suicide_room():
    print "Die in peace"
    lost

def lost():
    print "You lost"
    print "If you want to reapeat Press R if you wanna exit tye E"
    losing = raw_input ("> ")
    if losing == "R":
        start()
    else:
        exit()
</code>```

for me i think everything i written as it should be but when i run my script i get an error :

```Traceback (most recent call last):
  File "newgame.py", line 26, in
    start()
NameError: name 'start' is not defined```

couldn't figure out
Help me Please and thank you

答:
You are missing to call starting() function, and in place of that you mistakenly called start() which is nowhere defined in the entire program.

So, either name the 1st function in the programme as start() or else rename the 3 occurrences of start() to starting().

Title: Python Issue Making a Game

Body:
Im a new python learner and Im reading Zed Shaw book called :
Learn python the hardway
Im doing very well at following the instructions and doing the study drills as well .
Recently I've tried to make a little game by myself but i got stuck and i need a little help
this is my script :

from sys import exit

def starting():
    print "Welcome to the abyss of dark"
    print "The game is about choosing"
    print "if you lose you die if you win you live"

    choose_door = raw_input("> ")

    if "1" in choose_door or "door 1" or "D1" or "d1":
        no_weapon()
    elif "2" in choose_door or "door 2" or "D2" or "d2":
        Weapon_room()
    elif "3" in choose_door or "door 3" or "D3" or "d3":
        shortcut()
    elif "4" in choose_door or "door 4" or "D4" or "d4":
        princess_room()
    elif "5" in choose_door or "door 5" or "D5" or "d5":
        princess_room()
    elif "6" in choose_door or "door 6" or "D6" or "d6":
        gards_room()
    else:
        "7" in choose_door or "door7" or "D7" or "d7"
        suicide_room()

start()

def map():
    print """"
    |------------------------------------------------------------------------------------|
    |   shortcut     D|room of the | room of the|                                        |
    |     to D4      O|princess    | gards      | S U I C I D E      R O  O M            |
    |                O|            |            |                                        |
    |                R|            |            |                                        |
    |                4|            |            |                                        |
    |-----DOOR 3---|------DOOR 5-------DOOR 6---------------------DOOR 7----------------|
    |Weapon ROOM |                                                                      |
    |            | DOOR 2               YOUR                                            |
    |            |                            ARE                                       |
    |            |                                 HERE                                 |
    |------------|                                                                      |
    |No Weapon   | DOOR 1                                                               |
    |            |                                                                      |
    |------------|------------------------------------------------------------------------

    """
    start()

def no_weapon():
    print "You've choosed to continue with no Weapons"
    print "What a BRAVE PLAYER!"
    print "Choose your door"
    print "3 , 5 , 6 , 7"
    no_weapon_door = raw_input("> ")
    if no_weapon_door == "3":
        shortcut
    elif no_weapon_door == "5":
        princess_room
    elif no_weapon_door == "6":
        gards_room
    else:
        suicide_room

def Weapon_room():
    print "You are armed now"
    print "Which door you choose type just the number"
    print "Door 3 or Door 4"
    Weapon_room_door = raw_input("> ")
    if Weapon_room_door == "3":
        shortcut
    else:
        princess_room

def shortcut():
    princess_room

def princess_room():
    print "You won"

def gards_room():
    print "fight with gards"
    print "Yes or No"
    fighting = raw_input("> ")
    if fighing == "Yes":
            princess_room
    else:
        fighting == "No"
        lost
def suicide_room():
    print "Die in peace"
    lost

def lost():
    print "You lost"
    print "If you want to reapeat Press R if you wanna exit tye E"
    losing = raw_input ("> ")
    if losing == "R":
        start()
    else:
        exit()

for me i think everything i written as it should be but when i run my script i get an error :

Traceback (most recent call last):
  File "newgame.py", line 26, in
    start()
NameError: name 'start' is not defined

couldn't figure out
Help me Please and thank you


问:
Does wxpython run on separate process and release the GIL (Global Interpreter Lock)?
I was wondering the interaction that wxPython has with running things on separate cores and if wxPython releases the GIL when running.

I've assumed that when I kick off some command which takes a while that wxPython starts up the wxWidgets c++ code which runs on multiple cores and somehow releases the GIL until the task is finished and then comes back. However I have nothing to base this on. Does this ever happen?

What is actually going on under the hood?

答:
The GIL is automatically released and reacquired whenever a call is made to a wx C++ function or method.  This is probably a bit of overkill as there are a number of things that are quick and won't ever block and it might be more efficient to not release/reacquire the GIL, but this approach ensures that we don't miss doing it for something that will block.

In addition, any time there is an event dispatched to a Python event handler, or when a virtual method overridden in Python is called, or etc. then the GIL is acquired before entry to that code and released again afterwards.


问:
Explicit vs implicit SQL joins
Is there any efficiency difference in an explicit vs implicit inner join?
For example:

```<code>SELECT * FROM
table a INNER JOIN table b
ON a.id = b.id;
</code>```

vs.

```<code>SELECT a.*, b.*
FROM table a, table b
WHERE a.id = b.id;
</code>```

答:
Performance-wise, they are exactly the same (at least in SQL Server).

PS: Be aware that the "implicit OUTER JOIN" syntax--using *= or =* in a WHERE after using comma--is deprecated since SQL Server 2005. (The "implicit (CROSS) JOIN" syntax using comma as used in the question is still supported.)

Deprecation of "Old Style" JOIN Syntax: Only A Partial Thing

OwnerDisplayName: dmanxiii

Title: Explicit vs implicit SQL joins

Body:
Is there any efficiency difference in an explicit vs implicit inner join?
For example:

SELECT * FROM
table a INNER JOIN table b
ON a.id = b.id;

vs.

SELECT a.*, b.*
FROM table a, table b
WHERE a.id = b.id;

LastEditorDisplayName: Eric Z Beard

OwnerDisplayName: lomaxx

LastEditorDisplayName: lomaxx


问:
Insert a symbol ">" between the characters in a list of strings
I have a column in Excel like this:

```<code>ABC
BCD
BA
</code>```

How can I put the symbols ">" between every letters in the strings? The expected output should be like this:

```<code>A>B>C
B>C>D
B>A
</code>```

Or could we do this in Matlab ?

答:
A single line matlab solution would be:

strjoin(cellstr(str(:)), '>')
```

Explanation:

cellstr(str(:)): converts the char array to a cell array

strjoin: joins all the cells with the given delimiter, i.e. >

Body:
I have a column in Excel like this:

ABC
BCD
BA

How can I put the symbols ">" between every letters in the strings? The expected output should be like this:

A>B>C
B>C>D
B>A

Or could we do this in Matlab ?

Body:
A single line matlab solution would be:

strjoin(cellstr(str(:)), '>')

Explanation:

cellstr(str(:)): converts the char array to a cell array

strjoin: joins all the cells with the given delimiter, i.e. >


问:
I wish to show route of 'n' number of drivers (single route for each driver)on Gmap. Its a case of dynamic drivers
Currently i am able to display 3 route of 3 drivers respectively(one for each) on a single Gmap.
Now, I wish to show route of 'n' number of drivers (single route for each driver)on Gmap. Its a case of dynamic drivers. I can get data from db for 'n' number of drivers that i need to display on a single map.

My Code is below for single driver please help me for dynamic craetion of routes:

```<code>                 var lat_lng1 = [];
                var latlngbounds1 = "";
                lat_lng1 = new Array();
                var value1 = markers1.length;

                //Intialize the Path Array
                var path1 = new google.maps.MVCArray();
                //Intialize the Direction Service
                var service1 = new google.maps.DirectionsService();
                var lineSymbol1 = { path1: google.maps.SymbolPath.CIRCLE };
                //Set the Path Stroke Color

                for (i = 0; i < markers1.length; i++) {
                    var data1 = markers1[i]
                    var myLatlng1 = new google.maps.LatLng(data1.lat, data1.lng);
                    lat_lng1.push(myLatlng1);

                    var marker1 = new google.maps.Marker({position: myLatlng1,map: map,icon: icon1});
                    (function (marker1, data1) {
                        // Attaching a click event to the current marker
                        google.maps.event.addListener(marker1, "click", function (e) {
                            if (i == 0){
                                infoWindow.setContent(data1.Person);infoWindow.open(map, marker1);}
                            if(i=(markers2.length -1)){
                                infoWindow.setContent(data1.Person);infoWindow.open(map, marker1);}
                            else{
                                infoWindow.setContent(data1.Title);
                                infoWindow.open(map, marker1);}
                        });
                    })(marker1, data1);
                }

                poly = new google.maps.Polyline({
                    // path: lineCoordinates,
                    strokeColor: '#BC456F',
                    icons: [{
                        icon: {
                            path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW,strokeColor: '#009900',fillColor: '#009900',fillOpacity: 1},
                        repeat: '100px',
                        path1: []
                    }],
                    map: map
                });
</code>```

答: well I solved this issue the very next day by calling ajax loops by driver id</p>

Body:
Currently i am able to display 3 route of 3 drivers respectively(one for each) on a single Gmap.
Now, I wish to show route of 'n' number of drivers (single route for each driver)on Gmap. Its a case of dynamic drivers. I can get data from db for 'n' number of drivers that i need to display on a single map.

My Code is below for single driver please help me for dynamic craetion of routes:

                 var lat_lng1 = [];
                var latlngbounds1 = "";
                lat_lng1 = new Array();
                var value1 = markers1.length;

                //Intialize the Path Array
                var path1 = new google.maps.MVCArray();
                //Intialize the Direction Service
                var service1 = new google.maps.DirectionsService();
                var lineSymbol1 = { path1: google.maps.SymbolPath.CIRCLE };
                //Set the Path Stroke Color

                for (i = 0; i < markers1.length; i++) {
                    var data1 = markers1[i]
                    var myLatlng1 = new google.maps.LatLng(data1.lat, data1.lng);
                    lat_lng1.push(myLatlng1);

                    var marker1 = new google.maps.Marker({position: myLatlng1,map: map,icon: icon1});
                    (function (marker1, data1) {
                        // Attaching a click event to the current marker
                        google.maps.event.addListener(marker1, "click", function (e) {
                            if (i == 0){
                                infoWindow.setContent(data1.Person);infoWindow.open(map, marker1);}
                            if(i=(markers2.length -1)){
                                infoWindow.setContent(data1.Person);infoWindow.open(map, marker1);}
                            else{
                                infoWindow.setContent(data1.Title);
                                infoWindow.open(map, marker1);}
                        });
                    })(marker1, data1);
                }

                poly = new google.maps.Polyline({
                    // path: lineCoordinates,
                    strokeColor: '#BC456F',
                    icons: [{
                        icon: {
                            path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW,strokeColor: '#009900',fillColor: '#009900',fillOpacity: 1},
                        repeat: '100px',
                        path1: []
                    }],
                    map: map
                });


问:
set/unset user presence in IRC
I am programming an IRC gateway to another protocol, and I want my IRC server (the gateway) to notify the IRC client when other users are connected or disconnected.

This feature is supported by my IRC client (Quassel) : it shows me when a user set himself as /away, but I can't figure out what command my IRC server must send to set/unset user presence.

答:
You ideally implement the IRCv3 spec away-notify: http://ircv3.net/specs/extensions/away-notify-3.1.html

Otherwise your client has to spam WHO polls often to get the latest status of users.

Title: set/unset user presence in IRC


问:
Android M permission of the tested READ_PHONE_STATE(dangerous permissions)
If the device is running Android 6.0 or higher when im trying to get phone number using getLine1Number():

java.lang.SecurityException: Requires READ_PHONE_STATE: Neither user 10184 nor current process has android.permission.READ_PHONE_STATE.
This is coming out.

I declared permission as :

```<code><uses-permission android:name="android.permission.READ_PHONE_STATE" />
</code>```

答:
```<code>public class MainActivity extends AppCompatActivity {

    TextView textView;
    String device_unique_id,IMEI;

    private static final int MY_PERMISSIONS_REQUEST_READ_PHONE_STATE = 0;

   @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textView = (TextView)findViewById(R.id.textView);
    }
    public void GetImei(View view)
    {

        loadIMEI();

    }

    public void loadIMEI() {
        // Check if the READ_PHONE_STATE permission is already available.
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE)
                != PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.READ_PHONE_STATE)) {
//                get_imei_data();
            } else {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE},
                        MY_PERMISSIONS_REQUEST_READ_PHONE_STATE);
            }
        } else {

            TelephonyManager mngr = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
            IMEI = mngr.getDeviceId();
            device_unique_id = Settings.Secure.getString(this.getContentResolver(),
                    Settings.Secure.ANDROID_ID);
            textView.setText(device_unique_id+"----"+mngr.getDeviceId());
            // READ_PHONE_STATE permission is already been granted.
            Toast.makeText(this,"Alredy granted",Toast.LENGTH_SHORT).show();
        }
    }
       @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,@NonNull int[] grantResults) {

        if (requestCode == MY_PERMISSIONS_REQUEST_READ_PHONE_STATE) {

            if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

//                Toast.makeText(this,"Alredy DONE",Toast.LENGTH_SHORT).show();
                TelephonyManager mngr = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
                IMEI = mngr.getDeviceId();
                device_unique_id = Settings.Secure.getString(this.getContentResolver(),Settings.Secure.ANDROID_ID);
                textView.setText(device_unique_id+"----"+mngr.getDeviceId());

            } else {
                Toast.makeText(this,"ehgehfg",Toast.LENGTH_SHORT).show();
            }
        }
    }
</code>```

Body:
If the device is running Android 6.0 or higher when im trying to get phone number using getLine1Number():

java.lang.SecurityException: Requires READ_PHONE_STATE: Neither user 10184 nor current process has android.permission.READ_PHONE_STATE.
This is coming out.

I declared permission as :

<uses-permission android:name="android.permission.READ_PHONE_STATE" />


问:
Manual approval / rejection of user registration by admin using Firebase
Currently I'm designing an application in Swift 3.0 that will be used by a small group up to 100 users.

Users will register through a simple registration form using email id and password but Admin will have to approve or reject the user registration request manually.

Workflow I can think of is if a user register, admin will get some notification or email that a new user registration request is there and then when admin approve or rejects the user registration request and user  will get a email (that his registration is approved or rejected).

Is it possible with Firebase, I have tried reading Firebase documents but cannot find anything that can be helpful in this case.

Any help or ideas are very much appreciated.

答: it's possible, you have to add a field to your user node name it as example approved by default 0, when a new user is added to your database the admin receive a notification and check the registration if accepted change the value to of approved to 1 else delete the user data


问:
Quit jQuery $.each loop

Possible Duplicate:

  How do I break out of an $.each in jquery?

How to quit the jquery $.each loop?

答:
Use return false inside the .each() loop to break out entirely. Returning anything that's not false is like continue: it stops the current iteration and jumps right to the next.

```<code>var myArr = [1,2,3,4,5,6,7];
$.each( myArr, function(){
  // Skip on three
  if( this === 3 ) return true;
  // Abort on five
  if( this === 5 ) return false;
  doStuff( this ); // never for 3, 5, 6 or 7
});
</code>```

ContentLicense: CC BY-SA 2.5

Title: Quit jQuery $.each loop

Body:
Use return false inside the .each() loop to break out entirely. Returning anything that's not false is like continue: it stops the current iteration and jumps right to the next.

var myArr = [1,2,3,4,5,6,7];
$.each( myArr, function(){
  // Skip on three
  if( this === 3 ) return true;
  // Abort on five
  if( this === 5 ) return false;
  doStuff( this ); // never for 3, 5, 6 or 7
});


问:
How to stop Direct3D from flicker on release on multihead setup?
Have a kiosk system with a small touchscreen and a large display, and I have an app that works well playing video on the large display. For some reason, when Direct3D stops (app quits), both screens flicker (turn black, then recover).

I simplified the problem down to a program that simply opens a focus window, initializes a Direct3D device, then releases it. On release (or stopping the program without releasing), both screens flicker.

Can someone who's familiar with Direct3D look at this and tell me if I'm doing something wrong?

#include <iostream>
#include <windows.h>
#include <d3d9.h>

const char g_szClassName[] = "myWindowClass";

LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
    switch (msg)
    {
    case WM_CLOSE:
        DestroyWindow(hwnd);
        break;
    case WM_DESTROY:
        PostQuitMessage(0);
        break;
    default:
        return DefWindowProc(hwnd, msg, wParam, lParam);
    }
    return 0;
}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {

    WNDCLASSEX wc;

    wc.cbSize = sizeof(WNDCLASSEX);
    wc.style = 0;
    wc.lpfnWndProc = WndProc;
    wc.cbClsExtra = 0;
    wc.cbWndExtra = 0;
    wc.hInstance = hInstance;
    wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
    wc.hCursor = LoadCursor(NULL, IDC_ARROW);
    wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
    wc.lpszMenuName = NULL;
    wc.lpszClassName = g_szClassName;
    wc.hIconSm = LoadIcon(NULL, IDI_APPLICATION);

    if (!RegisterClassEx(&wc)) {
        MessageBox(NULL, "Window Registration Failed!", "Error!", MB_ICONEXCLAMATION | MB_OK);
        return 0;
    }

    HWND hwnd = CreateWindowEx(
        WS_EX_CLIENTEDGE,
        g_szClassName,
        "Focus Window",
        WS_POPUP | WS_VISIBLE,
        CW_USEDEFAULT, CW_USEDEFAULT, 240, 120,
        NULL, NULL, hInstance, NULL);

    if (hwnd == NULL) {
        MessageBox(NULL, "Window Creation Failed!", "Error!", MB_ICONEXCLAMATION | MB_OK);
        return 0;
    }

    ShowWindow(hwnd, nCmdShow);
    UpdateWindow(hwnd);

    IDirect3D9* m_pD3D = Direct3DCreate9(D3D_SDK_VERSION);
    if (m_pD3D == NULL) {
        MessageBox(NULL, "Failed to initialize direct3D!", "Error!", MB_ICONEXCLAMATION | MB_OK);
        return 0;
    }

    // second display is 1920 x 1080

    D3DPRESENT_PARAMETERS m_param;
    ZeroMemory(&m_param, sizeof(m_param));
    m_param.BackBufferWidth = 1920;
    m_param.BackBufferHeight = 1080;
    m_param.BackBufferFormat = D3DFMT_X8R8G8B8;
    m_param.BackBufferCount = 1;
    m_param.MultiSampleType = D3DMULTISAMPLE_NONE;
    m_param.SwapEffect = D3DSWAPEFFECT_COPY;
    m_param.hDeviceWindow = hwnd;
    m_param.Windowed = FALSE;
    m_param.Flags = D3DPRESENTFLAG_VIDEO;
    m_param.FullScreen_RefreshRateInHz = D3DPRESENT_RATE_DEFAULT;
    m_param.PresentationInterval = D3DPRESENT_INTERVAL_ONE;

    HRESULT hr;
    IDirect3DDevice9* m_pD3DD;
    hr = m_pD3D->CreateDevice(
        1,
        D3DDEVTYPE_HAL,
        hwnd,
        D3DCREATE_HARDWARE_VERTEXPROCESSING | D3DCREATE_MULTITHREADED,
        &m_param,
        &m_pD3DD
    );

    if (hr != S_OK) {
        MessageBox(NULL, "Failed to create direct3D device!", "Error!", MB_ICONEXCLAMATION | MB_OK);
        return 0;
    }

    Sleep(3000);

    // flicker occurs here
    m_pD3DD->Release();
    m_pD3D->Release();

    return 0;

}
```

NOTE: This program should run on any setup with 2 screens on the same video card, but the second screen's width/height might need to be adjusted (it's hardcoded in BackBufferWidth and BackBufferHeight)

答:
Not sure if that is workable for you, but in trying various examples around the interwebs, it seems the only way to avoid the flicker is to use windowed mode with a borderless window:</p>

```<code>...

HWND hwnd = CreateWindowEx(
    0,
    g_szClassName,
    "Focus Window",
    WS_POPUP | WS_VISIBLE, // <-- borderless window
    800, 0,                // <-- position on 2nd screen
    1920, 1080,            // <-- fill entire 2nd screen
    NULL, NULL, hInstance, NULL);

...

D3DPRESENT_PARAMETERS m_param;
ZeroMemory(&m_param, sizeof(m_param));
m_param.BackBufferWidth = 1920;
m_param.BackBufferHeight = 1080;
m_param.BackBufferFormat = D3DFMT_X8R8G8B8;
m_param.BackBufferCount = 1;
m_param.MultiSampleType = D3DMULTISAMPLE_NONE;
m_param.SwapEffect = D3DSWAPEFFECT_COPY;
m_param.hDeviceWindow = hwnd;
m_param.Windowed = TRUE;   // <-- use windowed mode
m_param.Flags = D3DPRESENTFLAG_VIDEO;
m_param.FullScreen_RefreshRateInHz = D3DPRESENT_RATE_DEFAULT;
m_param.PresentationInterval = D3DPRESENT_INTERVAL_ONE;
</code>```

Body:
Have a kiosk system with a small touchscreen and a large display, and I have an app that works well playing video on the large display. For some reason, when Direct3D stops (app quits), both screens flicker (turn black, then recover).

I simplified the problem down to a program that simply opens a focus window, initializes a Direct3D device, then releases it. On release (or stopping the program without releasing), both screens flicker.

Can someone who's familiar with Direct3D look at this and tell me if I'm doing something wrong?

#include <iostream>
#include <windows.h>
#include <d3d9.h>

const char g_szClassName[] = "myWindowClass";

LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
    switch (msg)
    {
    case WM_CLOSE:
        DestroyWindow(hwnd);
        break;
    case WM_DESTROY:
        PostQuitMessage(0);
        break;
    default:
        return DefWindowProc(hwnd, msg, wParam, lParam);
    }
    return 0;
}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {

    WNDCLASSEX wc;

    wc.cbSize = sizeof(WNDCLASSEX);
    wc.style = 0;
    wc.lpfnWndProc = WndProc;
    wc.cbClsExtra = 0;
    wc.cbWndExtra = 0;
    wc.hInstance = hInstance;
    wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
    wc.hCursor = LoadCursor(NULL, IDC_ARROW);
    wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
    wc.lpszMenuName = NULL;
    wc.lpszClassName = g_szClassName;
    wc.hIconSm = LoadIcon(NULL, IDI_APPLICATION);

    if (!RegisterClassEx(&wc)) {
        MessageBox(NULL, "Window Registration Failed!", "Error!", MB_ICONEXCLAMATION | MB_OK);
        return 0;
    }

    HWND hwnd = CreateWindowEx(
        WS_EX_CLIENTEDGE,
        g_szClassName,
        "Focus Window",
        WS_POPUP | WS_VISIBLE,
        CW_USEDEFAULT, CW_USEDEFAULT, 240, 120,
        NULL, NULL, hInstance, NULL);

    if (hwnd == NULL) {
        MessageBox(NULL, "Window Creation Failed!", "Error!", MB_ICONEXCLAMATION | MB_OK);
        return 0;
    }

    ShowWindow(hwnd, nCmdShow);
    UpdateWindow(hwnd);

    IDirect3D9* m_pD3D = Direct3DCreate9(D3D_SDK_VERSION);
    if (m_pD3D == NULL) {
        MessageBox(NULL, "Failed to initialize direct3D!", "Error!", MB_ICONEXCLAMATION | MB_OK);
        return 0;
    }

    // second display is 1920 x 1080

    D3DPRESENT_PARAMETERS m_param;
    ZeroMemory(&m_param, sizeof(m_param));
    m_param.BackBufferWidth = 1920;
    m_param.BackBufferHeight = 1080;
    m_param.BackBufferFormat = D3DFMT_X8R8G8B8;
    m_param.BackBufferCount = 1;
    m_param.MultiSampleType = D3DMULTISAMPLE_NONE;
    m_param.SwapEffect = D3DSWAPEFFECT_COPY;
    m_param.hDeviceWindow = hwnd;
    m_param.Windowed = FALSE;
    m_param.Flags = D3DPRESENTFLAG_VIDEO;
    m_param.FullScreen_RefreshRateInHz = D3DPRESENT_RATE_DEFAULT;
    m_param.PresentationInterval = D3DPRESENT_INTERVAL_ONE;

    HRESULT hr;
    IDirect3DDevice9* m_pD3DD;
    hr = m_pD3D->CreateDevice(
        1,
        D3DDEVTYPE_HAL,
        hwnd,
        D3DCREATE_HARDWARE_VERTEXPROCESSING | D3DCREATE_MULTITHREADED,
        &m_param,
        &m_pD3DD
    );

    if (hr != S_OK) {
        MessageBox(NULL, "Failed to create direct3D device!", "Error!", MB_ICONEXCLAMATION | MB_OK);
        return 0;
    }

    Sleep(3000);

    // flicker occurs here
    m_pD3DD->Release();
    m_pD3D->Release();

    return 0;

}

NOTE: This program should run on any setup with 2 screens on the same video card, but the second screen's width/height might need to be adjusted (it's hardcoded in BackBufferWidth and BackBufferHeight)

Body:
Not sure if that is workable for you, but in trying various examples around the interwebs, it seems the only way to avoid the flicker is to use windowed mode with a borderless window:

...

HWND hwnd = CreateWindowEx(
    0,
    g_szClassName,
    "Focus Window",
    WS_POPUP | WS_VISIBLE, // <-- borderless window
    800, 0,                // <-- position on 2nd screen
    1920, 1080,            // <-- fill entire 2nd screen
    NULL, NULL, hInstance, NULL);

...

D3DPRESENT_PARAMETERS m_param;
ZeroMemory(&m_param, sizeof(m_param));
m_param.BackBufferWidth = 1920;
m_param.BackBufferHeight = 1080;
m_param.BackBufferFormat = D3DFMT_X8R8G8B8;
m_param.BackBufferCount = 1;
m_param.MultiSampleType = D3DMULTISAMPLE_NONE;
m_param.SwapEffect = D3DSWAPEFFECT_COPY;
m_param.hDeviceWindow = hwnd;
m_param.Windowed = TRUE;   // <-- use windowed mode
m_param.Flags = D3DPRESENTFLAG_VIDEO;
m_param.FullScreen_RefreshRateInHz = D3DPRESENT_RATE_DEFAULT;
m_param.PresentationInterval = D3DPRESENT_INTERVAL_ONE;


问:
Export PATCH/PUT but not POST in @RepositoryRestResource
I am using spring-data-rest and exposing endpoints for CRUD-ing my entities through repositories.

One of entities should be updatable with PATCH/PUT methods, but it shouldn't be possible to create a new instance with POST method.

It seems that both actions go through save method so it seems not possible to export only some of the requests:

```<code>@RestResource(exported = ?)
@Override
<S extends User> S save(S s);
</code>```

What's the best way to accomplish that?

Should I override save method? Write custom Validator?

答:
You can use

Validators and add an Error to the errors parameter

Event Handlers, throw an Exception and catch that by @ControllerAdvice, which returns a custom Message or HTTP status code

Custom Controllers and handle the request manually. See this answer: https://stackoverflow.com/a/41351429/7226417

The first two should listen to BeforeCreateEvent.

Body:
I am using spring-data-rest and exposing endpoints for CRUD-ing my entities through repositories.

One of entities should be updatable with PATCH/PUT methods, but it shouldn't be possible to create a new instance with POST method.

It seems that both actions go through save method so it seems not possible to export only some of the requests:

@RestResource(exported = ?)
@Override
<S extends User> S save(S s);

What's the best way to accomplish that?

Should I override save method? Write custom Validator?


问:
How to use Facebook SDK with Nuxt.js?
You can see my code.

npm install vue init nuxt/koa my-project (koa@2)

pages

|- login.vue

```

but,

sdk.js:96 Uncaught TypeError: vm.statusChangeCallback is not a function

When using the Nuxt project (nuxt/koa), what is the best way to use the Facebook SDK?

答:
I running into the same problem this day. Here is my solution with nuxt.js

First create a plugin plugins/fb-sdk.js

const vue_fb = {}
vue_fb.install = function install(Vue, options) {
    (function(d, s, id){
        var js, fjs = d.getElementsByTagName(s)[0]
        if (d.getElementById(id)) {return}
        js = d.createElement(s)
        js.id = id
        js.src = "//connect.facebook.net/en_US/sdk.js"
        fjs.parentNode.insertBefore(js, fjs)
        console.log('setting fb sdk')
    }(document, 'script', 'facebook-jssdk'))

    window.fbAsyncInit = function onSDKInit() {
        FB.init(options)
        FB.AppEvents.logPageView()
        Vue.FB = FB
        window.dispatchEvent(new Event('fb-sdk-ready'))
    }
    Vue.FB = undefined
}

import Vue from 'vue'

Vue.use(vue_fb, {
    appId: 'your-app-id',
    autoLogAppEvents: true,
    xfbml: true,
    version: 'v2.9'
})
```
<p>We can use <code>Vue.FB</code> to invoke methods in FB SDK and listen to the <code>fb-sdk-ready</code> event in any component like this:</p>
<pre class="lang-js prettyprint-override"><code>export default{
    data: function () {
        return {isFBReady: false}
    },
    mounted: function () {
        this.isFBReady = Vue.FB != undefined
        window.addEventListener('fb-sdk-ready', this.onFBReady)
    },
    beforeDestroy: function () {
        window.removeEventListener('fb-sdk-ready', this.onFBReady)
    },
    methods: {
        onFBReady: function () {
          this.isFBReady = true
        }
    }
}
</code>```

Title: How to use Facebook SDK with Nuxt.js?

Body:
You can see my code.

npm install vue init nuxt/koa my-project (koa@2)

pages

|- login.vue

but,

sdk.js:96 Uncaught TypeError: vm.statusChangeCallback is not a function

When using the Nuxt project (nuxt/koa), what is the best way to use the Facebook SDK?

Body:
I running into the same problem this day. Here is my solution with nuxt.js

First create a plugin plugins/fb-sdk.js

const vue_fb = {}
vue_fb.install = function install(Vue, options) {
    (function(d, s, id){
        var js, fjs = d.getElementsByTagName(s)[0]
        if (d.getElementById(id)) {return}
        js = d.createElement(s)
        js.id = id
        js.src = "//connect.facebook.net/en_US/sdk.js"
        fjs.parentNode.insertBefore(js, fjs)
        console.log('setting fb sdk')
    }(document, 'script', 'facebook-jssdk'))

    window.fbAsyncInit = function onSDKInit() {
        FB.init(options)
        FB.AppEvents.logPageView()
        Vue.FB = FB
        window.dispatchEvent(new Event('fb-sdk-ready'))
    }
    Vue.FB = undefined
}

import Vue from 'vue'

Vue.use(vue_fb, {
    appId: 'your-app-id',
    autoLogAppEvents: true,
    xfbml: true,
    version: 'v2.9'
})

We can use Vue.FB to invoke methods in FB SDK and listen to the fb-sdk-ready event in any component like this:

export default{
    data: function () {
        return {isFBReady: false}
    },
    mounted: function () {
        this.isFBReady = Vue.FB != undefined
        window.addEventListener('fb-sdk-ready', this.onFBReady)
    },
    beforeDestroy: function () {
        window.removeEventListener('fb-sdk-ready', this.onFBReady)
    },
    methods: {
        onFBReady: function () {
          this.isFBReady = true
        }
    }
}


问:
Python Dataframe Single Row with Label
```<code>import pandas as pd
data = ["X", "Y", "Z", "A", "B"]
label = ['a','b','c','d','e']
df = pd.DataFrame(data, columns=label)
print(df)
</code>```

I want to get the dataframe to be:

```<code>a b c d e
X Y Z A B
</code>```

I am getting

```<code>ValueError: Shape of passed values is (1, 5), indices imply (5, 5)
</code>```

How to fix this to get the desired dataframe ?

答:
Pass it as a list of list.</p>

```<code>In [439]: pd.DataFrame([data], columns=label)
Out[439]:
   a  b  c  d  e
0  X  Y  Z  A  B
</code>```

Title: Python Dataframe Single Row with Label

Body:
import pandas as pd
data = ["X", "Y", "Z", "A", "B"]
label = ['a','b','c','d','e']
df = pd.DataFrame(data, columns=label)
print(df)

I want to get the dataframe to be:

a b c d e
X Y Z A B

I am getting

ValueError: Shape of passed values is (1, 5), indices imply (5, 5)

How to fix this to get the desired dataframe ?

Body:
Pass it as a list of list.

In [439]: pd.DataFrame([data], columns=label)
Out[439]:
   a  b  c  d  e
0  X  Y  Z  A  B


问:
Preview email generated by Microsoft Outlook Object Library
Is it possible to preview the email generated by Microsoft Outlook Object Library?

I currently construct a MailItem, fill it with relevant information then send it. I would like to have Outlook open and preview the email and allow the user to send the email rather than having it automatically sent.

Thank you.

答: Of course. Instead of calling MailItem.Send, call MailItem.Display.


问:
Why does append print out 'NONE'?
I am trying to add items to a list with the function append. But when I print out the updated list it returns 'None'

Here's what I got so far

```<code>lists = []
count = 0

while count < 10:
count += 1
ask = input("What note do you want stored?")

lists = lists.append(ask)
print(lists)

>>> What note do you want stored? sd
None
</code>```

答:
Because you're assigning the result of lists.append back to lists.  lists.append modifies its argument list and always returns None.  Just do the lists.append and don't do anything with its return value.

Instead of

```<code>lists = lists.append(ask)
</code>```

just do

```<code>lists.append(ask)
</code>```

The append method modifies the list in place. It doesn't return the new list; in fact, it doesn't return anything at all, which is why assigning its return value to lists gets you a value of None.

Title: Why does append print out 'NONE'?

Body:
I am trying to add items to a list with the function append. But when I print out the updated list it returns 'None'

Here's what I got so far

lists = []
count = 0

while count < 10:
count += 1
ask = input("What note do you want stored?")

lists = lists.append(ask)
print(lists)

>>> What note do you want stored? sd
None

Body:
Because you're assigning the result of lists.append back to lists.  lists.append modifies its argument list and always returns None.  Just do the lists.append and don't do anything with its return value.

Instead of

lists = lists.append(ask)

just do

lists.append(ask)

The append method modifies the list in place. It doesn't return the new list; in fact, it doesn't return anything at all, which is why assigning its return value to lists gets you a value of None.


问:
Objective-c Novice - Needs help with UIViews
Im new to iphone development and after lots of reading on it im still trying to figure out how UIViews operate properly. I have been playing about with it and i this is where i am at so far:

I have created a new xcode project using the view-based application. I have my MMAppViewController classes and i created a new UIViewController subclass called "Level1View".

There is a button titled "Level 1" that takes me to the "Level1View" viewController. In this viewController there is there is a "next" button, a "main menu" button (that returns to MMAppViewController) and there is a label, currently titled "Level 1".

My problem is that the code i have used to change the title of label does not work! Does anyone know why this is? Here is my code:

```<code>@class MMAppViewController;

@interface MMAppAppDelegate : NSObject <UIApplicationDelegate> {
    UIWindow *window;
    MMAppViewController *viewController;
}

@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet MMAppViewController *viewController;

@end
</code>```

and

```<code>@implementation MMAppViewController

-(IBAction)pushLevel1{

    Level1View *level1View = [[Level1View alloc] initWithNibName:nil bundle:nil];
    [self presentModalViewController:level1View animated:YES];
}
...
</code>```

and

```<code>#import <UIKit/UIKit.h>

@interface Level1View : UIViewController {
    IBOutlet UILabel *labelTitle;

}
-(IBAction)pushBack;
-(IBAction)pushNext;
@end
</code>```

and

```<code> #import "Level1View.h"
    #import "MMAppViewController.h"

    @implementation Level1View

    -(IBAction)pushBack{

        MMAppViewController *MainView = [[MMAppViewController alloc] initWithNibName:nil bundle:nil];
        [self presentModalViewController:MainView animated:YES];

    }
    -(IBAction)pushNext{

        [labelTitle setText:(@"Thanks for playing :)")];

    }

    - (void)didReceiveMemoryWarning {
    ...
</code>```

Currently the app runs but the label wont change when i hit the "next" button. Can anyone help?

答:
are you sure you connected the label in IB?

and if you set a property "@property (nonatomic, retain) IBOutlet UILabel *labelTitle;" in Level1View.h you can access it from Main View:

```<code>Level1View *level1View = [[Level1View alloc] initWithNibName:nil bundle:nil];
[self presentModalViewController:level1View animated:YES];
level1View.labelTitle.text = @"something";
[level1View release];
</code>```

The other thing you shouldn't present the Main View Controller again instead dismiss the Level1View with:

```<code>@implementation Level1View
    -(IBAction)pushBack{
        [self dismissModalViewControllerAnimated:YES];
    }
</code>```

//
and maybe the problem is [[Level1View alloc] initWithNibName:nil bundle:nil] you have to specify the nib you want to load e.g. [[Level1View alloc] initWithNibName:@"Level1View" bundle:nil]

Body:
Im new to iphone development and after lots of reading on it im still trying to figure out how UIViews operate properly. I have been playing about with it and i this is where i am at so far:

I have created a new xcode project using the view-based application. I have my MMAppViewController classes and i created a new UIViewController subclass called "Level1View".

There is a button titled "Level 1" that takes me to the "Level1View" viewController. In this viewController there is there is a "next" button, a "main menu" button (that returns to MMAppViewController) and there is a label, currently titled "Level 1".

My problem is that the code i have used to change the title of label does not work! Does anyone know why this is? Here is my code:

@class MMAppViewController;

@interface MMAppAppDelegate : NSObject <UIApplicationDelegate> {
    UIWindow *window;
    MMAppViewController *viewController;
}

@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet MMAppViewController *viewController;

@end

and

@implementation MMAppViewController

-(IBAction)pushLevel1{

    Level1View *level1View = [[Level1View alloc] initWithNibName:nil bundle:nil];
    [self presentModalViewController:level1View animated:YES];
}
...

and

#import <UIKit/UIKit.h>

@interface Level1View : UIViewController {
    IBOutlet UILabel *labelTitle;

}
-(IBAction)pushBack;
-(IBAction)pushNext;
@end

and

 #import "Level1View.h"
    #import "MMAppViewController.h"

    @implementation Level1View

    -(IBAction)pushBack{

        MMAppViewController *MainView = [[MMAppViewController alloc] initWithNibName:nil bundle:nil];
        [self presentModalViewController:MainView animated:YES];

    }
    -(IBAction)pushNext{

        [labelTitle setText:(@"Thanks for playing :)")];

    }

    - (void)didReceiveMemoryWarning {
    ...

Currently the app runs but the label wont change when i hit the "next" button. Can anyone help?

Body:
are you sure you connected the label in IB?

and if you set a property "@property (nonatomic, retain) IBOutlet UILabel *labelTitle;" in Level1View.h you can access it from Main View:

Level1View *level1View = [[Level1View alloc] initWithNibName:nil bundle:nil];
[self presentModalViewController:level1View animated:YES];
level1View.labelTitle.text = @"something";
[level1View release];

The other thing you shouldn't present the Main View Controller again instead dismiss the Level1View with:

@implementation Level1View
    -(IBAction)pushBack{
        [self dismissModalViewControllerAnimated:YES];
    }

//
and maybe the problem is [[Level1View alloc] initWithNibName:nil bundle:nil] you have to specify the nib you want to load e.g. [[Level1View alloc] initWithNibName:@"Level1View" bundle:nil]


问:
Dependency Injection in scala
I have a trait

```<code>trait Tt[T]{
   //tens of methods
}
</code>```

and

```<code>class St{ tt: Tt[T] =>
  type T = //...
  //some methods
}

object St{
    def apply[T](tt: Tt[T]) = new St with tt //error
}
</code>```

The issue is the objects of Tt are generated by a library. Is there a way to avoid implementing all these tens of methods and just "inject the instance"?

I cannot just pass it as a parameter, because of the type variable declaration that is defined inside the class.

Extracting the type variable declaration to the type parameter is not possible.

答:
How about class St(val tt: Tt[St#T]) { type T = ... }

There is something else with your apply though: St wants the type parameter to Tt to be the same as it's own type T (you gotta start using more letters for these types), but apply is parametrized with T, which is yet another different type, that just happens to use the same letter. So, def apply[T](tt: Tt[T]) = new St(tt) won't compile, it needs to be def apply(tt: Tt(St#T)) = new St(tt)

Title: Dependency Injection in scala

Body:
I have a trait

trait Tt[T]{
   //tens of methods
}

and

class St{ tt: Tt[T] =>
  type T = //...
  //some methods
}

object St{
    def apply[T](tt: Tt[T]) = new St with tt //error
}

The issue is the objects of Tt are generated by a library. Is there a way to avoid implementing all these tens of methods and just "inject the instance"?

I cannot just pass it as a parameter, because of the type variable declaration that is defined inside the class.

Extracting the type variable declaration to the type parameter is not possible.


问:
SAS Summing a dynamic range in array
I have an array with totals for 210 days. I need to find the sum of all 90 day ranges. The new array is med_sum. So med_sum(1) =sum(of Total(32)-total(121)), then med_sum(2)=sum(of total(33)-total(122)), and so on, 90 different times all the way to med_sum(90)=sum(of total(121)-total(210)).
Below is the syntax, but the sum(of) function isn't allowing me to do this and errors out. I have tried quite a few different options but have been unable to find anything that works.
Thank you in advance!!</p>

```<code>data work.total_base_3;
set work.total_base_2;
array med_total(*) total1-total210;
array med_sum(*) avg1-avg90;
do i = 1 to 90;
med_sum(i)=sum(of med_total(i+31)-med_total(i+120));
end;
run;
</code>```

答:
here's a sample that you should be able to extend to your data (so in your case you would change the 3's to 90's):

case 1 Data in rows :

```<code>data test;
keep obs;
do i=1 to 10;
   obs = i;
   output;
end;
run;

data test1;
set test;
keep obs sum;
array x[3];
retain x;
x[mod(_n_ -1,3)+1] = obs;
if (_n_ >= 3)then do;
   sum = 0;
   do i = 1 to 3;
      sum= sum + x[i];
   end;
end;
run;
</code>```

case 2 data in columns (use the test dataset from from above):

```<code>proc transpose data=test out=testrow;
var  obs;
run;

data test2;
set testrow;
array med_total(*) col1-col10;
array med_sum(8) ;
do i = 3 to 10;
  med_sum[i-2]=0;
  do j = 1 +(i-3) to i;
     med_sum(i-2)=med_sum[i-2] + med_total(j);
  end;
end;
run;
</code>```

Title: SAS Summing a dynamic range in array

Body:
I have an array with totals for 210 days. I need to find the sum of all 90 day ranges. The new array is med_sum. So med_sum(1) =sum(of Total(32)-total(121)), then med_sum(2)=sum(of total(33)-total(122)), and so on, 90 different times all the way to med_sum(90)=sum(of total(121)-total(210)).
Below is the syntax, but the sum(of) function isn't allowing me to do this and errors out. I have tried quite a few different options but have been unable to find anything that works.
Thank you in advance!!

data work.total_base_3;
set work.total_base_2;
array med_total(*) total1-total210;
array med_sum(*) avg1-avg90;
do i = 1 to 90;
med_sum(i)=sum(of med_total(i+31)-med_total(i+120));
end;
run;

Body:
here's a sample that you should be able to extend to your data (so in your case you would change the 3's to 90's):

case 1 Data in rows :

data test;
keep obs;
do i=1 to 10;
   obs = i;
   output;
end;
run;

data test1;
set test;
keep obs sum;
array x[3];
retain x;
x[mod(_n_ -1,3)+1] = obs;
if (_n_ >= 3)then do;
   sum = 0;
   do i = 1 to 3;
      sum= sum + x[i];
   end;
end;
run;

case 2 data in columns (use the test dataset from from above):

proc transpose data=test out=testrow;
var  obs;
run;

data test2;
set testrow;
array med_total(*) col1-col10;
array med_sum(8) ;
do i = 3 to 10;
  med_sum[i-2]=0;
  do j = 1 +(i-3) to i;
     med_sum(i-2)=med_sum[i-2] + med_total(j);
  end;
end;
run;


问:
Unexpected SyntaxError: Unexpected token : from JSON data (AngularJS Api Request)
So I'm getting this error and when I click on the link it shows next to it, it takes me to some json response:

```<code>{"link-canonical":"https:\/\/myanimelist.net\/anime\/1\/Cowboy_Bebop",.....}
</code>```

I'm simply making a get request for an anime api. Apparently this colon in the json it retrieves is giving me the error..? I have no idea. My code for the request is definitely working but I just tried it out with another api url which worked fine.

This is the code for the request:

```<code>myApp.controller('mainController', ['$scope', '$resource', function($scope, $resource) {

$scope.animeApi = $resource('http://jikan.me/api/anime/1', {callback: "JSON_CALLBACK"}, { get: { method: "JSONP" }});

$scope.animeResult = $scope.animeApi.get({});
console.log($scope.animeResult);
</code>```

}]);

答:
So you know what to do:</p>

```<code>let str = {"link-canonical":"https:\/\/myanimelist.net\/anime\/1\/Cowboy_Bebop"};
let data = JSON.parse(JSON.stringify(str));
</code>```

Body:
So I'm getting this error and when I click on the link it shows next to it, it takes me to some json response:

{"link-canonical":"https:\/\/myanimelist.net\/anime\/1\/Cowboy_Bebop",.....}

I'm simply making a get request for an anime api. Apparently this colon in the json it retrieves is giving me the error..? I have no idea. My code for the request is definitely working but I just tried it out with another api url which worked fine.

This is the code for the request:

myApp.controller('mainController', ['$scope', '$resource', function($scope, $resource) {

$scope.animeApi = $resource('http://jikan.me/api/anime/1', {callback: "JSON_CALLBACK"}, { get: { method: "JSONP" }});

$scope.animeResult = $scope.animeApi.get({});
console.log($scope.animeResult);

}]);

Body:
So you know what to do:

let str = {"link-canonical":"https:\/\/myanimelist.net\/anime\/1\/Cowboy_Bebop"};
let data = JSON.parse(JSON.stringify(str));


问:
How to create an "Expression" with babylon?
I need to add an objectProperty, but it requires key and value:

t.objectProperty(key, value, ...)

And the value must be an "Expression". I assumed that it must be object expression:

t.objectExpression(properties)

Where "properties" must be an array of ObjectMethod || ObjectProperty || SpreadProperty.

But I wanted to create an ObjectProperty in the first place!
So what is an "Expression" and how can I create it in order to create an ObjectProperty?

答:
Thanks to Bergi, I found an answer.
An example where an object's property value is a string:</p>

```<code>t.objectExpression([
  t.objectProperty(
  t.identifier('key'),
  t.stringLiteral('value'),
)]);
</code>```

Body:
Thanks to Bergi, I found an answer.
An example where an object's property value is a string:

t.objectExpression([
  t.objectProperty(
  t.identifier('key'),
  t.stringLiteral('value'),
)]);


问:
jQuery - Given a DIV with a bunch of
 tags, how to find the first
 that isn't empty
Given a DIV with a lot of paragraph tags:

```<code><div>
 <p></p>
 <p>ADSADASAD ADS ADS  A </p>
 <p>ADSADASAD ADS ADS  A </p>
 <p>ADSADASAD ADS ADS  A </p>
 <p>ADSADASAD ADS ADS  A </p>
</div>
</code>```

How to magically find the first
 which isn't empty using just jQUery? ideas?

答:
I think you can use:</p>

```<code>$('div').find('p:not(:empty):first')
</code>```

Title: jQuery - Given a DIV with a bunch of <P> tags, how to find the first <P> that isn't empty

Body:
Given a DIV with a lot of paragraph tags:

ADSADASAD ADS ADS  A

ADSADASAD ADS ADS  A

ADSADASAD ADS ADS  A

ADSADASAD ADS ADS  A

How to magically find the first
 which isn't empty using just jQUery? ideas?

Body:
I think you can use:

$('div').find('p:not(:empty):first')


问:
Pandas - Drop function error (label not contained in axis)
I have a CSV file that is as the following:

```<code>index,Avg,Min,Max
Build1,56.19,39.123,60.1039
Build2,57.11,40.102,60.2
Build3,55.1134,35.129404123,60.20121
</code>```

Based off my question here I am able to add some relevant information to this csv via this short script:

```<code>import pandas as pd

df = pd.read_csv('newdata.csv')
print(df)

df_out = pd.concat([df.set_index('index'),df.set_index('index').agg(['max','min','mean'])]).rename(index={'max':'Max','min':'Min','mean':'Average'}).reset_index()

with open('newdata.csv', 'w') as f:
    df_out.to_csv(f,index=False)
</code>```

This results in this CSV:

```<code>index,Avg,Min,Max
Build1,56.19,39.123,60.1039
Build2,57.11,40.102,60.2
Build3,55.1134,35.129404123,60.20121
Max,57.11,40.102,60.20121
Min,55.1134,35.129404123,60.1039
Average,56.1378,38.1181347077,60.16837
</code>```

I would like to now have it so I can update this csv. For example if I ran a new build (build4 for instance) I could add that in and then redo the Max, Min, Average rows. My idea is that I therefore delete the rows with labels Max, Min, Average, add my new row, redo the stats. I believe the code I need is as simple as (just for Max but would have lines for Min and Average as well):

```<code>df = pd.read_csv('newdata.csv')
df = df.drop('Max')
</code>```

However this always results in an ValueError: labels ['Max'] not contained in axis

I have created the csv files in sublime text, could this be part of the issue? I have read other SO posts about this and none seem to help my issue.

I am unsure if this allowed but here is a download link to my csv just in case something is wrong with the file itself.

I would be okay with two possible answers:

How to fix this drop issue

How to add more builds and update the statistics (a method without drop)

答:
To delete a particular column in pandas; do simply: </p>

```<code>del df['Max']
</code>```

Body:
I have a CSV file that is as the following:

index,Avg,Min,Max
Build1,56.19,39.123,60.1039
Build2,57.11,40.102,60.2
Build3,55.1134,35.129404123,60.20121

Based off my question here I am able to add some relevant information to this csv via this short script:

import pandas as pd

df = pd.read_csv('newdata.csv')
print(df)

df_out = pd.concat([df.set_index('index'),df.set_index('index').agg(['max','min','mean'])]).rename(index={'max':'Max','min':'Min','mean':'Average'}).reset_index()

with open('newdata.csv', 'w') as f:
    df_out.to_csv(f,index=False)

This results in this CSV:

index,Avg,Min,Max
Build1,56.19,39.123,60.1039
Build2,57.11,40.102,60.2
Build3,55.1134,35.129404123,60.20121
Max,57.11,40.102,60.20121
Min,55.1134,35.129404123,60.1039
Average,56.1378,38.1181347077,60.16837

I would like to now have it so I can update this csv. For example if I ran a new build (build4 for instance) I could add that in and then redo the Max, Min, Average rows. My idea is that I therefore delete the rows with labels Max, Min, Average, add my new row, redo the stats. I believe the code I need is as simple as (just for Max but would have lines for Min and Average as well):

df = pd.read_csv('newdata.csv')
df = df.drop('Max')

However this always results in an ValueError: labels ['Max'] not contained in axis

I have created the csv files in sublime text, could this be part of the issue? I have read other SO posts about this and none seem to help my issue.

I am unsure if this allowed but here is a download link to my csv just in case something is wrong with the file itself.

I would be okay with two possible answers:

How to fix this drop issue

How to add more builds and update the statistics (a method without drop)

Body:
To delete a particular column in pandas; do simply:

del df['Max']


答:
Did you bind the Label in Interface Builder to the labelTitle outlet in your Level1View?

If you forget that step, the outlets won't work.  Even after several years, I still forget this step sometimes.

--Mike

Title: Objective-c Novice - Needs help with UIViews


问:
How to change caret (cursor) blinking rate in NetBeans?
How to change caret (cursor) blinking rate in NetBeans? (7.0)

NetBeans developers say that this is supported as a Swing option, see Bug 124211 - Cursor blink rate too fast but I can't figure out the name of this Swing option to set from the command line.

The closest example of setting Swing option that I found is setting look and feel by putting
-J-Dswing.defaultlaf=com.sun.java.swing.plaf.windows.WindowsLookAndFeel to the netbeans.conf.

答:
If you would like to disable it for all editors, instead of just the Java editor, add the following:

```<code><entry javaType="java.lang.Integer" name="caret-blink-rate" xml:space="preserve">
    <value>2147483647</value>
</entry>
</code>```

under the <editor-preferences> element to the file:

```<code>config/Editors/Preferences/org-netbeans-modules-editor-settings-CustomPreferences.xml
</code>```

The full paths are:

On Mac:

```<code>~/Library/Application Support/NetBeans/8.2/config/Editors/Preferences/org-netbeans-modules-editor-settings-CustomPreferences.xml
</code>```

On Windows:

```<code>%APPDATA%\NetBeans\8.2\config\Editors\Preferences\org-netbeans-modules-editor-settings-CustomPreferences.xml
</code>```

Source: https://forums.netbeans.org/topic9561.html

Body:
If you would like to disable it for all editors, instead of just the Java editor, add the following:

<entry javaType="java.lang.Integer" name="caret-blink-rate" xml:space="preserve">
    <value>2147483647</value>
</entry>

under the <editor-preferences> element to the file:

config/Editors/Preferences/org-netbeans-modules-editor-settings-CustomPreferences.xml

The full paths are:

On Mac:

~/Library/Application Support/NetBeans/8.2/config/Editors/Preferences/org-netbeans-modules-editor-settings-CustomPreferences.xml

On Windows:

%APPDATA%\NetBeans\8.2\config\Editors\Preferences\org-netbeans-modules-editor-settings-CustomPreferences.xml

Source: https://forums.netbeans.org/topic9561.html


问:
How to plot time series in seaborn with one day a x label?
I have a dataframe which represents a time series of five days with one day 48 rows of data like:

```<code>   Density Value     start time
       0.328336  2012-01-16 00:00:00
       1.195605  2012-01-16 00:30:00
       2.398546  2012-01-16 01:00:00
       1.320956  2012-01-16 01:30:00
       1.292287  2012-01-16 02:00:00
       1.286741  2012-01-16 02:30:00
       ...
       0.199826  2012-01-20 23:00:00
       0.437794  2012-01-20 23:30:00
</code>```

I tried to use seaborn to draw a time series graph with one day only one label on time axis, which means there are only 5 labels (from 2012-01-16 to 2012-01-20) on x-axis. I have tried seaborn.tsplot like sns.tsplot(data=density_list,time=start_time_list) but only get the axis labels as the following picture shows:

I am wondering how I can get the x labels I want in this case. Thanks!

答:
Thanks to the suggestion from @Vinícius Aguiar, I followed the answer in Possible duplicate of Seaborn tsplot does not show datetimes on x axis well and modified it to get the labels I want.

When I use ax.xaxis.set_major_locator(mdates.AutoDateLocator()), I get the result like  and after I read the docs I tried mdates.DayLocator(interval=1) and it works!

Body:
I have a dataframe which represents a time series of five days with one day 48 rows of data like:

   Density Value     start time
       0.328336  2012-01-16 00:00:00
       1.195605  2012-01-16 00:30:00
       2.398546  2012-01-16 01:00:00
       1.320956  2012-01-16 01:30:00
       1.292287  2012-01-16 02:00:00
       1.286741  2012-01-16 02:30:00
       ...
       0.199826  2012-01-20 23:00:00
       0.437794  2012-01-20 23:30:00

I tried to use seaborn to draw a time series graph with one day only one label on time axis, which means there are only 5 labels (from 2012-01-16 to 2012-01-20) on x-axis. I have tried seaborn.tsplot like sns.tsplot(data=density_list,time=start_time_list) but only get the axis labels as the following picture shows:

I am wondering how I can get the x labels I want in this case. Thanks!


问:
Compiling vs Transpiling
While searching about the difference, I came across these definitions:

Compiling is the general term for taking source code written in one language and transforming into another.

Transpiling is a specific term for taking source code written in one language and transforming into another language that has a similar level of abstraction.

I understand what Abstraction is.

But what does "similar level of abstraction" mean in the above definition? And how do we find the level of abstraction in a language?

答:
Here's a sort of descriptive way to answer

If you think of layers of abstraction as this example:

```<code>(1) CPU-level (actual logic gates on the CPU)
(2)machine code
(3)assembly code
(4)[C/C++, JVM/bytecode]
(5)[JavaScript, Python]
</code>```

A compiler goes to a lower level (lower number). A transpiler switches from one language (or version of a language) to another at the same number.

Title: Compiling vs Transpiling

Body:
Here's a sort of descriptive way to answer

If you think of layers of abstraction as this example:

(1) CPU-level (actual logic gates on the CPU)
(2)machine code
(3)assembly code
(4)[C/C++, JVM/bytecode]
(5)[JavaScript, Python]

A compiler goes to a lower level (lower number). A transpiler switches from one language (or version of a language) to another at the same number.


问:
Class Not Found when executing Java Web App
I'm very new to the Java landscape (Eclipse, Spring, etc.) and just walking through some introductory tutorials at the moment.  I just finished a Hello World tutorial for Spring MVC, with a simple page that then posts to another action.  Straightforward enough.

I then went on to tinker a bit with the working result of that tutorial.  My first attempt is to create another project in Eclipse with just some simple packages containing POJOs.  The idea being to have something portable which different applications could use.  (Intended to be the equivalent of a "Class Library" project in the .NET world.)

That project has one package, with one interface (IWorld) and one class (HelloWorld).  In my Spring MVC project I then add the other project to the build path and create an instance of that object in the controller.  The compiler says everything's fine:

```<code>package com.sandbox.application.mvctest.controllers;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.sandbox.domain.models.*;

@Controller
public class HelloWorldController {

    @RequestMapping("/")
    public String hello() {
        IWorld world = new HelloWorld();
        world.speak();
        return "hello";
        //TODO: Return a ModelAndView instead
    }

    @RequestMapping(value = "/hi", method = RequestMethod.GET)
    public String hi(@RequestParam("name") String name, Model model) {
        String message = "Hi " + name + "!";
        model.addAttribute("message", message);
        return "hi";
    }

}
</code>```

The .speak() method doesn't do anything of note, just returns a value which the controller isn't using yet.  The intent of course is to start building up some features in the models rather than just in the controllers and views, building more of a rich domain model.

Eclipse doesn't complain about the code, everything seems to compile just fine.  But when executing on Tomcat I get an exception:

```<code>Jul 05, 2017 12:36:49 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Allocate exception for servlet [springDispatcher]
java.lang.ClassNotFoundException: com.sandbox.domain.models.IWorld
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1269)
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1104)
    at java.lang.Class.getDeclaredMethods0(Native Method)
    [and so on...]
</code>```

My Googling has proved fruitless so far, likely because I don't always understand what I'm finding.  For example, there are some posts which advise to correct something in a pom.xml file.  I have no such file.  Is this related to Spring's dependency injection?  Should I be using that?  I wouldn't have considered this to be an injectable dependency, I'm just creating an instance directly.  But then I'm also approaching this from a deeply dogmatic .NET mindset, so all bets are off.

What am I missing here?

答:
you are using springframework, so you can create the bean of the com.sandbox.domain.models.IWorld and use the @Autowired tp Dependency Injection. refer code

```<code>@Autowired
private IWorld world;
</code>```

Body:
I'm very new to the Java landscape (Eclipse, Spring, etc.) and just walking through some introductory tutorials at the moment.  I just finished a Hello World tutorial for Spring MVC, with a simple page that then posts to another action.  Straightforward enough.

I then went on to tinker a bit with the working result of that tutorial.  My first attempt is to create another project in Eclipse with just some simple packages containing POJOs.  The idea being to have something portable which different applications could use.  (Intended to be the equivalent of a "Class Library" project in the .NET world.)

That project has one package, with one interface (IWorld) and one class (HelloWorld).  In my Spring MVC project I then add the other project to the build path and create an instance of that object in the controller.  The compiler says everything's fine:

package com.sandbox.application.mvctest.controllers;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.sandbox.domain.models.*;

@Controller
public class HelloWorldController {

    @RequestMapping("/")
    public String hello() {
        IWorld world = new HelloWorld();
        world.speak();
        return "hello";
        //TODO: Return a ModelAndView instead
    }

    @RequestMapping(value = "/hi", method = RequestMethod.GET)
    public String hi(@RequestParam("name") String name, Model model) {
        String message = "Hi " + name + "!";
        model.addAttribute("message", message);
        return "hi";
    }

}

The .speak() method doesn't do anything of note, just returns a value which the controller isn't using yet.  The intent of course is to start building up some features in the models rather than just in the controllers and views, building more of a rich domain model.

Eclipse doesn't complain about the code, everything seems to compile just fine.  But when executing on Tomcat I get an exception:

Jul 05, 2017 12:36:49 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Allocate exception for servlet [springDispatcher]
java.lang.ClassNotFoundException: com.sandbox.domain.models.IWorld
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1269)
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1104)
    at java.lang.Class.getDeclaredMethods0(Native Method)
    [and so on...]

My Googling has proved fruitless so far, likely because I don't always understand what I'm finding.  For example, there are some posts which advise to correct something in a pom.xml file.  I have no such file.  Is this related to Spring's dependency injection?  Should I be using that?  I wouldn't have considered this to be an injectable dependency, I'm just creating an instance directly.  But then I'm also approaching this from a deeply dogmatic .NET mindset, so all bets are off.

What am I missing here?

Body:
you are using springframework, so you can create the bean of the com.sandbox.domain.models.IWorld and use the @Autowired tp Dependency Injection. refer code

@Autowired
private IWorld world;


问:
Download file via PHP
I'm trying to download a zip file without revealing the URL to the user. The file should only be accessible by authorized users.

Currently I'm doing this:

```<code>// check authentication and request method etc...
// ...

$file = '../../filename.zip';
$filesize = filesize($file);
header('Content-Description: File Transfer');
header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename="' . basename($file) . '"');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: private');
header('Content-Length: ' . $filesize);
ob_clean();
flush();

echo readfile($file);

die();
</code>```

And I can see the file is downloaded somehow in the Chrome network tab (it shows in the Response tab) and ~3MB are transferred (which is the filesize), but the file isn't downloaded in the browser.

I'm doing a simple GET request, btw.

Thanks for your help,
Tobias

EDIT: Okay, apparently I also had an error on the client side and now the file is being downloaded in the browser, but it's only a 1KB zip containing Response with status: 200 OK for URL: xxx.

My request looks like this:

```<code>let headers = new Headers({'Accept': 'application/zip'});
let options = new RequestOptions({ headers: headers, responseType: ResponseContentType.Blob });
this.authHttp.post(environment.apiUrl + 'rewards/download/', data, options)
  .map(res => new Blob([res],{ type: 'application/zip' }))
  .catch((error:any) => Observable.throw(error.json().error || 'Server error'))
  .subscribe(
    data => {
      //console.log(data);
      window.location.href = window.URL.createObjectURL(data);
    },
    error => {
      console.log("Error downloading file.");
    },
    () => console.log("Download completed."));
</code>```

EDIT2: Okay, got it. Apparently I had to use .map(res => new Blob([res.json()],{ type: 'application/zip' })) in the request. Also now I'm using FileSaver.js instead of window.location, but I don't think that affected the problem.

答: Okay, got it. Apparently I had to use .map(res => new Blob([res.json()],{ type: 'application/zip' })) in the request. Also now I'm using FileSaver.js instead of window.location, but I don't think that affected the problem.</p>

Title: Download file via PHP

Body:
I'm trying to download a zip file without revealing the URL to the user. The file should only be accessible by authorized users.

Currently I'm doing this:

// check authentication and request method etc...
// ...

$file = '../../filename.zip';
$filesize = filesize($file);
header('Content-Description: File Transfer');
header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename="' . basename($file) . '"');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: private');
header('Content-Length: ' . $filesize);
ob_clean();
flush();

echo readfile($file);

die();

And I can see the file is downloaded somehow in the Chrome network tab (it shows in the Response tab) and ~3MB are transferred (which is the filesize), but the file isn't downloaded in the browser.

I'm doing a simple GET request, btw.

Thanks for your help,
Tobias

EDIT: Okay, apparently I also had an error on the client side and now the file is being downloaded in the browser, but it's only a 1KB zip containing Response with status: 200 OK for URL: xxx.

My request looks like this:

let headers = new Headers({'Accept': 'application/zip'});
let options = new RequestOptions({ headers: headers, responseType: ResponseContentType.Blob });
this.authHttp.post(environment.apiUrl + 'rewards/download/', data, options)
  .map(res => new Blob([res],{ type: 'application/zip' }))
  .catch((error:any) => Observable.throw(error.json().error || 'Server error'))
  .subscribe(
    data => {
      //console.log(data);
      window.location.href = window.URL.createObjectURL(data);
    },
    error => {
      console.log("Error downloading file.");
    },
    () => console.log("Download completed."));

EDIT2: Okay, got it. Apparently I had to use .map(res => new Blob([res.json()],{ type: 'application/zip' })) in the request. Also now I'm using FileSaver.js instead of window.location, but I don't think that affected the problem.