问:
Task Canceled exception on RavenDB when creating indexes
I'm having an issue trying to create indexes on RavenDB 3.5

When creating more than 3 indexes the application just dies, getting a

Unable to connect to the remote server Status Code: ConnectFailure

The index creation code is farely straight forward:

```<code>    private static void CreateIndexes(IDocumentStore documentStore)
    {
        new PurchaseOrder_QueryByExternalReference().Execute(documentStore);
        new SupplierDocument_QueryBySupplierName().Execute(documentStore);
        new ProductDocument_QueryByProductIdAndName().Execute(documentStore);
        new PurchaseOrderLine_QueryableIndex().Execute(documentStore);
        new PurchaseOrderLine_ForPurchaseOrderIndex().Execute(documentStore);
    }
</code>```

But the same happens if the

IndexCreation.CreateIndexes(typeof(MyIndexClass).Assembly, store);

method is called. This happens with any 3 indexes from the list on any order.

Full stack-trace is this:

exception
  {"A task was canceled."}
      Data: {System.Collections.ListDictionaryInternal}
      Etag: null
      HResult: -2146233088
      HelpLink: null
      InnerException: null
      Message: "A task was canceled."
      Response: {StatusCode: 503, ReasonPhrase: 'Service Unavailable', Version: 1.1, Content: , Headers:
  {
  }}
      ResponseString: "Unable to connect to the remote server Status Code: ConnectFailure"
      Source: "Raven.Client.Lightweight"
      StackTrace: "   at Raven.Client.Connection.Implementation.HttpJsonRequest.<>c__DisplayClass36_0.<b__0>d.MoveNext() in C:\Builds\RavenDB-Stable-3.5\Raven.Client.Lightweight\Connection\Implementation\HttpJsonRequest.cs:line 258
      --- End of stack trace from previous location where exception was thrown ---
      at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
      at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
      at Raven.Client.Connection.Implementation.HttpJsonRequest.d__381.MoveNext() in C:\\Builds\\RavenDB-Stable-3.5\\Raven.Client.Lightweight\\Connection\\Implementation\\HttpJsonRequest.cs:line 312
      --- End of stack trace from previous location where exception was thrown ---
      at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
      at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
      at Raven.Client.Connection.Implementation.HttpJsonRequest.<ReadResponseJsonAsync>d__35.MoveNext() in C:\\Builds\\RavenDB-Stable-3.5\\Raven.Client.Lightweight\\Connection\\Implementation\\HttpJsonRequest.cs:line 221
      --- End of stack trace from previous location where exception was thrown ---
      at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
      at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
      at Raven.Client.Connection.Async.AsyncServerClient.<>c__DisplayClass69_0.<<GetIndexAsync>b__0>d.MoveNext() in C:\\Builds\\RavenDB-Stable-3.5\\Raven.Client.Lightweight\\Connection\\Async\\AsyncServerClient.cs:line 726
      --- End of stack trace from previous location where exception was thrown ---
      at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
      at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
      at Raven.Client.Connection.ReplicationInformerBase1.d__341.MoveNext() in C:\\Builds\\RavenDB-Stable-3.5\\Raven.Client.Lightweight\\Connection\\ReplicationInformerBase.cs:line 417
      --- End of stack trace from previous location where exception was thrown ---
      at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
      at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
      at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
      at Raven.Client.Connection.ReplicationInformerBase1.d__331.MoveNext() in C:\\Builds\\RavenDB-Stable-3.5\\Raven.Client.Lightweight\\Connection\\ReplicationInformerBase.cs:line 316
      --- End of stack trace from previous location where exception was thrown ---
      at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
      at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
      at Raven.Client.Connection.Async.AsyncServerClient.<ExecuteWithReplication>d__1641.MoveNext() in C:\Builds\RavenDB-Stable-3.5\Raven.Client.Lightweight\Connection\Async\AsyncServerClient.cs:line 0
      --- End of stack trace from previous location where exception was thrown ---
      at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
      at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
      at Raven.Abstractions.Util.AsyncHelpers.<>c__DisplayClass1_11.<<RunSync>b__0>d.MoveNext() in C:\\Builds\\RavenDB-Stable-3.5\\Raven.Abstractions\\Util\\AsyncHelpers.cs:line 75
      --- End of stack trace from previous location where exception was thrown ---
      at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
      at Raven.Abstractions.Util.AsyncHelpers.RunSync[T](Func1 task) in C:\Builds\RavenDB-Stable-3.5\Raven.Abstractions\Util\AsyncHelpers.cs:line 89
      at Raven.Client.Connection.ServerClient.GetIndex(String name) in C:\Builds\RavenDB-Stable-3.5\Raven.Client.Lightweight\Connection\ServerClient.cs:line 222\
     at Raven.Client.Indexes.AbstractIndexCreationTask.Execute(IDatabaseCommands databaseCommands, DocumentConvention documentConvention) in C:\Builds\RavenDB-Stable-3.5\Raven.Client.Lightweight\Indexes\AbstractIndexCreationTask.cs:line 304
     at Raven.Client.DocumentStoreBase.ExecuteIndex(AbstractIndexCreationTask indexCreationTask) in C:\Builds\RavenDB-Stable-3.5\Raven.Client.Lightweight\DocumentStoreBase.cs:line 102
     at Raven.Client.Indexes.AbstractIndexCreationTask.Execute(IDocumentStore store) in C:\Builds\RavenDB-Stable-3.5\Raven.Client.Lightweight\Indexes\AbstractIndexCreationTask.cs:line 221
     at Persistence.Database.Adapter.RavenDb.RavenDbDocumentStoreFactory.CreateIndexes(IDocumentStore documentStore) in \my\route\Persistence.Database.Adapter\RavenDb\RavenDbDocumentStoreFactory.cs:line 50
     at Persistence.Database.Adapter.RavenDb.RavenDbDocumentStoreFactory.ConfigureDocumentStore(IDocumentStore documentStore) in \my\route\Persistence.Database.Adapter\RavenDb\RavenDbDocumentStoreFactory.cs:line 38
     at Persistence.Database.Adapter.RavenDb.RavenDbDocumentStoreFactory.Create(String ravenDbLocation, String ravenDbDatabase) in \my\route\Persistence.Database.Adapter\RavenDb\RavenDbDocumentStoreFactory.cs:line 22
     at Persistence.Database.Adapter.PersistenceAdapter.<.ctor>b__8_0() in \my\route\Persistence.Database.Adapter\PersistenceAdapter.cs:line 53
     at Persistence.Database.Adapter.PersistenceAdapter.RegisterRavenDbUtilities() in \my\route\Persistence.Database.Adapter\PersistenceAdapter.cs:line 175
     at Persistence.Database.Adapter.PersistenceAdapter.RegisterRavenLogic() in \my\route\Persistence.Database.Adapter\PersistenceAdapter.cs:line 86
     at Persistence.Database.Adapter.PersistenceAdapter.Initialize() in \my\route\Persistence.Database.Adapter\PersistenceAdapter.cs:line 74
     at My-Program.ConfigurePersistentAdapter(Settings settings) in \my\route\MessageQueueListener\MessageQueueListenerService.cs:line 153
     at My-Program.AddBootstrapperExtension() in \my\route\net-stock-purchasing-service.MessageQueueListener\MessageQueueListenerService.cs:line 118
     at My-Program.Startup() in \my\route\net-stock-purchasing-service.MessageQueueListener\MessageQueueListenerService.cs:line 78"
      StatusCode: ServiceUnavailable
      TargetSite: {Void MoveNext()}

答:
When RavenDB 3.5 was release, something broke in the client package.

If you are running RavenDB.Client from 3.0.30000 to 3.0.30179, then it should work.

If you are running a higher version, then you will encounter (in certain conditions) this exception. To resolve that, you can use an alternate API: store.DatabaseCommands.PutIndexes.

```<code>var indexes = new List<AbstractIndexCreationTask>();
indexes.Add(new MyIndex1());
indexes.Add(new MyIndex2());
indexes.Add(new MyIndex....());

var transfos = new List<AbstractTransformerCreationTask>();
transfos.Add(new MyTransformer1());
transfos.Add(new MyTransformer2());
transfos.Add(new MyTransformer...());

// put indexes in 1 command
var indexesToPut = IndexCreation.CreateIndexesToAdd(indexes, documentStore.Conventions);
documentStore.DatabaseCommands.PutIndexes(indexesToPut);

// don't forget transformers
foreach (var item in transfos)
{
    item.Execute(Store);
}
</code>```

This should solve your problem.

I was encountering this problem after upgrading my client package. Note that the exception occurred only in console applications and not in my web applications.

Body:
I'm having an issue trying to create indexes on RavenDB 3.5

When creating more than 3 indexes the application just dies, getting a

Unable to connect to the remote server Status Code: ConnectFailure

The index creation code is farely straight forward:

    private static void CreateIndexes(IDocumentStore documentStore)
    {
        new PurchaseOrder_QueryByExternalReference().Execute(documentStore);
        new SupplierDocument_QueryBySupplierName().Execute(documentStore);
        new ProductDocument_QueryByProductIdAndName().Execute(documentStore);
        new PurchaseOrderLine_QueryableIndex().Execute(documentStore);
        new PurchaseOrderLine_ForPurchaseOrderIndex().Execute(documentStore);
    }

But the same happens if the

IndexCreation.CreateIndexes(typeof(MyIndexClass).Assembly, store);

method is called. This happens with any 3 indexes from the list on any order.

Full stack-trace is this:

exception
  {"A task was canceled."}
      Data: {System.Collections.ListDictionaryInternal}
      Etag: null
      HResult: -2146233088
      HelpLink: null
      InnerException: null
      Message: "A task was canceled."
      Response: {StatusCode: 503, ReasonPhrase: 'Service Unavailable', Version: 1.1, Content: , Headers:
  {
  }}
      ResponseString: "Unable to connect to the remote server Status Code: ConnectFailure"
      Source: "Raven.Client.Lightweight"
      StackTrace: "   at Raven.Client.Connection.Implementation.HttpJsonRequest.<>c__DisplayClass36_0.<b__0>d.MoveNext() in C:\Builds\RavenDB-Stable-3.5\Raven.Client.Lightweight\Connection\Implementation\HttpJsonRequest.cs:line 258
      --- End of stack trace from previous location where exception was thrown ---
      at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
      at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
      at Raven.Client.Connection.Implementation.HttpJsonRequest.d__381.MoveNext() in C:\\Builds\\RavenDB-Stable-3.5\\Raven.Client.Lightweight\\Connection\\Implementation\\HttpJsonRequest.cs:line 312
      --- End of stack trace from previous location where exception was thrown ---
      at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
      at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
      at Raven.Client.Connection.Implementation.HttpJsonRequest.<ReadResponseJsonAsync>d__35.MoveNext() in C:\\Builds\\RavenDB-Stable-3.5\\Raven.Client.Lightweight\\Connection\\Implementation\\HttpJsonRequest.cs:line 221
      --- End of stack trace from previous location where exception was thrown ---
      at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
      at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
      at Raven.Client.Connection.Async.AsyncServerClient.<>c__DisplayClass69_0.<<GetIndexAsync>b__0>d.MoveNext() in C:\\Builds\\RavenDB-Stable-3.5\\Raven.Client.Lightweight\\Connection\\Async\\AsyncServerClient.cs:line 726
      --- End of stack trace from previous location where exception was thrown ---
      at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
      at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
      at Raven.Client.Connection.ReplicationInformerBase1.d__341.MoveNext() in C:\\Builds\\RavenDB-Stable-3.5\\Raven.Client.Lightweight\\Connection\\ReplicationInformerBase.cs:line 417
      --- End of stack trace from previous location where exception was thrown ---
      at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
      at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
      at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
      at Raven.Client.Connection.ReplicationInformerBase1.d__331.MoveNext() in C:\\Builds\\RavenDB-Stable-3.5\\Raven.Client.Lightweight\\Connection\\ReplicationInformerBase.cs:line 316
      --- End of stack trace from previous location where exception was thrown ---
      at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
      at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
      at Raven.Client.Connection.Async.AsyncServerClient.<ExecuteWithReplication>d__1641.MoveNext() in C:\Builds\RavenDB-Stable-3.5\Raven.Client.Lightweight\Connection\Async\AsyncServerClient.cs:line 0
      --- End of stack trace from previous location where exception was thrown ---
      at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
      at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
      at Raven.Abstractions.Util.AsyncHelpers.<>c__DisplayClass1_11.<<RunSync>b__0>d.MoveNext() in C:\\Builds\\RavenDB-Stable-3.5\\Raven.Abstractions\\Util\\AsyncHelpers.cs:line 75
      --- End of stack trace from previous location where exception was thrown ---
      at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
      at Raven.Abstractions.Util.AsyncHelpers.RunSync[T](Func1 task) in C:\Builds\RavenDB-Stable-3.5\Raven.Abstractions\Util\AsyncHelpers.cs:line 89
      at Raven.Client.Connection.ServerClient.GetIndex(String name) in C:\Builds\RavenDB-Stable-3.5\Raven.Client.Lightweight\Connection\ServerClient.cs:line 222\
     at Raven.Client.Indexes.AbstractIndexCreationTask.Execute(IDatabaseCommands databaseCommands, DocumentConvention documentConvention) in C:\Builds\RavenDB-Stable-3.5\Raven.Client.Lightweight\Indexes\AbstractIndexCreationTask.cs:line 304
     at Raven.Client.DocumentStoreBase.ExecuteIndex(AbstractIndexCreationTask indexCreationTask) in C:\Builds\RavenDB-Stable-3.5\Raven.Client.Lightweight\DocumentStoreBase.cs:line 102
     at Raven.Client.Indexes.AbstractIndexCreationTask.Execute(IDocumentStore store) in C:\Builds\RavenDB-Stable-3.5\Raven.Client.Lightweight\Indexes\AbstractIndexCreationTask.cs:line 221
     at Persistence.Database.Adapter.RavenDb.RavenDbDocumentStoreFactory.CreateIndexes(IDocumentStore documentStore) in \my\route\Persistence.Database.Adapter\RavenDb\RavenDbDocumentStoreFactory.cs:line 50
     at Persistence.Database.Adapter.RavenDb.RavenDbDocumentStoreFactory.ConfigureDocumentStore(IDocumentStore documentStore) in \my\route\Persistence.Database.Adapter\RavenDb\RavenDbDocumentStoreFactory.cs:line 38
     at Persistence.Database.Adapter.RavenDb.RavenDbDocumentStoreFactory.Create(String ravenDbLocation, String ravenDbDatabase) in \my\route\Persistence.Database.Adapter\RavenDb\RavenDbDocumentStoreFactory.cs:line 22
     at Persistence.Database.Adapter.PersistenceAdapter.<.ctor>b__8_0() in \my\route\Persistence.Database.Adapter\PersistenceAdapter.cs:line 53
     at Persistence.Database.Adapter.PersistenceAdapter.RegisterRavenDbUtilities() in \my\route\Persistence.Database.Adapter\PersistenceAdapter.cs:line 175
     at Persistence.Database.Adapter.PersistenceAdapter.RegisterRavenLogic() in \my\route\Persistence.Database.Adapter\PersistenceAdapter.cs:line 86
     at Persistence.Database.Adapter.PersistenceAdapter.Initialize() in \my\route\Persistence.Database.Adapter\PersistenceAdapter.cs:line 74
     at My-Program.ConfigurePersistentAdapter(Settings settings) in \my\route\MessageQueueListener\MessageQueueListenerService.cs:line 153
     at My-Program.AddBootstrapperExtension() in \my\route\net-stock-purchasing-service.MessageQueueListener\MessageQueueListenerService.cs:line 118
     at My-Program.Startup() in \my\route\net-stock-purchasing-service.MessageQueueListener\MessageQueueListenerService.cs:line 78"
      StatusCode: ServiceUnavailable
      TargetSite: {Void MoveNext()}

Body:
When RavenDB 3.5 was release, something broke in the client package.

If you are running RavenDB.Client from 3.0.30000 to 3.0.30179, then it should work.

If you are running a higher version, then you will encounter (in certain conditions) this exception. To resolve that, you can use an alternate API: store.DatabaseCommands.PutIndexes.

var indexes = new List<AbstractIndexCreationTask>();
indexes.Add(new MyIndex1());
indexes.Add(new MyIndex2());
indexes.Add(new MyIndex....());

var transfos = new List<AbstractTransformerCreationTask>();
transfos.Add(new MyTransformer1());
transfos.Add(new MyTransformer2());
transfos.Add(new MyTransformer...());

// put indexes in 1 command
var indexesToPut = IndexCreation.CreateIndexesToAdd(indexes, documentStore.Conventions);
documentStore.DatabaseCommands.PutIndexes(indexesToPut);

// don't forget transformers
foreach (var item in transfos)
{
    item.Execute(Store);
}

This should solve your problem.

I was encountering this problem after upgrading my client package. Note that the exception occurred only in console applications and not in my web applications.


来源: stackexchange

问:
Back button does not show up in navigation controller
I have added a show segue from table cell in one view controller to another table view embedded in a navigation controller. When I click on the cell in the first view the segue works as expected and brings up the new view. However, the "Back" button (with the title of the original view) does not appear in the navigation bar.

I searched SO and found a number of such questions asked in the past (both for Swift and Objective-C). Most of them suggest that the first view needs a title for this to work. I do have a title. I even added one programmatically, just in case. That did not help. One of the answers suggested to add an identifier to the segue; that didn't help me either.

How else can I debug this issue?

答: Verify you are not hiding backbutton in destination controller...</p>

ContentLicense: CC BY-SA 3.0


问:
GCC Compiler options -wno-four-char-constants and -wno-multichar
Couldn't find any documentation on -Wno-four-char-constants, however I suspect that it is similar to -Wno-multichar. Am I correct?

答:
They're related but not the same thing.

Compiling with the -Wall --pedantic flags, the assignment:

```<code>int i = 'abc';
</code>```

produces:

warning: multi-character character constant [-Wmultichar]

with both GCC and CLANG, while:

```<code> int i = 'abcd';
</code>```

produces:

GCC warning: multi-character character constant [-Wmultichar]

CLANG warning: multi-character character constant [-Wfour-char-constants]

The standard (C99 standard with corrigenda TC1, TC2 and TC3 included, subsection 6.4.4.4 - character constants) states that:

The value of an integer character constant containing more than one character (e.g., 'ab'), [...] is implementation-defined.

A multi-char always resolves to an int but, since the order in which the characters are packed into one int is not specified, portable use of multi-character constants is difficult (the exact value is implementation-dependent).

Also compilers differ in how they handle incomplete multi-chars (such as 'abc').

Some compilers pad on the left, some on the right, regardless of endian-ness (some compilers may not pad at all).

Someone who can accept the portability problems of a complete multi-char may anyway want a warning for an incomplete one (-Wmultichar -Wno-four-char-constants).

Body:
They're related but not the same thing.

Compiling with the -Wall --pedantic flags, the assignment:

int i = 'abc';

produces:

warning: multi-character character constant [-Wmultichar]

with both GCC and CLANG, while:

 int i = 'abcd';

produces:

GCC warning: multi-character character constant [-Wmultichar]

CLANG warning: multi-character character constant [-Wfour-char-constants]

The standard (C99 standard with corrigenda TC1, TC2 and TC3 included, subsection 6.4.4.4 - character constants) states that:

The value of an integer character constant containing more than one character (e.g., 'ab'), [...] is implementation-defined.

A multi-char always resolves to an int but, since the order in which the characters are packed into one int is not specified, portable use of multi-character constants is difficult (the exact value is implementation-dependent).

Also compilers differ in how they handle incomplete multi-chars (such as 'abc').

Some compilers pad on the left, some on the right, regardless of endian-ness (some compilers may not pad at all).

Someone who can accept the portability problems of a complete multi-char may anyway want a warning for an incomplete one (-Wmultichar -Wno-four-char-constants).


问:
Is DispatchMessage multithreaded?
I'm using a simple loop to process windows message to render a window:

```<code>while (GetMessage(&msg, NULL, 0, 0)>0)
{
    TranslateMessage(&msg);
    DispatchMessage(&msg);
}
</code>```

And I though I had only on e thread in my application but adding some OutputDebugString in the WM_PAINT and WM_CHAR portions I see that a WM_PAINT is called in the middle of a method I call in WM_CHAR which I don't see how it is possible without have several threads.

So my question is simple, does this loop use several threads to handle window messages ?

Thanks

答:
No, DispatchMessage does not use other threads to perform its work. You can check this yourself by including the thread ID in your logging output.

What you are likely observing is some re-entrant behaviour. Perhaps you called a function that in turn called RedrawWindow, or similar. That function in turn calls your window procedure, leading to the behaviour that you observe.

Title: Is DispatchMessage multithreaded?

Body:
I'm using a simple loop to process windows message to render a window:

while (GetMessage(&msg, NULL, 0, 0)>0)
{
    TranslateMessage(&msg);
    DispatchMessage(&msg);
}

And I though I had only on e thread in my application but adding some OutputDebugString in the WM_PAINT and WM_CHAR portions I see that a WM_PAINT is called in the middle of a method I call in WM_CHAR which I don't see how it is possible without have several threads.

So my question is simple, does this loop use several threads to handle window messages ?

Thanks


问:
How to add time to a timestamp in sqlite
I have two fields in my table : last_service_date and the next_service_date. The last_service_date has a default timestamp. What I want is to add 3 months to the next_service_date. Is that possible?

答:
You can just run a simple sql command

```<code>UPDATE tablename SET next_service_date = last_service_date + (60*60*24*30*3);
</code>```

That would do the job, but keep in mind that this piece of code changes every entry in the table! You may want to add a LIMIT to that.

Also, I assumed you wanted to add 3 months to the last_service_date. You may need to change that accordingly.

Some months may also have more or less than 30 days, which I used as a base.

Body:
You can just run a simple sql command

UPDATE tablename SET next_service_date = last_service_date + (60*60*24*30*3);

That would do the job, but keep in mind that this piece of code changes every entry in the table! You may want to add a LIMIT to that.

Also, I assumed you wanted to add 3 months to the last_service_date. You may need to change that accordingly.

Some months may also have more or less than 30 days, which I used as a base.


问:
Windows CloudFormation Script, MetaData commands are not running
Below is my CloudFormation template for creating a windows EC2 instance with Java and Tomcat installed on it. However, the nothing from the MetaData is being executed. I login to the created EC2 instance, and none of the specified folders in the metadata can be found. What is my CloudFormation script missing?

Thank you

```<code>{
"AWSTemplateFormatVersion": "2010-09-09",
"Description": "Script to create Windows AMI",
"Metadata": {
    "AWS::CloudFormation::Designer": {
        "94153bdc-589b-4aa8-b859-5e84a1051a50": {
            "size": {
                "width": 60,
                "height": 60
            },
            "position": {
                "x": 280,
                "y": 110
            },
            "z": 1,
            "embeds": []
        }
    }
},
"Parameters": {},
"Rules": {},
"Mappings": {},
"Resources": {
    "JavaTomcatEC2Instance": {
        "Type": "AWS::EC2::Instance",
        "Properties": {
            "ImageId": "ami-06b19063",
            "InstanceType": "t2.micro",
            "KeyName": "WindowsTest"
        },
        "Metadata": {
            "AWS::CloudFormation::Init": {
                "configSets": {
                    "config": [
                        "setup"
                    ]
                },
                "setup": {
                    "Install-Java-Tomcat-set-env-variables-paths": {
                        "files": {
                            "c:\\cfn\\modules\\jdk-8u151-windows-x64.exe": {
                                "source": "https://s3.amazonaws.com/windows-ami-software/jdk-8u151-windows-x64.exe"
                            },
                            "c:\\cfn\\modules\\apache-tomcat-8.5.23.exe": {
                                "source": "https://s3.amazonaws.com/windows-ami-software/apache-tomcat-8.5.23.exe"
                            },
                            "c:\\cfn\\scripts\\Install-Java-JDK.ps1": {
                                "content": {
                                    "Fn::Join": [
                                        "",
                                        [
                                            "Set-Location C:\\cfn\\modules;",
                                            ".\\jdk-8u151-windows-x64.exe /s ADDLOCAL=\"ToolsFeature,SourceFeature,PublicjreFeature\"",
                                            "\n"
                                        ]
                                    ]
                                }
                            },
                            "c:\\cfn\\scripts\\Install-Tomcat8.ps1": {
                                "content": {
                                    "Fn::Join": [
                                        "",
                                        [
                                            "Set-Location C:\\cfn\\modules;",
                                            ".\\apache-tomcat-8.5.23.exe /S",
                                            "\n"
                                        ]
                                    ]
                                }
                            },
                            "c:\\cfn\\scripts\\Set-Java-Tomcat8-Paths-Homes.ps1": {
                                "content": {
                                    "Fn::Join": [
                                        "",
                                        [
                                            "$oldPath=(Get-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\\System\\CurrentControlSet\\Control\\Session Manager\\Environment' -Name PATH).Path;",
                                            "$addedFolder = 'C:\\Program Files\\Java\\jdk1.8.0_151\\bin; C:\\Program Files\\Apache Software Foundation\\Tomcat 8.5\\bin';",
                                            "$newPath = $oldPath +';'+$addedFolder;",
                                            "Set-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\\System\\CurrentControlSet\\Control\\Session Manager\\Environment' -Name PATH -Value $newPath ;",
                                            "[Environment]::SetEnvironmentVariable('CATALINA_HOME', 'C:\\Program Files\\Apache Software Foundation\\Tomcat 8.5\\', 'Machine');",
                                            "[Environment]::SetEnvironmentVariable('JAVA_HOME', 'C:\\Program Files\\Java\\jdk1.8.0_151\\', 'Machine');",
                                            "Restart-Computer -Force;",
                                            "\n"
                                        ]
                                    ]
                                }
                            },
                            "c:\\cfn\\scripts\\Install-Tomcat8-Service.ps1": {
                                "content": {
                                    "Fn::Join": [
                                        "",
                                        [
                                            "Set-Location 'C:\\Program Files\\Apache Software Foundation\\Tomcat 8.5\\bin';",
                                            ".\\service.bat install;",
                                            "Set-Service Tomcat8 -StartupType Automatic;",
                                            "Start-Service Tomcat8;",
                                            "\n"
                                        ]
                                    ]
                                }
                            }
                        },
                        "commands": {
                            "a-Install-Java-JDK": {
                                "command": "powershell.exe -ExecutionPolicy RemoteSigned -Command c:\\cfn\\scripts\\Install-Java-JDK.ps1",
                                "waitAfterCompletion": "30"
                            },
                            "b-Install-Tomcat8": {
                                "command": "powershell.exe -ExecutionPolicy RemoteSigned -Command c:\\cfn\\scripts\\Install-Tomcat8.ps1",
                                "waitAfterCompletion": "30"
                            },
                            "c-Set-Java-Tomcat8-Paths-Homes": {
                                "command": "powershell.exe -ExecutionPolicy RemoteSigned -Command c:\\cfn\\scripts\\Set-Java-Tomcat8-Paths-Homes.ps1",
                                "waitAfterCompletion": "forever"
                            },
                            "d-Install-Tomcat8-Service": {
                                "command": "powershell.exe -ExecutionPolicy RemoteSigned -Command c:\\cfn\\scripts\\Install-Tomcat8-Service.ps1",
                                "waitAfterCompletion": "30"
                            }
                        }
                    }
                }
            },
            "AWS::CloudFormation::Designer": {
                "id": "94153bdc-589b-4aa8-b859-5e84a1051a50"
            }
        }
    }
}
</code>```

}

答:
There are 2 things you need to check:

Check if those scripts are getting created on location C:\cfn\scripts
--IF not then check where is the issue

If these scripts are created there, then call separately the step "commands" in configSets (line no. 33-34). I suspect that is the problem where the actual scripts are not getting called.

Body:
Below is my CloudFormation template for creating a windows EC2 instance with Java and Tomcat installed on it. However, the nothing from the MetaData is being executed. I login to the created EC2 instance, and none of the specified folders in the metadata can be found. What is my CloudFormation script missing?

Thank you

{
"AWSTemplateFormatVersion": "2010-09-09",
"Description": "Script to create Windows AMI",
"Metadata": {
    "AWS::CloudFormation::Designer": {
        "94153bdc-589b-4aa8-b859-5e84a1051a50": {
            "size": {
                "width": 60,
                "height": 60
            },
            "position": {
                "x": 280,
                "y": 110
            },
            "z": 1,
            "embeds": []
        }
    }
},
"Parameters": {},
"Rules": {},
"Mappings": {},
"Resources": {
    "JavaTomcatEC2Instance": {
        "Type": "AWS::EC2::Instance",
        "Properties": {
            "ImageId": "ami-06b19063",
            "InstanceType": "t2.micro",
            "KeyName": "WindowsTest"
        },
        "Metadata": {
            "AWS::CloudFormation::Init": {
                "configSets": {
                    "config": [
                        "setup"
                    ]
                },
                "setup": {
                    "Install-Java-Tomcat-set-env-variables-paths": {
                        "files": {
                            "c:\\cfn\\modules\\jdk-8u151-windows-x64.exe": {
                                "source": "https://s3.amazonaws.com/windows-ami-software/jdk-8u151-windows-x64.exe"
                            },
                            "c:\\cfn\\modules\\apache-tomcat-8.5.23.exe": {
                                "source": "https://s3.amazonaws.com/windows-ami-software/apache-tomcat-8.5.23.exe"
                            },
                            "c:\\cfn\\scripts\\Install-Java-JDK.ps1": {
                                "content": {
                                    "Fn::Join": [
                                        "",
                                        [
                                            "Set-Location C:\\cfn\\modules;",
                                            ".\\jdk-8u151-windows-x64.exe /s ADDLOCAL=\"ToolsFeature,SourceFeature,PublicjreFeature\"",
                                            "\n"
                                        ]
                                    ]
                                }
                            },
                            "c:\\cfn\\scripts\\Install-Tomcat8.ps1": {
                                "content": {
                                    "Fn::Join": [
                                        "",
                                        [
                                            "Set-Location C:\\cfn\\modules;",
                                            ".\\apache-tomcat-8.5.23.exe /S",
                                            "\n"
                                        ]
                                    ]
                                }
                            },
                            "c:\\cfn\\scripts\\Set-Java-Tomcat8-Paths-Homes.ps1": {
                                "content": {
                                    "Fn::Join": [
                                        "",
                                        [
                                            "$oldPath=(Get-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\\System\\CurrentControlSet\\Control\\Session Manager\\Environment' -Name PATH).Path;",
                                            "$addedFolder = 'C:\\Program Files\\Java\\jdk1.8.0_151\\bin; C:\\Program Files\\Apache Software Foundation\\Tomcat 8.5\\bin';",
                                            "$newPath = $oldPath +';'+$addedFolder;",
                                            "Set-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\\System\\CurrentControlSet\\Control\\Session Manager\\Environment' -Name PATH -Value $newPath ;",
                                            "[Environment]::SetEnvironmentVariable('CATALINA_HOME', 'C:\\Program Files\\Apache Software Foundation\\Tomcat 8.5\\', 'Machine');",
                                            "[Environment]::SetEnvironmentVariable('JAVA_HOME', 'C:\\Program Files\\Java\\jdk1.8.0_151\\', 'Machine');",
                                            "Restart-Computer -Force;",
                                            "\n"
                                        ]
                                    ]
                                }
                            },
                            "c:\\cfn\\scripts\\Install-Tomcat8-Service.ps1": {
                                "content": {
                                    "Fn::Join": [
                                        "",
                                        [
                                            "Set-Location 'C:\\Program Files\\Apache Software Foundation\\Tomcat 8.5\\bin';",
                                            ".\\service.bat install;",
                                            "Set-Service Tomcat8 -StartupType Automatic;",
                                            "Start-Service Tomcat8;",
                                            "\n"
                                        ]
                                    ]
                                }
                            }
                        },
                        "commands": {
                            "a-Install-Java-JDK": {
                                "command": "powershell.exe -ExecutionPolicy RemoteSigned -Command c:\\cfn\\scripts\\Install-Java-JDK.ps1",
                                "waitAfterCompletion": "30"
                            },
                            "b-Install-Tomcat8": {
                                "command": "powershell.exe -ExecutionPolicy RemoteSigned -Command c:\\cfn\\scripts\\Install-Tomcat8.ps1",
                                "waitAfterCompletion": "30"
                            },
                            "c-Set-Java-Tomcat8-Paths-Homes": {
                                "command": "powershell.exe -ExecutionPolicy RemoteSigned -Command c:\\cfn\\scripts\\Set-Java-Tomcat8-Paths-Homes.ps1",
                                "waitAfterCompletion": "forever"
                            },
                            "d-Install-Tomcat8-Service": {
                                "command": "powershell.exe -ExecutionPolicy RemoteSigned -Command c:\\cfn\\scripts\\Install-Tomcat8-Service.ps1",
                                "waitAfterCompletion": "30"
                            }
                        }
                    }
                }
            },
            "AWS::CloudFormation::Designer": {
                "id": "94153bdc-589b-4aa8-b859-5e84a1051a50"
            }
        }
    }
}

}


问:
No matching function on heap
I've created a mix method which is taking two lists by reference. Than I've created mixed list(3) to which I'm assigning elements form list 1 and 2, than I return a list 3.

When I try to implement it it works in stack, but not heap.
What can be a possible problem?

(sth3 = sth3->mix(sth1,sth2);) - I have no matching function problem.

Not working:

```<code>    Sequence<int,string> *sth1 = new Sequence<int,string>();
    sth1->AddNode(1,"n1");
    sth1->AddNode(2,"n2");

    Sequence<int,string> *sth2 = new Sequence<int,string>();
    sth2->AddNode(10,"n1");

    Sequence<int,string> *sth3 = new Sequence<int,string>();
    sth3 = sth3->mix(sth1,sth2);
    sth3->Print();
</code>```

Working one:

```<code>    Sequence<int,string> st1;
    st1.AddNode(1,"n1");

    Sequence<int,string> st2;
    st2.AddNode(10,"n1");

    Sequence<int,string> st3;
    st3 = st3.mix(st1,st2);
    st3.Print();
</code>```

Simplified function mix(..)

```<code>template<typename key,typename info>
Sequence<key, info> Sequence<key, info>::mix(const Sequence<key, info> &s1, const Sequence<key,info> &s2)
{
            Sequence<key,info> s;
            Node<key, info> *curr1 = s1.head;
            Node<key, info> *curr2 = s2.head;

            while (s.count < 10)
            {
                s.AddNode(curr1->GetId(), curr1->GetData())
                curr1 = curr1->GetNext();
                s.AddNode(curr2->GetId(), curr2->GetData())
                curr2 = curr2->GetNext();

                if (curr1 == NULL && curr2 == NULL)
                    break;

            }

    return s;
}
</code>```

答: Change sth3 = sth3->mix(sth1,sth2) to *sth3 = sth3->mix(*sth1,*sth2).

Title: No matching function on heap

Body:
I've created a mix method which is taking two lists by reference. Than I've created mixed list(3) to which I'm assigning elements form list 1 and 2, than I return a list 3.

When I try to implement it it works in stack, but not heap.
What can be a possible problem?

(sth3 = sth3->mix(sth1,sth2);) - I have no matching function problem.

Not working:

    Sequence<int,string> *sth1 = new Sequence<int,string>();
    sth1->AddNode(1,"n1");
    sth1->AddNode(2,"n2");

    Sequence<int,string> *sth2 = new Sequence<int,string>();
    sth2->AddNode(10,"n1");

    Sequence<int,string> *sth3 = new Sequence<int,string>();
    sth3 = sth3->mix(sth1,sth2);
    sth3->Print();

Working one:

    Sequence<int,string> st1;
    st1.AddNode(1,"n1");

    Sequence<int,string> st2;
    st2.AddNode(10,"n1");

    Sequence<int,string> st3;
    st3 = st3.mix(st1,st2);
    st3.Print();

Simplified function mix(..)

template<typename key,typename info>
Sequence<key, info> Sequence<key, info>::mix(const Sequence<key, info> &s1, const Sequence<key,info> &s2)
{
            Sequence<key,info> s;
            Node<key, info> *curr1 = s1.head;
            Node<key, info> *curr2 = s2.head;

            while (s.count < 10)
            {
                s.AddNode(curr1->GetId(), curr1->GetData())
                curr1 = curr1->GetNext();
                s.AddNode(curr2->GetId(), curr2->GetData())
                curr2 = curr2->GetNext();

                if (curr1 == NULL && curr2 == NULL)
                    break;

            }

    return s;
}


问:
Find the path that is used to search for executable programs?
So for one of my HW assignment, I must "display the path used to search for executable programs" in both Windows and in Ubuntu using a .bat and .sh file. At the moment I'm a bit confused about what exactly I must locate and print out.

Is this referring to one of the locations in the Windows %PATH% environment variable? If so, what would be the equivalent in Linux? Once I know what I am looking for printing it should be pretty simple.

Any advice would be very much appreciated!

答:
You are correct about windows and %PATH%.

For any Linux/Unix OS the equivalent is $PATH.

See this wikipedia article for more details


问:
KeyError: kafka.producer.record_accumulator.RecordBatch
Using kafka-python api to send a bunch of messages to a topic. A portion of messages get successfully sent to the topic but not all of them are sent before the program terminates with the following error message:

```<code>KeyError: <kafka.producer.record_accumulator.RecordBatch object at 0x143d290>
Batch is already closed -- ignoring batch.done()
Error processing errback
Traceback (most recent call last):
  File "/usr/lib/python2.6/site-packages/kafka/future.py", line 79, in _call_backs
    f(value)
  File "/usr/lib/python2.6/site-packages/kafka/producer/sender.py", line 185, in _failed_produce
    self._complete_batch(batch, error, -1, None)
  File "/usr/lib/python2.6/site-packages/kafka/producer/sender.py", line 243, in _complete_batch
    self._accumulator.deallocate(batch)
  File "/usr/lib/python2.6/site-packages/kafka/producer/record_accumulator.py", line 507, in deallocate
    self._incomplete.remove(batch)
  File "/usr/lib/python2.6/site-packages/kafka/producer/record_accumulator.py", line 587, in remove
    return self._incomplete.remove(batch)
</code>```

Every run a different number of messages are actually received in my topic. The problem appears to be that kafka producer.send calls do not complete sending before the program reaches its end.

According to kafka documentations producer.send is an async method which is probably the root cause - not all async threads complete sending before the process is killed:

The send() method is asynchronous. When called it adds the record to a
  buffer of pending record sends and immediately returns. This allows
  the producer to batch together individual records for efficiency.

There are a number of naive solutions for this (such as setting the batch.size to a low number) that could cause a performance bottleneck.

How would you address this issue without compromising the performance too much?

答: Just call producer.flush() before exit.

Body:
Using kafka-python api to send a bunch of messages to a topic. A portion of messages get successfully sent to the topic but not all of them are sent before the program terminates with the following error message:

KeyError: <kafka.producer.record_accumulator.RecordBatch object at 0x143d290>
Batch is already closed -- ignoring batch.done()
Error processing errback
Traceback (most recent call last):
  File "/usr/lib/python2.6/site-packages/kafka/future.py", line 79, in _call_backs
    f(value)
  File "/usr/lib/python2.6/site-packages/kafka/producer/sender.py", line 185, in _failed_produce
    self._complete_batch(batch, error, -1, None)
  File "/usr/lib/python2.6/site-packages/kafka/producer/sender.py", line 243, in _complete_batch
    self._accumulator.deallocate(batch)
  File "/usr/lib/python2.6/site-packages/kafka/producer/record_accumulator.py", line 507, in deallocate
    self._incomplete.remove(batch)
  File "/usr/lib/python2.6/site-packages/kafka/producer/record_accumulator.py", line 587, in remove
    return self._incomplete.remove(batch)

Every run a different number of messages are actually received in my topic. The problem appears to be that kafka producer.send calls do not complete sending before the program reaches its end.

According to kafka documentations producer.send is an async method which is probably the root cause - not all async threads complete sending before the process is killed:

The send() method is asynchronous. When called it adds the record to a
  buffer of pending record sends and immediately returns. This allows
  the producer to batch together individual records for efficiency.

There are a number of naive solutions for this (such as setting the batch.size to a low number) that could cause a performance bottleneck.

How would you address this issue without compromising the performance too much?

Body: Just call producer.flush() before exit.


问:
Fastest way to generate combinations of rows
We have a table of plans and each plan has many services. We would like a fast way of finding the combinations of plans that do not contain duplicate services but as a combinations contain certain services.

e.g. table of plans

```<code>id | service_1 | service_2 | ...
---------------------------------
1  |   true    |  true     | ...
2  |   true    |  false    | ...
3  |   false   |  true     | ...
</code>```

e.g. valid combinations containing service_1 and service_2

UPDATE

If there were 2 services and I required both of them we would combine up to 2 rows (or plans) as they could contain at minimum 1 service in each.

```<code>id | service_1 | service_2 | id | service_1 | service_2 |
---------------------------------------------------------
1  |   true    |  true     |NULL|    NULL   |    NULL   |
2  |   true    |  false    | 3  |    false  |    true   |
</code>```

UPDATE

It currently works by self left joining itself with aggressive pruning or rows. The query is dynamically generated based on the number of services. It creates the permutations of valid join conditions making it not practical to post.

Currently the cost is in the order of number of plans ^ number of services.

I'm mostly interested in other ways of solving this not necessarily improvements to the current way.

答:
This seems to work ok

Setup data

```<code>DROP TABLE IF EXISTS plan;
CREATE TABLE plan (id int, service1 bool, service2 bool, service3 bool);
INSERT INTO `plan` (`id`, `service1`, `service2`, `service3`) VALUES (1, 1, 0, 0);
INSERT INTO `plan` (`id`, `service1`, `service2`, `service3`) VALUES (2, 0, 1, 0);
INSERT INTO `plan` (`id`, `service1`, `service2`, `service3`) VALUES (3, 1, 1, 1);
INSERT INTO `plan` (`id`, `service1`, `service2`, `service3`) VALUES (4, 1, 0, 1);
INSERT INTO `plan` (`id`, `service1`, `service2`, `service3`) VALUES (5, 0, 0, 1);
</code>```

The query

```<code>select *
from plan A
left join (
    select id, service1, service2, service3 from plan
    union all
    select null, null, null, null) B on B.id > A.id or B.id is null
left join (
    select id, service1, service2, service3 from plan
    union all
    select null, null, null, null) C on C.id > B.id or C.id is null
WHERE (A.service1 + A.service2 + A.service3)
  AND (A.service1 + ifnull(B.service1,0) + ifnull(C.service1,0)) = 1
  AND (A.service2 + ifnull(B.service2,0) + ifnull(C.service2,0)) = 1
  AND (A.service3 + ifnull(B.service3,0) + ifnull(C.service3,0)) = 1
</code>```

Result

```<code>id | service1 | service2 | service3 | id | service1 | service2 | service3 | id | service1 | service2 | service3
1 | 1 | 0 | 0 | 2 | 0 | 1 | 0 | 5 | 0 | 0 | 1
1 | 1 | 0 | 0 | 5 | 0 | 0 | 1 | 2 | 0 | 1 | 0
2 | 0 | 1 | 0 | 4 | 1 | 0 | 1 | NULL | NULL | NULL | NULL
2 | 0 | 1 | 0 | NULL | NULL | NULL | NULL | 4 | 1 | 0 | 1
3 | 1 | 1 | 1 | NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL
</code>```

ContentLicense: CC BY-SA 2.5

Body:
We have a table of plans and each plan has many services. We would like a fast way of finding the combinations of plans that do not contain duplicate services but as a combinations contain certain services.

e.g. table of plans

id | service_1 | service_2 | ...
---------------------------------
1  |   true    |  true     | ...
2  |   true    |  false    | ...
3  |   false   |  true     | ...

e.g. valid combinations containing service_1 and service_2

UPDATE

If there were 2 services and I required both of them we would combine up to 2 rows (or plans) as they could contain at minimum 1 service in each.

id | service_1 | service_2 | id | service_1 | service_2 |
---------------------------------------------------------
1  |   true    |  true     |NULL|    NULL   |    NULL   |
2  |   true    |  false    | 3  |    false  |    true   |

UPDATE

It currently works by self left joining itself with aggressive pruning or rows. The query is dynamically generated based on the number of services. It creates the permutations of valid join conditions making it not practical to post.

Currently the cost is in the order of number of plans ^ number of services.

I'm mostly interested in other ways of solving this not necessarily improvements to the current way.

Body:
This seems to work ok

Setup data

DROP TABLE IF EXISTS plan;
CREATE TABLE plan (id int, service1 bool, service2 bool, service3 bool);
INSERT INTO `plan` (`id`, `service1`, `service2`, `service3`) VALUES (1, 1, 0, 0);
INSERT INTO `plan` (`id`, `service1`, `service2`, `service3`) VALUES (2, 0, 1, 0);
INSERT INTO `plan` (`id`, `service1`, `service2`, `service3`) VALUES (3, 1, 1, 1);
INSERT INTO `plan` (`id`, `service1`, `service2`, `service3`) VALUES (4, 1, 0, 1);
INSERT INTO `plan` (`id`, `service1`, `service2`, `service3`) VALUES (5, 0, 0, 1);

The query

select *
from plan A
left join (
    select id, service1, service2, service3 from plan
    union all
    select null, null, null, null) B on B.id > A.id or B.id is null
left join (
    select id, service1, service2, service3 from plan
    union all
    select null, null, null, null) C on C.id > B.id or C.id is null
WHERE (A.service1 + A.service2 + A.service3)
  AND (A.service1 + ifnull(B.service1,0) + ifnull(C.service1,0)) = 1
  AND (A.service2 + ifnull(B.service2,0) + ifnull(C.service2,0)) = 1
  AND (A.service3 + ifnull(B.service3,0) + ifnull(C.service3,0)) = 1

Result

id | service1 | service2 | service3 | id | service1 | service2 | service3 | id | service1 | service2 | service3
1 | 1 | 0 | 0 | 2 | 0 | 1 | 0 | 5 | 0 | 0 | 1
1 | 1 | 0 | 0 | 5 | 0 | 0 | 1 | 2 | 0 | 1 | 0
2 | 0 | 1 | 0 | 4 | 1 | 0 | 1 | NULL | NULL | NULL | NULL
2 | 0 | 1 | 0 | NULL | NULL | NULL | NULL | 4 | 1 | 0 | 1
3 | 1 | 1 | 1 | NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL


问:
JPA flush vs commit
in JPA, if we call EntityTransaction.commit(), does it automatically call EntityManager.flush()? or should we call them both? what is the difference? because i have problem with JPA, when i insert an entity to database, i call persist(). in the database, the data has been inserted (can be fetched), but that data doesn't show up in my app (i fetch it using findAll()). and on another entity, it showed up. is there something i don't know? i'm using standard Spring CRUD, JPA resource_local, and postgresql. sorry for my english, thanks in advance</p>

答:
If you have a @Version annotated column in your entity and call entityManager.flush(), then you will either (immediately!) get an OptimisticLockException, or the database will lock this row (or table). In the later case you can still call setRollbackOnly(), and the lock will later be released without a DB change.

Or from a different perspective, with flush() you can create a (pessimistic) lock on that database row. The others will still see the old entry, but if they try to update they will be blocked, until the lock is released.

All this is also true for CMT (container managed transactions). Instead of waiting for the moment, where the service method is finished and the CMT commit is performed, you can call flush() (even several times) in your service method and handle the OptimisticLockException(s) immediately.

Title: JPA flush vs commit


问:
Rename file in Node.js without using fs
Is there any way to rename file in Node js without using fs package. Since it says Security holding package in NPM Respository
 https://www.npmjs.com/package/fs.

答:
If you really do not want to use fs, you could rename your file with child_process exec:

```<code>const { exec } = require('child_process');
exec('mv old_file_name new_file_name');
</code>```

Title: Rename file in Node.js without using fs

Body:
If you really do not want to use fs, you could rename your file with child_process exec:

const { exec } = require('child_process');
exec('mv old_file_name new_file_name');


问:
Electron store reference to new BrowserWindow
I have a github auth link in my app which triggers the 'new-window' listener'

```<code>mainWindow.webContents.on('new-window', (event, url, frameName, disposition, options, additionalFeatures) => {
// how do i store a reference to the newly created window here
})
</code>```

How do i store a refernce to this new window so i can later perform actions on the instance?

答:
You could instead of letting electron make the window make the window yourself like what it says further down in the documentation.

Then you could store a reference to the window variable and do things with it like this:

```<code>var newWindow;

myBrowserWindow.webContents.on('new-window', (event, url) => {
  event.preventDefault()
  const win = new BrowserWindow({show: false})
  win.once('ready-to-show', () => win.show())
  win.loadURL(url)
  event.newGuest = win
  newWindow      = win;
})

// Do something with the window.
newWindow.hide();
</code>```

Documentation

Body:
I have a github auth link in my app which triggers the 'new-window' listener'

mainWindow.webContents.on('new-window', (event, url, frameName, disposition, options, additionalFeatures) => {
// how do i store a reference to the newly created window here
})

How do i store a refernce to this new window so i can later perform actions on the instance?

Body:
You could instead of letting electron make the window make the window yourself like what it says further down in the documentation.

Then you could store a reference to the window variable and do things with it like this:

var newWindow;

myBrowserWindow.webContents.on('new-window', (event, url) => {
  event.preventDefault()
  const win = new BrowserWindow({show: false})
  win.once('ready-to-show', () => win.show())
  win.loadURL(url)
  event.newGuest = win
  newWindow      = win;
})

// Do something with the window.
newWindow.hide();

Documentation


问:
Creating a file with Acumatica Framework
How do you generate a file on Acumatica ? I didnt find the process in the trainings nor the framework

I need to add a button like the "export to excel" but with xml for example but a simple button on a screen generating my xml would be enough

Thanks

答:
Follow standard procedure to add the button to your grid:

Add button to grid in Acumatica

Adding button on newly created tab

In your button event handler:

```<code>[PXButton]
[PXUIField(DisplayName = "Export XML")]
public virtual IEnumerable exportXML(PXAdapter adapter)
{
   // Use your favorite library to create XML file
   XmlDocument xmlDoc = new XmlDocument();
   xmlDoc.AppendChild(xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null));

   // Create root node of XML file
   XmlNode rootNode = xmlDoc.CreateElement("Grid Data");

   // Iterate rows of the DataView
   foreach (DAC dacRecord in GridDataView.Select())
   {
      // Create an XML Element to represent the DAC row
      XMLNode xmlDACRecord = xmlDoc.CreateElement("DAC Record");

      // Add desired DAC fields as child XML Elements of the DAC row XML element
      XMLNode xmlDACField1 = xmlDoc.CreateElement("DAC Field 1");
      xmlDACField1.AppendChild(xmlDoc.CreateTextNode(dacRecord.Field1.ToString()));
      xmlDACRecord.AppendChild(xmlDACField1);

      // Adding XML DAC Record to XML root node
      rootNode.AppendChild(xmlDACRecord);
   }

   // Adding XML root node to XML document
   xmlDoc.AppendChild(rootNode);

   // Redirect browser to XML file created in memory on server
   throw new PXRedirectToFileException(new PX.SM.FileInfo(Guid.NewGuid(),
                                                          "filename.xml",
                                                          null,
                                                          System.Text.Encoding.UTF8.GetBytes(xmlDoc.OuterXml)),
                                       true);
   return adapter.Get();
}
</code>```

Body:
Follow standard procedure to add the button to your grid:

Add button to grid in Acumatica

Adding button on newly created tab

In your button event handler:

[PXButton]
[PXUIField(DisplayName = "Export XML")]
public virtual IEnumerable exportXML(PXAdapter adapter)
{
   // Use your favorite library to create XML file
   XmlDocument xmlDoc = new XmlDocument();
   xmlDoc.AppendChild(xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null));

   // Create root node of XML file
   XmlNode rootNode = xmlDoc.CreateElement("Grid Data");

   // Iterate rows of the DataView
   foreach (DAC dacRecord in GridDataView.Select())
   {
      // Create an XML Element to represent the DAC row
      XMLNode xmlDACRecord = xmlDoc.CreateElement("DAC Record");

      // Add desired DAC fields as child XML Elements of the DAC row XML element
      XMLNode xmlDACField1 = xmlDoc.CreateElement("DAC Field 1");
      xmlDACField1.AppendChild(xmlDoc.CreateTextNode(dacRecord.Field1.ToString()));
      xmlDACRecord.AppendChild(xmlDACField1);

      // Adding XML DAC Record to XML root node
      rootNode.AppendChild(xmlDACRecord);
   }

   // Adding XML root node to XML document
   xmlDoc.AppendChild(rootNode);

   // Redirect browser to XML file created in memory on server
   throw new PXRedirectToFileException(new PX.SM.FileInfo(Guid.NewGuid(),
                                                          "filename.xml",
                                                          null,
                                                          System.Text.Encoding.UTF8.GetBytes(xmlDoc.OuterXml)),
                                       true);
   return adapter.Get();
}


问:
Button with mysql query in action
I created a dropdown list with 6 options.

After select an option and clicking the submit button, the selected value should be inserted into the mysql database. This is code:

```<code><form name="name" method="get" action="<?php echo $_SERVER['PHP_SELF']; ?>">

<select id="broj" name="name">
  <option value="0">--Select--</option>
  <option value="2">Option 1</option>
  <option value="3">Option 2</option>
  <option value="4">Option 3</option>
  <option value="5">Option 4</option>
  <option value="6">Option 5</option>
  <option value="7">Option 6</option>
</select>
<input type="submit" name="submit" value="Submit" />
</form>

<?php
if($_GET){
   $result= $_GET['name'];
  }
?>
//
After this follows the code that inserts the $result into the mysql database
</code>```

I have two problems with this code:

As soon as the page is opened (before clicking the button) , the value 0 is inserted into the database (value of "Select" option)

After refreshing page, the selected value is re-insert into the database

How to make the selected option inserted into the database only when the submit button is clicked

答:
I think you should change your form method to POST instead of GET. And check for post before insert into database

```<code>    if ($_SERVER['REQUEST_METHOD'] == 'POST')
    {
        // Code insert into database here
    }
</code>```

In your code I see

```<code>    action="<?php echo $_SERVER['PHP_SELF']; ?>"
</code>```

$_SERVER['PHP_SELF'] with form method GET will contain your submit parameter and that may cause some strange problems. I think there may be no problem if you let action="", your form still submit data to current page

Title: Button with mysql query in action

Body:
I created a dropdown list with 6 options.

After select an option and clicking the submit button, the selected value should be inserted into the mysql database. This is code:

<form name="name" method="get" action="<?php echo $_SERVER['PHP_SELF']; ?>">

<select id="broj" name="name">
  <option value="0">--Select--</option>
  <option value="2">Option 1</option>
  <option value="3">Option 2</option>
  <option value="4">Option 3</option>
  <option value="5">Option 4</option>
  <option value="6">Option 5</option>
  <option value="7">Option 6</option>
</select>
<input type="submit" name="submit" value="Submit" />
</form>

<?php
if($_GET){
   $result= $_GET['name'];
  }
?>
//
After this follows the code that inserts the $result into the mysql database

I have two problems with this code:

As soon as the page is opened (before clicking the button) , the value 0 is inserted into the database (value of "Select" option)

After refreshing page, the selected value is re-insert into the database

How to make the selected option inserted into the database only when the submit button is clicked

Body:
I think you should change your form method to POST instead of GET. And check for post before insert into database

    if ($_SERVER['REQUEST_METHOD'] == 'POST')
    {
        // Code insert into database here
    }

In your code I see

    action="<?php echo $_SERVER['PHP_SELF']; ?>"

$_SERVER['PHP_SELF'] with form method GET will contain your submit parameter and that may cause some strange problems. I think there may be no problem if you let action="", your form still submit data to current page


问:
Is it possible to use JFS on CentOS 7?
I have some TS-7800 boards that run BusyBox/Debian from SD cards.  Two of the partitions on the SD cards use JFS.  I create and edit the SD cards on a CentOS computer.

A while back I upgraded to CentOS 7.  Apparently this caused me to lose all JFS support.

I tried to enable it using the same procedure I used to enable it on CentOS 6:

https://wiki.centos.org/AdditionalResources/Repositories/CentOSPlus

Even though the procedure claims to work for CentOS 7, I cannot find a jfsutils package.  I have spent many hours on Google and have searched all of the CentOS repos I can find but it appears that there is no jfsutils package for CentOS 7.

Has anyone else had this issue?  Am I out of luck?

答: Yes.  You have to use the CentOSPlus kernel though.</p>

Title: Is it possible to use JFS on CentOS 7?


问:
Can you avoid unboxing in a memoizing generic method?
I have a generic method I use to memoize conversions of string values in the db to an actual converted value.

```<code>public MySpecialValue {
    object val;
    bool valSet = false;

    T GetValue<T> () {
         if (!valSet)
         {
                val = (T)Convert.ChangeType(DatabaseValue, typeof(T));
                valSet = true;
         }
         return (T)val;
     }

     public string DatabaseValue { get; set; }
}
</code>```

The trouble is that during initialization I do not know what type the data in the database is, its only on first call that I can make this decision.

Is there any way to structure it in such a way that it is not forced to unbox value types that are cached? (without changing the signature of the containing class)

答:
This makes stuff ever so slightly faster for value types (no unboxing) ... and ever so slightly slower for ref types one extra call ... it is however a bit strange. </p>

```<code> class MyClass {
    class Container<T>
    {
        public T Value { get; set; }
    }

    bool valSet;
    object val;

    public T GetValue<T> () {
        if (!valSet)
        {
            val = new Container<T>{Value =  (T)Convert.ChangeType(DatabaseValue, typeof(T))};
            valSet = true;
        }
        return ((Container<T>)val).Value;
    }

    public string DatabaseValue { get; set; }
 }
</code>```

Body:
I have a generic method I use to memoize conversions of string values in the db to an actual converted value.

public MySpecialValue {
    object val;
    bool valSet = false;

    T GetValue<T> () {
         if (!valSet)
         {
                val = (T)Convert.ChangeType(DatabaseValue, typeof(T));
                valSet = true;
         }
         return (T)val;
     }

     public string DatabaseValue { get; set; }
}

The trouble is that during initialization I do not know what type the data in the database is, its only on first call that I can make this decision.

Is there any way to structure it in such a way that it is not forced to unbox value types that are cached? (without changing the signature of the containing class)

Body:
This makes stuff ever so slightly faster for value types (no unboxing) ... and ever so slightly slower for ref types one extra call ... it is however a bit strange.

 class MyClass {
    class Container<T>
    {
        public T Value { get; set; }
    }

    bool valSet;
    object val;

    public T GetValue<T> () {
        if (!valSet)
        {
            val = new Container<T>{Value =  (T)Convert.ChangeType(DatabaseValue, typeof(T))};
            valSet = true;
        }
        return ((Container<T>)val).Value;
    }

    public string DatabaseValue { get; set; }
 }


问:
Sidebar hide and show with Bootstrap and Jquery?
Guys I want to create a sidebar hiding and showing using bootstrap, but my code isn't working..

Please help me...

My code HTML is:

```<code><nav role="nav" class="navbar">
    <a href="" class="menu">button</a>
</nav>

<nav role="nav" class="sidebar">
    sidebar menu
</nav>

<main role="main" class="main-page">
    main content
</main>
</code>```

This is my CSS code:

```<code>.menu {
    display: block !important;
}

.sidebar {
    color: #fff;
    width: 240px;
    height: 100%;
    position: fixed;
    background: #2a3542;
}

.main-page {
    color: #000;
    margin-left: 240px;
    position :relative;
}
</code>```

And this is my jquery code:

```<code><script>
    $(function () {
        $('.menu').on('click', function () {
            if ($('.sidebar').is(':visible')) {
                $('.sidebar').animate({'width': '0px'}, 'slow', function () {
                    $('.sidebar').hide();
                });
                $('.main-page').animate({'padding-left': '0px'}, 'slow');
            } else {
                $('.sidebar').show();
                $('.sidebar').animate({'width': '240px'}, 'slow');
                $('.main-page').animate({'padding-left': '240px'}, 'slow');
            }
        });
    });
</script>
</code>```

I'm using bootstrp CDN: jquery-3.2.1.slim.min.js / popper.min.js / bootstrap.min.js

答:
You are using slim version of jQuery library which does not contain DOM animation capabilities. That is why your code is not working...

See more on this link below:
https://stackoverflow.com/a/35424465/704661

EDIT:

You had several bugs in your code:

First is that your anchor has empty href attribute which causes page to reload on every click.

Secondly you had margin and padding on main content which was causing multiple gap between sidebar and content.

HTML

```<code><nav role="nav" class="navbar">
    <a href="#" class="menu">button</a>
</nav>

<nav role="nav" class="sidebar">
    sidebar menu
</nav>

<main role="main" class="main-page">
    main content
</main>
</code>```

CSS

```<code>.menu {
                display: block !important;
            }

            .sidebar {
                color: #fff;
                width: 240px;
                height: 100%;
                position: fixed;
                background: #2a3542;
            }

            .main-page {
                color: #000;
                padding-left: 240px;
                position :relative;
            }
</code>```

Javascript

```<code>$(function () {
        $('.menu').on('click', function () {
        if ($('.sidebar').is(':visible')) {
            $('.sidebar').animate({'width': '0px'}, 'slow', function () {
                $('.sidebar').hide();
            });
            $('.main-page').animate({'padding-left': '0px'}, 'slow');
        } else {
            $('.sidebar').show();
            $('.sidebar').animate({'width': '240px'}, 'slow');
            $('.main-page').animate({'padding-left': '240px'}, 'slow');
        }
        });
    });
</code>```

here is working fiddle example

https://codepen.io/mnikolaus/pen/mqByqK

Body:
Guys I want to create a sidebar hiding and showing using bootstrap, but my code isn't working..

Please help me...

My code HTML is:

    button

    sidebar menu

    main content

This is my CSS code:

.menu {
    display: block !important;
}

.sidebar {
    color: #fff;
    width: 240px;
    height: 100%;
    position: fixed;
    background: #2a3542;
}

.main-page {
    color: #000;
    margin-left: 240px;
    position :relative;
}

And this is my jquery code:

I'm using bootstrp CDN: jquery-3.2.1.slim.min.js / popper.min.js / bootstrap.min.js

Body:
You are using slim version of jQuery library which does not contain DOM animation capabilities. That is why your code is not working...

See more on this link below:
https://stackoverflow.com/a/35424465/704661

EDIT:

You had several bugs in your code:

First is that your anchor has empty href attribute which causes page to reload on every click.

Secondly you had margin and padding on main content which was causing multiple gap between sidebar and content.

HTML

<nav role="nav" class="navbar">
    <a href="#" class="menu">button</a>
</nav>

<nav role="nav" class="sidebar">
    sidebar menu
</nav>

<main role="main" class="main-page">
    main content
</main>

CSS

.menu {
                display: block !important;
            }

            .sidebar {
                color: #fff;
                width: 240px;
                height: 100%;
                position: fixed;
                background: #2a3542;
            }

            .main-page {
                color: #000;
                padding-left: 240px;
                position :relative;
            }

Javascript

$(function () {
        $('.menu').on('click', function () {
        if ($('.sidebar').is(':visible')) {
            $('.sidebar').animate({'width': '0px'}, 'slow', function () {
                $('.sidebar').hide();
            });
            $('.main-page').animate({'padding-left': '0px'}, 'slow');
        } else {
            $('.sidebar').show();
            $('.sidebar').animate({'width': '240px'}, 'slow');
            $('.main-page').animate({'padding-left': '240px'}, 'slow');
        }
        });
    });

here is working fiddle example

https://codepen.io/mnikolaus/pen/mqByqK


问:
How to wait inside a beforeEach in Angular 4/Jasmine
One of my components uses a setTimeout inside ngOnInit, e.g:

```<code>ngOnInit() {
  setTimeout(() => {
      // do some setup stuff using FormBuilder
  }, 100);
}
</code>```

In the unit tests for this component, I need to spy on one of the methods of one of the controls which are built programmatically using FormBuilder, so I am doing this in a beforeEach:

```<code>describe('testing something', () => {

    beforeEach(() => {
        spyOn(component.form.controls.myControl, 'enable');
    });

    it('does something', () => {
      // test stuff
    });

});
</code>```

Before the timeout was added, the test was working perfectly. How can I make the beforeEach wait for the 100 ms timeout in the ngOnInit method?

I've tried adding async and fakeAsync to the outer describe, e.g. like this:

```<code> describe('testing something', <any>fakeAsync(() => {
     ...
 }));
</code>```

or

```<code>describe('testing something', async(() => {
     ...
 }));
</code>```

But in the first case, with fakeAsync I see a message in the test runner Error: Expected to be running in 'ProxyZone', but it was not found., and in the second case it just doesn't even run the test. I also tried wrapping the it methods in fakeAsync but that doesn't do anything to delay the beforeEach

I've tried wrapping the spyOn method inside the beforeEach in a setTimeout and this doesn't appear to have any effect, i.e. the test fails in the same way.

I've also tried using fakeAsync with the beforeEach, like this:

```<code>beforeEach(<any>fakeAsync(() => {
    tick(100);
    spyOn(component.modelForm.controls.myControl, 'enable');

  }));
</code>```

But this doesn't work either. It doesn't result in any errors, but the method I want to spy on doesn't exist yet, even after the tick.

How can I force the beforeEach to wait for the timeout in ngOnInit()? Is it even possible?

答:
The following solution can be adapted for beforeEach if needed

before(() => {
  jasmine.clock().install();
})

after(() => {
  jasmine.clock().uninstall();
})

it('test case', () => {
  spyOn(component.modelForm.controls.myControl, 'enable');

  component.ngOnInit();

  var timeout = 2000 // 2 seconds
  jasmine.clock().tick(timeout);

  expect(component.modelForm.controls.myControl.enable).toHaveBeenCalled()
})```

Body:
One of my components uses a setTimeout inside ngOnInit, e.g:

ngOnInit() {
  setTimeout(() => {
      // do some setup stuff using FormBuilder
  }, 100);
}

In the unit tests for this component, I need to spy on one of the methods of one of the controls which are built programmatically using FormBuilder, so I am doing this in a beforeEach:

describe('testing something', () => {

    beforeEach(() => {
        spyOn(component.form.controls.myControl, 'enable');
    });

    it('does something', () => {
      // test stuff
    });

});

Before the timeout was added, the test was working perfectly. How can I make the beforeEach wait for the 100 ms timeout in the ngOnInit method?

I've tried adding async and fakeAsync to the outer describe, e.g. like this:

 describe('testing something', <any>fakeAsync(() => {
     ...
 }));

or

describe('testing something', async(() => {
     ...
 }));

But in the first case, with fakeAsync I see a message in the test runner Error: Expected to be running in 'ProxyZone', but it was not found., and in the second case it just doesn't even run the test. I also tried wrapping the it methods in fakeAsync but that doesn't do anything to delay the beforeEach

I've tried wrapping the spyOn method inside the beforeEach in a setTimeout and this doesn't appear to have any effect, i.e. the test fails in the same way.

I've also tried using fakeAsync with the beforeEach, like this:

beforeEach(<any>fakeAsync(() => {
    tick(100);
    spyOn(component.modelForm.controls.myControl, 'enable');

  }));

But this doesn't work either. It doesn't result in any errors, but the method I want to spy on doesn't exist yet, even after the tick.

How can I force the beforeEach to wait for the timeout in ngOnInit()? Is it even possible?


问:
Pass arguments to signal handler in C
How can I pass arguments (e.g. a pointer to a struct) to a signal handler?
I'm writing a multithread application, so I cannot use global variables

I associate a timer to each thread. When timer expires I have to update a struct (each thread has a different struct).

How can I do?

答:
POSIX timers allow to specify the details of how your process will be notified of an expiration using the struct sigevent structure documented in sigevent(7).

To pass context info to the siggnal handler for the generated signal, you can set the .sigev_value.sival_ptr member, which your signal handler will then be able to retrieve (you'll need to set the signal handler via the .sa_sigaction member of struct sigaction, while making sure the structure's .sa_flags is ORred with SA_SIGINFO).

Title: Pass arguments to signal handler in C

ContentLicense: CC BY-SA 4.0


问:
How to loop over object with unknown keys and values
I get a JSON response of shoe sizes from an API endpoint that looks like this:

```<code>data: [{
    0: {
        system: "US",
        sizes: {
            7: {B: 3, C: 6, D: 1, E: 1}
            7.5: {A: 6, B: 7, C: 14, D: 11, E: 2}
            8: {2E: 1, A: 5, B: 32, C: 38, D: 23, …}
            8.5: {2E: 2, A: 9, B: 56, C: 79, D: 61, …}
            9: {2A: 5, 2E: 4, A: 17, B: 92, C: 143, …}
            9.5: {2A: 3, 2E: 3, A: 26, B: 132, C: 194, …}
            10: {2A: 5, 2E: 3, 3A: 1, A: 53, B: 159, …}
        }
    }
}]
</code>```

The data shows e.g that US size 7 has four different kinds of shapes (B, C, D, E) where 3 people have foots of shape B. In total, 11 people has size 7. The list can contain sizes in US, EU or different systems, and key of shapes can be A-Z or basically anything else.

I want to loop over sizes and create a diagram of how many people that has a certain size, and how many has a certain shape of that size.

What would be the best way to loop over an object like this to get the value of every shape? I would expect it to be an array of sizes.

ES6 or ES7 is fine but I would prefer to do it without jQuery.

EDIT:
Let me be more clear.
First of all I have considered improving data structure but unfortunately that's not an option.

I have tried Object.keys(sizes) which returns an array of the keys. Sure that's one step forward. But I would like to call a function that returns an object with the keys and its values. In my mind, that return value should be something like this:

```<code>sizes: [
    {
        size: 7,
        total: 11
        shapes: [
            {name: 'B', value: 3},
            {name: 'C', value: 6},
            {name: 'D', value: 1},
            {name: 'E', value: 1}
        ]
    },{...},{...}
]
</code>```

Does that makes sense? Of course, length is not absolutely necessary to include in the object.

答:
You can extract all of the keys of an object into an array and simply iterate over that array.

var obj = {
  'key1': 'val1',
  'key2': 'val2'
}
var keys = Object.keys(obj); // ['key1', 'key2']
keys.forEach( function(key) {
  var values = obj[key]
  console.log(values)
  // do stuff with "values"
})```

Reference -

Object.keys()

Body:
I get a JSON response of shoe sizes from an API endpoint that looks like this:

data: [{
    0: {
        system: "US",
        sizes: {
            7: {B: 3, C: 6, D: 1, E: 1}
            7.5: {A: 6, B: 7, C: 14, D: 11, E: 2}
            8: {2E: 1, A: 5, B: 32, C: 38, D: 23, …}
            8.5: {2E: 2, A: 9, B: 56, C: 79, D: 61, …}
            9: {2A: 5, 2E: 4, A: 17, B: 92, C: 143, …}
            9.5: {2A: 3, 2E: 3, A: 26, B: 132, C: 194, …}
            10: {2A: 5, 2E: 3, 3A: 1, A: 53, B: 159, …}
        }
    }
}]

The data shows e.g that US size 7 has four different kinds of shapes (B, C, D, E) where 3 people have foots of shape B. In total, 11 people has size 7. The list can contain sizes in US, EU or different systems, and key of shapes can be A-Z or basically anything else.

I want to loop over sizes and create a diagram of how many people that has a certain size, and how many has a certain shape of that size.

What would be the best way to loop over an object like this to get the value of every shape? I would expect it to be an array of sizes.

ES6 or ES7 is fine but I would prefer to do it without jQuery.

EDIT:
Let me be more clear.
First of all I have considered improving data structure but unfortunately that's not an option.

I have tried Object.keys(sizes) which returns an array of the keys. Sure that's one step forward. But I would like to call a function that returns an object with the keys and its values. In my mind, that return value should be something like this:

sizes: [
    {
        size: 7,
        total: 11
        shapes: [
            {name: 'B', value: 3},
            {name: 'C', value: 6},
            {name: 'D', value: 1},
            {name: 'E', value: 1}
        ]
    },{...},{...}
]

Does that makes sense? Of course, length is not absolutely necessary to include in the object.

Body:
You can extract all of the keys of an object into an array and simply iterate over that array.

var obj = {
  'key1': 'val1',
  'key2': 'val2'
}
var keys = Object.keys(obj); // ['key1', 'key2']
keys.forEach( function(key) {
  var values = obj[key]
  console.log(values)
  // do stuff with "values"
})

Reference -

Object.keys()


问:
Does HTML5 change anything if I don't use video or audio?
I keep hearing all about HTML5 and how great it is, but if I don't really care about audio and video, is there anything it really changes for me? I've read up on the new tags it supports and they just don't seem to be all that revolutionary beyond its video and audio capabilities.</p>

答:
One of the biggest deals about HTML5 which is under reported is that HTML4 never defined error handing, but this is well defined in HTML5. All browser vendors are building HTML5 parsers that conform to this spec. While this is not sexy, the end result will be that browsers will become more interoperable with each other (especially in cases where the author makes an error). In the long run this should mean you'll spend less time trying to get all browsers to work correctly, and users will benefit from less broken sites in their browser of choice.

HTML5 also allows you to make more application quality sites, using many of the technologies mentioned in the other answers. Opera Dragonfly (the project I'm involved with) is a complex web app which doesn't use audio or video but takes advantage of a large number of HTML5 technologies. We use AppCache to make sure it still works when you are offline, Web Storage to save user preferences and history (we can store a lot more information than cookies allowed) and will likely use Web Workers to allow the app to use more than one process at once (will speed up performance on mult-core machines).

If you are doing anything with graphics then the Canvas API gives you a lot of drawing options, while SVG (an open vector format) can be used within your HTML pages now. Previously pages had to be served as XML for SVG to be included inside them.


问:
How to get value of cell instead formula value?
I use this library openpyxl.

And read data as:

```<code>for row in sheet.rows:
    print row[0].value
</code>```

Instead value of cell I get formula: =D42-D42*0.1.

答:
Edit: In latest version (3.0.6+) the api was changed to disable the user of the first option (internal_value property) and thus only the second option now works. (Thanks Akshat)

You can either

Use row[0].internal_value.

Or

Use data_only=True when you load your workbook.
(For example, workbook = openpyxl.load_workbook("yourxlsx.xlsx", data_only=True))

The second option is good when you are sure you don't wish to ever get the original formula from the workbook.

Body:
I use this library openpyxl.

And read data as:

for row in sheet.rows:
    print row[0].value

Instead value of cell I get formula: =D42-D42*0.1.


问:
How to Filter Nested Array Object in DynamoDB
I am very beginner to AWS DynamoDB, I want to scan the DynamoDB with SENDTO.emailAddress = "first@first.com" as FilterExpression.

The DB Structure looks like this

```<code>{
    ID
    NAME
    MESSAGE
    SENDTO[
        {
            name
            emailAddress
        }
    ]
}
</code>```

A Sample Data

```<code>{
    ID: 1,
    NAME: "HELLO",
    MESSAGE: "HELLO WORLD!",
    SENDTO: [
        {
            name: "First",
            emailAddress: "first@first.com"
        },
        {
            name: "Second",
            emailAddress: "second@first.com"
        }
    ]
}
</code>```

I want to retrieve document that match emailAddress. I tried to scan with filter expression and here is my code to retrieve the data. I am using AWS Javascript SDK.

```<code>let params = {
    TableName : "email",
    FilterExpression: "SENDTO.emailAddress = :emailAddress",
    ExpressionAttributeValues: {
        ":emailAddress": "first@first.com",
    }
}

let result = await ctx.docClient.scan(params).promise();
</code>```

答:
I think that you should create two tables for users and for messages.

The user table has partition_key: user_id and sort_key: email and a field with an array of his messages ids.

The message table has partition_key: message_id and a field with an array of users ids.

When you will get the array of users ids you can use BATCH GET query to get all users of one message.

When you will get the array of message ids you can use BATCH GET query to get all messages of one user.

If you want to get one user by email you can use QUERY method.

Docs

Body:
I am very beginner to AWS DynamoDB, I want to scan the DynamoDB with SENDTO.emailAddress = "first@first.com" as FilterExpression.

The DB Structure looks like this

{
    ID
    NAME
    MESSAGE
    SENDTO[
        {
            name
            emailAddress
        }
    ]
}

A Sample Data

{
    ID: 1,
    NAME: "HELLO",
    MESSAGE: "HELLO WORLD!",
    SENDTO: [
        {
            name: "First",
            emailAddress: "first@first.com"
        },
        {
            name: "Second",
            emailAddress: "second@first.com"
        }
    ]
}

I want to retrieve document that match emailAddress. I tried to scan with filter expression and here is my code to retrieve the data. I am using AWS Javascript SDK.

let params = {
    TableName : "email",
    FilterExpression: "SENDTO.emailAddress = :emailAddress",
    ExpressionAttributeValues: {
        ":emailAddress": "first@first.com",
    }
}

let result = await ctx.docClient.scan(params).promise();


问:
How do I get all data from a form using Vue
I've the following markup.

```<code><div class="checkbox">
  <label>
    <input class="weekdays" name="wednesday[]" v-model="wed.selected" id="wednesday" type="checkbox"> Wed
  </label>
</div>
<div class="checkbox">
  <label>
    <input class="weekdays" name="thursday[]" v-model="thu.selected" id="thursday" type="checkbox"> Thu
  </label>
</div>
</code>```

Similarly for all other days of the week. And in the Vue instance:

```<code>new Vue({
    el: '#provider',
    data: {
        mon: {selected: false, day: 'Mondays'},
        tue: {selected: false, day: 'Tuesdays'},
        wed: {selected: false, day: 'Wednesdays'},
        thu: {selected: false, day: 'Thursdays'},
        fri: {selected: false, day: 'Fridays'},
        sat: {selected: false, day: 'Saturdays'},
        sun: {selected: false, day: 'Sundays'},
        weekends: {selected: false, day: 'Weekends'},
        weekdays: {selected: false, day: 'Weekdays'},
        fromTime: '',
        toTime: '',
        selectedDays:[{
            days : [],
            from: '',
            to:''
        }]

    },
    methods: {
        addAvailability: function() {
            if(this.mon.selected)
            {
                var days = [];
                days.push(this.mon.day);
                this.selectedDays['days'].push(days);
            }
        }
    }
});
</code>```

But this seems not working. What I'm trying to do here is when I click on a button, I want to add all checked days and time in to a variable selectedDays and add it to a hidden input field (json serialize the data).But what I've tried is not working well.

Can anybody direct me to the right direction? I've spent 3 days and I couldn't figure out how to fix this.

答:
Have you tried:

```<code>//HTML
<div id='example-3'>
  <input type="checkbox" id="jack" value="Jack" v-model="checkedNames">
  <label for="jack">Jack</label>
  <input type="checkbox" id="john" value="John" v-model="checkedNames">
  <label for="john">John</label>
  <input type="checkbox" id="mike" value="Mike" v-model="checkedNames">
  <label for="mike">Mike</label>
  <br>
  <span>Checked names: {{ checkedNames }}</span>
</div>
</code>```

and for js:

```<code>new Vue({
  el: '#example-3',
  data: {
    checkedNames: []
  }
})
</code>```

This is straight from the documentation. it will push all selected checkbox's value into the chackedNames array

Body:
I've the following markup.

    <input class="weekdays" name="wednesday[]" v-model="wed.selected" id="wednesday" type="checkbox"> Wed

    <input class="weekdays" name="thursday[]" v-model="thu.selected" id="thursday" type="checkbox"> Thu

Similarly for all other days of the week. And in the Vue instance:

new Vue({
    el: '#provider',
    data: {
        mon: {selected: false, day: 'Mondays'},
        tue: {selected: false, day: 'Tuesdays'},
        wed: {selected: false, day: 'Wednesdays'},
        thu: {selected: false, day: 'Thursdays'},
        fri: {selected: false, day: 'Fridays'},
        sat: {selected: false, day: 'Saturdays'},
        sun: {selected: false, day: 'Sundays'},
        weekends: {selected: false, day: 'Weekends'},
        weekdays: {selected: false, day: 'Weekdays'},
        fromTime: '',
        toTime: '',
        selectedDays:[{
            days : [],
            from: '',
            to:''
        }]

    },
    methods: {
        addAvailability: function() {
            if(this.mon.selected)
            {
                var days = [];
                days.push(this.mon.day);
                this.selectedDays['days'].push(days);
            }
        }
    }
});

But this seems not working. What I'm trying to do here is when I click on a button, I want to add all checked days and time in to a variable selectedDays and add it to a hidden input field (json serialize the data).But what I've tried is not working well.

Can anybody direct me to the right direction? I've spent 3 days and I couldn't figure out how to fix this.

Body:
Have you tried:

//HTML
<div id='example-3'>
  <input type="checkbox" id="jack" value="Jack" v-model="checkedNames">
  <label for="jack">Jack</label>
  <input type="checkbox" id="john" value="John" v-model="checkedNames">
  <label for="john">John</label>
  <input type="checkbox" id="mike" value="Mike" v-model="checkedNames">
  <label for="mike">Mike</label>
  <br>
  <span>Checked names: {{ checkedNames }}</span>
</div>

and for js:

new Vue({
  el: '#example-3',
  data: {
    checkedNames: []
  }
})

This is straight from the documentation. it will push all selected checkbox's value into the chackedNames array


问:
Stripes for Java Web Dev, is it worth learning ? Is it easier ? how it compared to Struts?
I am tired of Java web, and started to learn Ruby on Rails because of that, but I just found this Framework and it looks promessing... But I am not in the mood to study more Java, so I would like to know if this one is worth my time ( that would mean, less configuration and action mapping and so on)

Is it better then Struts 2(WebWorks) ??? because those are way better then Struts 1 but still not a RoR.

Spring MVC ?

I would like a Hands On Opnion, not a specs compare.

Thanks !

答:
The problem is not in language. At least for the last ten years it is mostly not in the language. Please stay with Java. Many people are tired of Java Web though - that is exactly why each year at least one new attempt to suggest a Java framework happens. Currently there are about 50 of presentation frameworks only. The so called "mainstream" Java technologies (Spring, Wicket, Struts and JSF) prove to be very very conservative after they reach some success and size.

The new wave like Web4j, Play and HybridJava concentrate strongly on making things back as simple as they were for Adam. Before leaving this (Java) world forever consider using one of those new.


问:
Laravel Session Flash persists for 2 requests
Recently I have changed to Laravel from Codeigniter, everything was going fine except I encountered a problem with Session::flash.

when I create new user I get success message but It will persist for 2 requests, even I didn't pass the validator:

my code in UsersController:

```<code>function getCreateUser(){
    $config = array(
        'pageName' => 'createUser',
        'pageTitle' => 'Create User',
        'formUrl'   => action('UsersController@postCreateUser'),
        'modelFields'   => array(
            array('db_name' => 'employee_id', 'text' => 'Employee Id', 'mandatory' => TRUE),
            array('db_name' => 'full_name', 'text' => 'Full Name', 'mandatory' => TRUE),
            array('db_name' => 'email', 'text' => 'Email', 'mandatory' => FALSE),
            array('db_name' => 'password', 'text' => 'Password','value' => '12345', 'mandatory' => TRUE)
            ),
        'submit_text' => 'Create'
        );
    return View::make('layouts.form', $config);
}

function postCreateUser(){
    $config = array(
        'pageName' => 'createUser',
        'pageTitle' => 'Create User',
        'formUrl'   => action('UsersController@postCreateUser'),
        'modelFields'   => array(
            array('db_name' => 'employee_id', 'text' => 'Employee Id', 'mandatory' => TRUE),
            array('db_name' => 'full_name', 'text' => 'Full Name', 'mandatory' => TRUE),
            array('db_name' => 'email', 'text' => 'Email', 'mandatory' => FALSE),
            array('db_name' => 'password', 'text' => 'Password','value' => '12345', 'mandatory' => TRUE)
            ),
        'submit_text' => 'Create'
        );
    $validator = User::validate(Input::all());
    if($validator->passes()){
        $user = new User(Input::all());
        $user->password = Hash::make(Input::get('password'));
        $user->Company_id = '1';
        $user->save();

        Session::flash('message', 'User Created Successfully!');
        Session::flash('alert-class', 'alert-success');
        return View::make('layouts.form', $config);
    }

    return View::make('layouts.form', $config)->withErrors($validator->messages());
}
</code>```

in form.blade:

```<code>@if ( $errors->count() > 0 )
<div class="alert alert-danger">
    <p>The following errors have occurred:</p>

    <ul>
        @foreach( $errors->all() as $message )
        <li>{{ $message }}</li>
        @endforeach
    </ul>
</div>
@endif
</code>```

in master.blade:

```<code>@if(Session::has('message'))
<p class="alert {{ Session::get('alert-class', 'alert-info') }} alert-dismissable"> {{ Session::get('message') }}</p>
@endif
</code>```

Maybe I'm not alone with this issue, here is another unanswered question.

Update

For anyone in future facing this problem:
Never flash session data without redirecting.

My code now looks like this:

```<code>function postCreateUser(){
    $validator = User::validate(Input::all());
    if($validator->passes()){
        $user = new User(Input::all());
        $user->password = Hash::make(Input::get('password'));
        $user->Company_id = '1';
        $user->save();

        Session::flash('message', 'User Created Successfully!');
        Session::flash('alert-class', 'alert-success');
    } else {
        Session::flash('message', Helpers::formatErrors($validator->messages()->all()));
        Session::flash('alert-class', 'alert-danger');
    }

    return Redirect::action('UsersController@getCreateUser');
}
</code>```

答:
The following seems to be available from version 5.1 onward. It used to be undocumented, now it is: see Laravel's session documentation.

```<code>session()->now()
</code>```

This is the same as flash, except it won't persist to the next request.

Body:
Recently I have changed to Laravel from Codeigniter, everything was going fine except I encountered a problem with Session::flash.

when I create new user I get success message but It will persist for 2 requests, even I didn't pass the validator:

my code in UsersController:

function getCreateUser(){
    $config = array(
        'pageName' => 'createUser',
        'pageTitle' => 'Create User',
        'formUrl'   => action('UsersController@postCreateUser'),
        'modelFields'   => array(
            array('db_name' => 'employee_id', 'text' => 'Employee Id', 'mandatory' => TRUE),
            array('db_name' => 'full_name', 'text' => 'Full Name', 'mandatory' => TRUE),
            array('db_name' => 'email', 'text' => 'Email', 'mandatory' => FALSE),
            array('db_name' => 'password', 'text' => 'Password','value' => '12345', 'mandatory' => TRUE)
            ),
        'submit_text' => 'Create'
        );
    return View::make('layouts.form', $config);
}

function postCreateUser(){
    $config = array(
        'pageName' => 'createUser',
        'pageTitle' => 'Create User',
        'formUrl'   => action('UsersController@postCreateUser'),
        'modelFields'   => array(
            array('db_name' => 'employee_id', 'text' => 'Employee Id', 'mandatory' => TRUE),
            array('db_name' => 'full_name', 'text' => 'Full Name', 'mandatory' => TRUE),
            array('db_name' => 'email', 'text' => 'Email', 'mandatory' => FALSE),
            array('db_name' => 'password', 'text' => 'Password','value' => '12345', 'mandatory' => TRUE)
            ),
        'submit_text' => 'Create'
        );
    $validator = User::validate(Input::all());
    if($validator->passes()){
        $user = new User(Input::all());
        $user->password = Hash::make(Input::get('password'));
        $user->Company_id = '1';
        $user->save();

        Session::flash('message', 'User Created Successfully!');
        Session::flash('alert-class', 'alert-success');
        return View::make('layouts.form', $config);
    }

    return View::make('layouts.form', $config)->withErrors($validator->messages());
}

in form.blade:

@if ( $errors->count() > 0 )

The following errors have occurred:

        @foreach( $errors->all() as $message )

{{ $message }}

        @endforeach

@endif

in master.blade:

@if(Session::has('message'))

 {{ Session::get('message') }}

@endif

Maybe I'm not alone with this issue, here is another unanswered question.

Update

For anyone in future facing this problem:
Never flash session data without redirecting.

My code now looks like this:

function postCreateUser(){
    $validator = User::validate(Input::all());
    if($validator->passes()){
        $user = new User(Input::all());
        $user->password = Hash::make(Input::get('password'));
        $user->Company_id = '1';
        $user->save();

        Session::flash('message', 'User Created Successfully!');
        Session::flash('alert-class', 'alert-success');
    } else {
        Session::flash('message', Helpers::formatErrors($validator->messages()->all()));
        Session::flash('alert-class', 'alert-danger');
    }

    return Redirect::action('UsersController@getCreateUser');
}

Body:
The following seems to be available from version 5.1 onward. It used to be undocumented, now it is: see Laravel's session documentation.

session()->now()

This is the same as flash, except it won't persist to the next request.