问:
Azure Web Job sometimes cannot connect to storage account
We have an Azure Web Job that runs (with [Singleton] attribute) and it occasionally complains about not being able to connect to the storage account that it needs to aquire the lock or when we try to log to storage account.

In the web job logs, it will result in "Invalid storage account XXXXXX. Please make sure your credentials are correct."

I have double-checked the access keys for the storage account, and the values in the hosting Azure Service's connection strings for the AzureWebJobsStorage and AzureWebJobsDashboard and also for our own application setting that we use when trying to create a CloudTableClient for logging.

This is intermittent, and works about 80% of the time, and 20% time it complains.

Sample from logs:

```<code>    [12/02/2017 16:45:10 > d747a0: INFO] Singleton lock acquired (5d3cc9c4e92841579c4df47db66e5bfc/CHO.WebJobs.csRfid.GPOFunctions.ProcessQueueMessage)

[12/02/2017 16:45:10 > d747a0: INFO] 12/2/2017 4:45:10 PM - Rfid processing started for Message Id 3286783.

[12/02/2017 16:45:13 > d747a0: INFO] Microsoft.ServiceBus.Messaging.BrokeredMessage{MessageId:3286783}

[12/02/2017 16:45:13 > d747a0: INFO] 12/2/2017 4:45:13 PM - Rfid processing finished for Message Id 3286783.

[12/02/2017 16:45:13 > d747a0: INFO] Singleton lock released (5d3cc9c4e92841579c4df47db66e5bfc/CHO.WebJobs.csRfid.GPOFunctions.ProcessQueueMessage)

[12/02/2017 16:45:13 > d747a0: INFO] Executed 'GPOFunctions.ProcessQueueMessage' (Succeeded, Id=aa430942-4fcb-4fa6-a899-fe936a183494)

[12/02/2017 16:45:13 > d747a0: INFO] Executing 'GPOFunctions.ProcessQueueMessage' (Reason='New ServiceBus message detected on 'tprfid/Subscriptions/subRfidUat'.', Id=c6eb4e56-ebd0-4410-acde-4e3bd7c3666d)

[12/02/2017 16:45:13 > d747a0: INFO] Singleton lock acquired (5d3cc9c4e92841579c4df47db66e5bfc/CHO.WebJobs.csRfid.GPOFunctions.ProcessQueueMessage)

[12/02/2017 16:45:13 > d747a0: INFO] 12/2/2017 4:45:13 PM - Rfid processing started for Message Id 3286784.

[12/02/2017 16:45:16 > d747a0: INFO] Microsoft.ServiceBus.Messaging.BrokeredMessage{MessageId:3286784}

[12/02/2017 16:45:16 > d747a0: WARN] Reached maximum allowed output lines for this run, to see all of the job's logs you can enable website application diagnostics

[12/02/2017 16:55:03 > d747a0: SYS ERR ] Job failed due to exit code -532462766

[12/02/2017 16:55:03 > d747a0: SYS INFO] Process went down, waiting for 0 seconds

[12/02/2017 16:55:03 > d747a0: SYS INFO] Status changed to PendingRestart

[12/02/2017 16:55:03 > d747a0: SYS INFO] Run script 'CHO.WebJobs.csRfid.exe' with script host - 'WindowsScriptHost'

[12/02/2017 16:55:03 > d747a0: SYS INFO] Status changed to Running

[12/02/2017 16:55:11 > d747a0: INFO] Found the following functions:

[12/02/2017 16:55:11 > d747a0: INFO] CHO.WebJobs.csRfid.GPOFunctions.ProcessQueueMessage

[12/02/2017 16:55:11 > d747a0: INFO] CHO.WebJobs.csRfid.GPOFunctions.ProcessTimer

[12/02/2017 16:55:12 > d747a0: INFO] Singleton lock acquired (5d3cc9c4e92841579c4df47db66e5bfc/CHO.WebJobs.csRfid.GPOFunctions.ProcessTimer.Listener)

[12/02/2017 16:55:12 > d747a0: INFO] Executing 'GPOFunctions.ProcessQueueMessage' (Reason='New ServiceBus message detected on 'tprfid/Subscriptions/subRfidUat'.', Id=ac2385b9-2000-4533-9166-57df9fef904f)

[12/02/2017 16:55:12 > d747a0: INFO] Singleton lock acquired (5d3cc9c4e92841579c4df47db66e5bfc/CHO.WebJobs.csRfid.GPOFunctions.ProcessQueueMessage)

[12/02/2017 16:55:13 > d747a0: INFO] 12/2/2017 4:55:13 PM - Rfid processing started for Message Id 3286815.

[12/02/2017 16:55:42 > d747a0: ERR ]

[12/02/2017 16:55:42 > d747a0: ERR ] Unhandled Exception: Microsoft.WindowsAzure.Storage.StorageException: Unable to connect to the remote server ---> System.Net.WebException: Unable to connect to the remote server ---> System.Net.Sockets.SocketException: An attempt was made to access a socket in a way forbidden by its access permissions

[12/02/2017 16:55:42 > d747a0: ERR ]    at System.Net.Sockets.Socket.DoBind(EndPoint endPointSnapshot, SocketAddress socketAddress)

[12/02/2017 16:55:42 > d747a0: ERR ]    at System.Net.Sockets.Socket.InternalBind(EndPoint localEP)

[12/02/2017 16:55:42 > d747a0: ERR ]    at System.Net.Sockets.Socket.BeginConnectEx(EndPoint remoteEP, Boolean flowContext, AsyncCallback callback, Object state)

[12/02/2017 16:55:42 > d747a0: ERR ]    at System.Net.Sockets.Socket.UnsafeBeginConnect(EndPoint remoteEP, AsyncCallback callback, Object state)

[12/02/2017 16:55:42 > d747a0: ERR ]    at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Exception& exception)

[12/02/2017 16:55:42 > d747a0: ERR ]    --- End of inner exception stack trace ---

[12/02/2017 16:55:42 > d747a0: ERR ]    at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)

[12/02/2017 16:55:42 > d747a0: ERR ]    at Microsoft.WindowsAzure.Storage.Core.Executor.Executor.EndGetResponse[T](IAsyncResult getResponseResult) in c:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\ClassLibraryCommon\Core\Executor\Executor.cs:line 284

[12/02/2017 16:55:42 > d747a0: ERR ]    --- End of inner exception stack trace ---

[12/02/2017 16:55:42 > d747a0: ERR ]    at Microsoft.WindowsAzure.Storage.Core.Executor.Executor.EndExecuteAsync[T](IAsyncResult result) in c:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\ClassLibraryCommon\Core\Executor\Executor.cs:line 50

[12/02/2017 16:55:42 > d747a0: ERR ]    at Microsoft.WindowsAzure.Storage.Queue.CloudQueue.EndExists(IAsyncResult asyncResult) in c:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\ClassLibraryCommon\Queue\CloudQueue.cs:line 994

[12/02/2017 16:55:42 > d747a0: ERR ]    at Microsoft.WindowsAzure.Storage.Core.Util.AsyncExtensions.<>c__DisplayClass1`1.<CreateCallback>b__0(IAsyncResult ar) in c:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\ClassLibraryCommon\Core\Util\AsyncExtensions.cs:line 66

[12/02/2017 16:55:42 > d747a0: ERR ] --- End of stack trace from previous location where exception was thrown ---

[12/02/2017 16:55:42 > d747a0: ERR ]    at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)

[12/02/2017 16:55:42 > d747a0: ERR ]    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

[12/02/2017 16:55:42 > d747a0: ERR ]    at Microsoft.Azure.WebJobs.Host.Queues.Listeners.QueueListener.<ExecuteAsync>d__21.MoveNext()

[12/02/2017 16:55:42 > d747a0: ERR ] --- End of stack trace from previous location where exception was thrown ---

[12/02/2017 16:55:42 > d747a0: ERR ]    at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)

[12/02/2017 16:55:42 > d747a0: ERR ]    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

[12/02/2017 16:55:42 > d747a0: ERR ]    at Microsoft.Azure.WebJobs.Host.Timers.TaskSeriesTimer.<RunAsync>d__14.MoveNext()

[12/02/2017 16:55:42 > d747a0: ERR ] --- End of stack trace from previous location where exception was thrown ---

[12/02/2017 16:55:42 > d747a0: ERR ]    at Microsoft.Azure.WebJobs.Host.Timers.WebJobsExceptionHandler.<>c__DisplayClass3_0.<OnUnhandledExceptionAsync>b__0()

[12/02/2017 16:55:42 > d747a0: ERR ]    at System.Threading.ThreadHelper.ThreadStart_Context(Object state)

[12/02/2017 16:55:42 > d747a0: ERR ]    at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)

[12/02/2017 16:55:42 > d747a0: ERR ]    at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)

[12/02/2017 16:55:42 > d747a0: ERR ]    at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)

[12/02/2017 16:55:42 > d747a0: ERR ]    at System.Threading.ThreadHelper.ThreadStart()

[12/02/2017 16:55:42 > d747a0: SYS ERR ] Job failed due to exit code -532462766

[12/02/2017 16:55:42 > d747a0: SYS INFO] Process went down, waiting for 60 seconds

[12/02/2017 16:55:42 > d747a0: SYS INFO] Status changed to PendingRestart

[12/02/2017 17:03:44 > d747a0: SYS INFO] Run script 'CHO.WebJobs.csRfid.exe' with script host - 'WindowsScriptHost'

[12/02/2017 17:03:44 > d747a0: SYS INFO] Status changed to Running

[12/02/2017 17:04:13 > d747a0: ERR ]

[12/02/2017 17:04:13 > d747a0: ERR ] Unhandled Exception: System.InvalidOperationException: Invalid storage account 'sachouat'. Please make sure your credentials are correct.

[12/02/2017 17:04:13 > d747a0: ERR ]    at Microsoft.Azure.WebJobs.Host.Executors.DefaultStorageCredentialsValidator.<ValidateCredentialsAsyncCore>d__2.MoveNext()

[12/02/2017 17:04:13 > d747a0: ERR ] --- End of stack trace from previous location where exception was thrown ---

[12/02/2017 17:04:13 > d747a0: ERR ]    at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)

[12/02/2017 17:04:13 > d747a0: ERR ]    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

[12/02/2017 17:04:13 > d747a0: ERR ]    at Microsoft.Azure.WebJobs.Host.Executors.DefaultStorageCredentialsValidator.<ValidateCredentialsAsync>d__1.MoveNext()

[12/02/2017 17:04:13 > d747a0: ERR ] --- End of stack trace from previous location where exception was thrown ---

[12/02/2017 17:04:13 > d747a0: ERR ]    at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)

[12/02/2017 17:04:13 > d747a0: ERR ]    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

[12/02/2017 17:04:13 > d747a0: ERR ]    at Microsoft.Azure.WebJobs.Host.Executors.DefaultStorageAccountProvider.<TryGetAccountAsync>d__23.MoveNext()

[12/02/2017 17:04:13 > d747a0: ERR ] --- End of stack trace from previous location where exception was thrown ---

[12/02/2017 17:04:13 > d747a0: ERR ]    at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)

[12/02/2017 17:04:13 > d747a0: ERR ]    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

[12/02/2017 17:04:13 > d747a0: ERR ]    at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)

[12/02/2017 17:04:13 > d747a0: ERR ]    at Microsoft.Azure.WebJobs.Host.Executors.JobHostContextFactory.<CreateAndLogHostStartedAsync>d__5.MoveNext()

[12/02/2017 17:04:13 > d747a0: ERR ] --- End of stack trace from previous location where exception was thrown ---

[12/02/2017 17:04:13 > d747a0: ERR ]    at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)

[12/02/2017 17:04:13 > d747a0: ERR ]    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

[12/02/2017 17:04:13 > d747a0: ERR ]    at Microsoft.Azure.WebJobs.Host.Executors.JobHostContextFactory.<CreateAndLogHostStartedAsync>d__4.MoveNext()

[12/02/2017 17:04:13 > d747a0: ERR ] --- End of stack trace from previous location where exception was thrown ---

[12/02/2017 17:04:13 > d747a0: ERR ]    at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)

[12/02/2017 17:04:13 > d747a0: ERR ]    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

[12/02/2017 17:04:13 > d747a0: ERR ]    at Microsoft.Azure.WebJobs.JobHost.<CreateContextAndLogHostStartedAsync>d__44.MoveNext()

[12/02/2017 17:04:13 > d747a0: ERR ] --- End of stack trace from previous location where exception was thrown ---

[12/02/2017 17:04:13 > d747a0: ERR ]    at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)

[12/02/2017 17:04:13 > d747a0: ERR ]    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

[12/02/2017 17:04:13 > d747a0: ERR ]    at Microsoft.Azure.WebJobs.JobHost.<StartAsyncCore>d__27.MoveNext()

[12/02/2017 17:04:13 > d747a0: ERR ] --- End of stack trace from previous location where exception was thrown ---

[12/02/2017 17:04:13 > d747a0: ERR ]    at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)

[12/02/2017 17:04:13 > d747a0: ERR ]    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

[12/02/2017 17:04:13 > d747a0: ERR ]    at Microsoft.Azure.WebJobs.JobHost.Start()

[12/02/2017 17:04:13 > d747a0: ERR ]    at Microsoft.Azure.WebJobs.JobHost.RunAndBlock()

[12/02/2017 17:04:13 > d747a0: ERR ]    at CHO.WebJobs.csRfid.ProcessRfidXml.StartListening() in F:\agent\_work\4\s\CHO.WebJobs\CHO.WebJobs.csRfid\ProcessRfidXml.cs:line 68

[12/02/2017 17:04:13 > d747a0: ERR ]    at CHO.WebJobs.csRfid.Program.Main() in F:\agent\_work\4\s\CHO.WebJobs\CHO.WebJobs.csRfid\Program.cs:line 98

[12/02/2017 17:04:13 > d747a0: SYS ERR ] Job failed due to exit code -532462766

[12/02/2017 17:04:13 > d747a0: SYS INFO] Process went down, waiting for 60 seconds

[12/02/2017 17:04:13 > d747a0: SYS INFO] Status changed to PendingRestart

[12/02/2017 17:05:14 > d747a0: SYS INFO] Run script 'CHO.WebJobs.csRfid.exe' with script host - 'WindowsScriptHost'

[12/02/2017 17:05:14 > d747a0: SYS INFO] Status changed to Running

[12/02/2017 17:05:28 > d747a0: INFO] Found the following functions:

[12/02/2017 17:05:28 > d747a0: INFO] CHO.WebJobs.csRfid.GPOFunctions.ProcessQueueMessage

[12/02/2017 17:05:28 > d747a0: INFO] CHO.WebJobs.csRfid.GPOFunctions.ProcessTimer

[12/02/2017 17:05:29 > d747a0: INFO] Singleton lock acquired (5d3cc9c4e92841579c4df47db66e5bfc/CHO.WebJobs.csRfid.GPOFunctions.ProcessTimer.Listener)

[12/02/2017 17:05:29 > d747a0: INFO] Function 'CHO.WebJobs.csRfid.GPOFunctions.ProcessTimer' initial status: Last='2017-12-02T16:54:06.7331501+00:00', Next='2017-12-02T16:55:06.7331501+00:00'

[12/02/2017 17:05:29 > d747a0: INFO] Function 'CHO.WebJobs.csRfid.GPOFunctions.ProcessTimer' is past due on startup. Executing now.

[12/02/2017 17:05:32 > d747a0: INFO] Executing 'GPOFunctions.ProcessQueueMessage' (Reason='New ServiceBus message detected on 'tprfid/Subscriptions/subRfidUat'.', Id=15bc1f92-4def-4ba2-ba96-5c2f510ee933)

[12/02/2017 17:05:32 > d747a0: INFO] Singleton lock acquired (5d3cc9c4e92841579c4df47db66e5bfc/CHO.WebJobs.csRfid.GPOFunctions.ProcessQueueMessage)

[12/02/2017 17:05:33 > d747a0: INFO] Executing 'GPOFunctions.ProcessTimer' (Reason='Timer fired at 2017-12-02T17:05:29.9786228+00:00', Id=3d6dc09b-82fb-41ae-a8d6-9d140af14945)

[12/02/2017 17:05:33 > d747a0: INFO] Singleton lock acquired (5d3cc9c4e92841579c4df47db66e5bfc/CHO.WebJobs.csRfid.GPOFunctions.ProcessTimer)

[12/02/2017 17:05:33 > d747a0: INFO] 12/2/2017 5:05:33 PM - Rfid processing started for Message Id 3286814.

[12/02/2017 17:05:55 > d747a0: ERR ]

[12/02/2017 17:05:55 > d747a0: ERR ] Unhandled Exception: Microsoft.WindowsAzure.Storage.StorageException: Unable to connect to the remote server ---> System.Net.WebException: Unable to connect to the remote server ---> System.Net.Sockets.SocketException: An attempt was made to access a socket in a way forbidden by its access permissions

[12/02/2017 17:05:55 > d747a0: ERR ]    at System.Net.Sockets.Socket.DoBind(EndPoint endPointSnapshot, SocketAddress socketAddress)

[12/02/2017 17:05:55 > d747a0: ERR ]    at System.Net.Sockets.Socket.InternalBind(EndPoint localEP)

[12/02/2017 17:05:55 > d747a0: ERR ]    at System.Net.Sockets.Socket.BeginConnectEx(EndPoint remoteEP, Boolean flowContext, AsyncCallback callback, Object state)

[12/02/2017 17:05:55 > d747a0: ERR ]    at System.Net.Sockets.Socket.UnsafeBeginConnect(EndPoint remoteEP, AsyncCallback callback, Object state)

[12/02/2017 17:05:55 > d747a0: ERR ]    at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Exception& exception)

[12/02/2017 17:05:55 > d747a0: ERR ]    --- End of inner exception stack trace ---

[12/02/2017 17:05:55 > d747a0: ERR ]    at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)

[12/02/2017 17:05:55 > d747a0: ERR ]    at Microsoft.WindowsAzure.Storage.Core.Executor.Executor.EndGetResponse[T](IAsyncResult getResponseResult) in c:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\ClassLibraryCommon\Core\Executor\Executor.cs:line 284

[12/02/2017 17:05:55 > d747a0: ERR ]    --- End of inner exception stack trace ---

[12/02/2017 17:05:55 > d747a0: ERR ]    at Microsoft.WindowsAzure.Storage.Core.Executor.Executor.EndExecuteAsync[T](IAsyncResult result) in c:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\ClassLibraryCommon\Core\Executor\Executor.cs:line 50

[12/02/2017 17:05:55 > d747a0: ERR ]    at Microsoft.WindowsAzure.Storage.Queue.CloudQueue.EndExists(IAsyncResult asyncResult) in c:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\ClassLibraryCommon\Queue\CloudQueue.cs:line 994

[12/02/2017 17:05:55 > d747a0: ERR ]    at Microsoft.WindowsAzure.Storage.Core.Util.AsyncExtensions.<>c__DisplayClass1`1.<CreateCallback>b__0(IAsyncResult ar) in c:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\ClassLibraryCommon\Core\Util\AsyncExtensions.cs:line 66

[12/02/2017 17:05:55 > d747a0: ERR ] --- End of stack trace from previous location where exception was thrown ---

[12/02/2017 17:05:55 > d747a0: ERR ]    at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)

[12/02/2017 17:05:55 > d747a0: ERR ]    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

[12/02/2017 17:05:55 > d747a0: ERR ]    at Microsoft.Azure.WebJobs.Host.Queues.Listeners.QueueListener.<ExecuteAsync>d__21.MoveNext()

[12/02/2017 17:05:55 > d747a0: ERR ] --- End of stack trace from previous location where exception was thrown ---

[12/02/2017 17:05:55 > d747a0: ERR ]    at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)

[12/02/2017 17:05:55 > d747a0: ERR ]    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

[12/02/2017 17:05:55 > d747a0: ERR ]    at Microsoft.Azure.WebJobs.Host.Timers.TaskSeriesTimer.<RunAsync>d__14.MoveNext()

[12/02/2017 17:05:55 > d747a0: ERR ] --- End of stack trace from previous location where exception was thrown ---

[12/02/2017 17:05:55 > d747a0: ERR ]    at Microsoft.Azure.WebJobs.Host.Timers.WebJobsExceptionHandler.<>c__DisplayClass3_0.<OnUnhandledExceptionAsync>b__0()

[12/02/2017 17:05:55 > d747a0: ERR ]    at System.Threading.ThreadHelper.ThreadStart_Context(Object state)

[12/02/2017 17:05:55 > d747a0: ERR ]    at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)

[12/02/2017 17:05:55 > d747a0: ERR ]    at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)

[12/02/2017 17:05:55 > d747a0: ERR ]    at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)

[12/02/2017 17:05:55 > d747a0: ERR ]    at System.Threading.ThreadHelper.ThreadStart()

[12/02/2017 17:05:55 > d747a0: SYS ERR ] Job failed due to exit code -532462766

[12/02/2017 17:05:55 > d747a0: SYS INFO] Process went down, waiting for 60 seconds

[12/02/2017 17:05:55 > d747a0: SYS INFO] Status changed to PendingRestart
</code>```

答: I see that you're getting an exception trying to open a Socket to talk to Windows Storage. I'm guessing that the intermittent problem you're experiencing is due to hitting up against the outbound connection limit for an Azure Web App. To fix this, try scaling up to a higher plan. </p>

Body:
We have an Azure Web Job that runs (with [Singleton] attribute) and it occasionally complains about not being able to connect to the storage account that it needs to aquire the lock or when we try to log to storage account.

In the web job logs, it will result in "Invalid storage account XXXXXX. Please make sure your credentials are correct."

I have double-checked the access keys for the storage account, and the values in the hosting Azure Service's connection strings for the AzureWebJobsStorage and AzureWebJobsDashboard and also for our own application setting that we use when trying to create a CloudTableClient for logging.

This is intermittent, and works about 80% of the time, and 20% time it complains.

Sample from logs:

    [12/02/2017 16:45:10 > d747a0: INFO] Singleton lock acquired (5d3cc9c4e92841579c4df47db66e5bfc/CHO.WebJobs.csRfid.GPOFunctions.ProcessQueueMessage)

[12/02/2017 16:45:10 > d747a0: INFO] 12/2/2017 4:45:10 PM - Rfid processing started for Message Id 3286783.

[12/02/2017 16:45:13 > d747a0: INFO] Microsoft.ServiceBus.Messaging.BrokeredMessage{MessageId:3286783}

[12/02/2017 16:45:13 > d747a0: INFO] 12/2/2017 4:45:13 PM - Rfid processing finished for Message Id 3286783.

[12/02/2017 16:45:13 > d747a0: INFO] Singleton lock released (5d3cc9c4e92841579c4df47db66e5bfc/CHO.WebJobs.csRfid.GPOFunctions.ProcessQueueMessage)

[12/02/2017 16:45:13 > d747a0: INFO] Executed 'GPOFunctions.ProcessQueueMessage' (Succeeded, Id=aa430942-4fcb-4fa6-a899-fe936a183494)

[12/02/2017 16:45:13 > d747a0: INFO] Executing 'GPOFunctions.ProcessQueueMessage' (Reason='New ServiceBus message detected on 'tprfid/Subscriptions/subRfidUat'.', Id=c6eb4e56-ebd0-4410-acde-4e3bd7c3666d)

[12/02/2017 16:45:13 > d747a0: INFO] Singleton lock acquired (5d3cc9c4e92841579c4df47db66e5bfc/CHO.WebJobs.csRfid.GPOFunctions.ProcessQueueMessage)

[12/02/2017 16:45:13 > d747a0: INFO] 12/2/2017 4:45:13 PM - Rfid processing started for Message Id 3286784.

[12/02/2017 16:45:16 > d747a0: INFO] Microsoft.ServiceBus.Messaging.BrokeredMessage{MessageId:3286784}

[12/02/2017 16:45:16 > d747a0: WARN] Reached maximum allowed output lines for this run, to see all of the job's logs you can enable website application diagnostics

[12/02/2017 16:55:03 > d747a0: SYS ERR ] Job failed due to exit code -532462766

[12/02/2017 16:55:03 > d747a0: SYS INFO] Process went down, waiting for 0 seconds

[12/02/2017 16:55:03 > d747a0: SYS INFO] Status changed to PendingRestart

[12/02/2017 16:55:03 > d747a0: SYS INFO] Run script 'CHO.WebJobs.csRfid.exe' with script host - 'WindowsScriptHost'

[12/02/2017 16:55:03 > d747a0: SYS INFO] Status changed to Running

[12/02/2017 16:55:11 > d747a0: INFO] Found the following functions:

[12/02/2017 16:55:11 > d747a0: INFO] CHO.WebJobs.csRfid.GPOFunctions.ProcessQueueMessage

[12/02/2017 16:55:11 > d747a0: INFO] CHO.WebJobs.csRfid.GPOFunctions.ProcessTimer

[12/02/2017 16:55:12 > d747a0: INFO] Singleton lock acquired (5d3cc9c4e92841579c4df47db66e5bfc/CHO.WebJobs.csRfid.GPOFunctions.ProcessTimer.Listener)

[12/02/2017 16:55:12 > d747a0: INFO] Executing 'GPOFunctions.ProcessQueueMessage' (Reason='New ServiceBus message detected on 'tprfid/Subscriptions/subRfidUat'.', Id=ac2385b9-2000-4533-9166-57df9fef904f)

[12/02/2017 16:55:12 > d747a0: INFO] Singleton lock acquired (5d3cc9c4e92841579c4df47db66e5bfc/CHO.WebJobs.csRfid.GPOFunctions.ProcessQueueMessage)

[12/02/2017 16:55:13 > d747a0: INFO] 12/2/2017 4:55:13 PM - Rfid processing started for Message Id 3286815.

[12/02/2017 16:55:42 > d747a0: ERR ]

[12/02/2017 16:55:42 > d747a0: ERR ] Unhandled Exception: Microsoft.WindowsAzure.Storage.StorageException: Unable to connect to the remote server ---> System.Net.WebException: Unable to connect to the remote server ---> System.Net.Sockets.SocketException: An attempt was made to access a socket in a way forbidden by its access permissions

[12/02/2017 16:55:42 > d747a0: ERR ]    at System.Net.Sockets.Socket.DoBind(EndPoint endPointSnapshot, SocketAddress socketAddress)

[12/02/2017 16:55:42 > d747a0: ERR ]    at System.Net.Sockets.Socket.InternalBind(EndPoint localEP)

[12/02/2017 16:55:42 > d747a0: ERR ]    at System.Net.Sockets.Socket.BeginConnectEx(EndPoint remoteEP, Boolean flowContext, AsyncCallback callback, Object state)

[12/02/2017 16:55:42 > d747a0: ERR ]    at System.Net.Sockets.Socket.UnsafeBeginConnect(EndPoint remoteEP, AsyncCallback callback, Object state)

[12/02/2017 16:55:42 > d747a0: ERR ]    at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Exception& exception)

[12/02/2017 16:55:42 > d747a0: ERR ]    --- End of inner exception stack trace ---

[12/02/2017 16:55:42 > d747a0: ERR ]    at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)

[12/02/2017 16:55:42 > d747a0: ERR ]    at Microsoft.WindowsAzure.Storage.Core.Executor.Executor.EndGetResponse[T](IAsyncResult getResponseResult) in c:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\ClassLibraryCommon\Core\Executor\Executor.cs:line 284

[12/02/2017 16:55:42 > d747a0: ERR ]    --- End of inner exception stack trace ---

[12/02/2017 16:55:42 > d747a0: ERR ]    at Microsoft.WindowsAzure.Storage.Core.Executor.Executor.EndExecuteAsync[T](IAsyncResult result) in c:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\ClassLibraryCommon\Core\Executor\Executor.cs:line 50

[12/02/2017 16:55:42 > d747a0: ERR ]    at Microsoft.WindowsAzure.Storage.Queue.CloudQueue.EndExists(IAsyncResult asyncResult) in c:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\ClassLibraryCommon\Queue\CloudQueue.cs:line 994

[12/02/2017 16:55:42 > d747a0: ERR ]    at Microsoft.WindowsAzure.Storage.Core.Util.AsyncExtensions.<>c__DisplayClass1`1.<CreateCallback>b__0(IAsyncResult ar) in c:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\ClassLibraryCommon\Core\Util\AsyncExtensions.cs:line 66

[12/02/2017 16:55:42 > d747a0: ERR ] --- End of stack trace from previous location where exception was thrown ---

[12/02/2017 16:55:42 > d747a0: ERR ]    at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)

[12/02/2017 16:55:42 > d747a0: ERR ]    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

[12/02/2017 16:55:42 > d747a0: ERR ]    at Microsoft.Azure.WebJobs.Host.Queues.Listeners.QueueListener.<ExecuteAsync>d__21.MoveNext()

[12/02/2017 16:55:42 > d747a0: ERR ] --- End of stack trace from previous location where exception was thrown ---

[12/02/2017 16:55:42 > d747a0: ERR ]    at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)

[12/02/2017 16:55:42 > d747a0: ERR ]    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

[12/02/2017 16:55:42 > d747a0: ERR ]    at Microsoft.Azure.WebJobs.Host.Timers.TaskSeriesTimer.<RunAsync>d__14.MoveNext()

[12/02/2017 16:55:42 > d747a0: ERR ] --- End of stack trace from previous location where exception was thrown ---

[12/02/2017 16:55:42 > d747a0: ERR ]    at Microsoft.Azure.WebJobs.Host.Timers.WebJobsExceptionHandler.<>c__DisplayClass3_0.<OnUnhandledExceptionAsync>b__0()

[12/02/2017 16:55:42 > d747a0: ERR ]    at System.Threading.ThreadHelper.ThreadStart_Context(Object state)

[12/02/2017 16:55:42 > d747a0: ERR ]    at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)

[12/02/2017 16:55:42 > d747a0: ERR ]    at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)

[12/02/2017 16:55:42 > d747a0: ERR ]    at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)

[12/02/2017 16:55:42 > d747a0: ERR ]    at System.Threading.ThreadHelper.ThreadStart()

[12/02/2017 16:55:42 > d747a0: SYS ERR ] Job failed due to exit code -532462766

[12/02/2017 16:55:42 > d747a0: SYS INFO] Process went down, waiting for 60 seconds

[12/02/2017 16:55:42 > d747a0: SYS INFO] Status changed to PendingRestart

[12/02/2017 17:03:44 > d747a0: SYS INFO] Run script 'CHO.WebJobs.csRfid.exe' with script host - 'WindowsScriptHost'

[12/02/2017 17:03:44 > d747a0: SYS INFO] Status changed to Running

[12/02/2017 17:04:13 > d747a0: ERR ]

[12/02/2017 17:04:13 > d747a0: ERR ] Unhandled Exception: System.InvalidOperationException: Invalid storage account 'sachouat'. Please make sure your credentials are correct.

[12/02/2017 17:04:13 > d747a0: ERR ]    at Microsoft.Azure.WebJobs.Host.Executors.DefaultStorageCredentialsValidator.<ValidateCredentialsAsyncCore>d__2.MoveNext()

[12/02/2017 17:04:13 > d747a0: ERR ] --- End of stack trace from previous location where exception was thrown ---

[12/02/2017 17:04:13 > d747a0: ERR ]    at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)

[12/02/2017 17:04:13 > d747a0: ERR ]    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

[12/02/2017 17:04:13 > d747a0: ERR ]    at Microsoft.Azure.WebJobs.Host.Executors.DefaultStorageCredentialsValidator.<ValidateCredentialsAsync>d__1.MoveNext()

[12/02/2017 17:04:13 > d747a0: ERR ] --- End of stack trace from previous location where exception was thrown ---

[12/02/2017 17:04:13 > d747a0: ERR ]    at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)

[12/02/2017 17:04:13 > d747a0: ERR ]    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

[12/02/2017 17:04:13 > d747a0: ERR ]    at Microsoft.Azure.WebJobs.Host.Executors.DefaultStorageAccountProvider.<TryGetAccountAsync>d__23.MoveNext()

[12/02/2017 17:04:13 > d747a0: ERR ] --- End of stack trace from previous location where exception was thrown ---

[12/02/2017 17:04:13 > d747a0: ERR ]    at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)

[12/02/2017 17:04:13 > d747a0: ERR ]    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

[12/02/2017 17:04:13 > d747a0: ERR ]    at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)

[12/02/2017 17:04:13 > d747a0: ERR ]    at Microsoft.Azure.WebJobs.Host.Executors.JobHostContextFactory.<CreateAndLogHostStartedAsync>d__5.MoveNext()

[12/02/2017 17:04:13 > d747a0: ERR ] --- End of stack trace from previous location where exception was thrown ---

[12/02/2017 17:04:13 > d747a0: ERR ]    at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)

[12/02/2017 17:04:13 > d747a0: ERR ]    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

[12/02/2017 17:04:13 > d747a0: ERR ]    at Microsoft.Azure.WebJobs.Host.Executors.JobHostContextFactory.<CreateAndLogHostStartedAsync>d__4.MoveNext()

[12/02/2017 17:04:13 > d747a0: ERR ] --- End of stack trace from previous location where exception was thrown ---

[12/02/2017 17:04:13 > d747a0: ERR ]    at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)

[12/02/2017 17:04:13 > d747a0: ERR ]    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

[12/02/2017 17:04:13 > d747a0: ERR ]    at Microsoft.Azure.WebJobs.JobHost.<CreateContextAndLogHostStartedAsync>d__44.MoveNext()

[12/02/2017 17:04:13 > d747a0: ERR ] --- End of stack trace from previous location where exception was thrown ---

[12/02/2017 17:04:13 > d747a0: ERR ]    at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)

[12/02/2017 17:04:13 > d747a0: ERR ]    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

[12/02/2017 17:04:13 > d747a0: ERR ]    at Microsoft.Azure.WebJobs.JobHost.<StartAsyncCore>d__27.MoveNext()

[12/02/2017 17:04:13 > d747a0: ERR ] --- End of stack trace from previous location where exception was thrown ---

[12/02/2017 17:04:13 > d747a0: ERR ]    at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)

[12/02/2017 17:04:13 > d747a0: ERR ]    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

[12/02/2017 17:04:13 > d747a0: ERR ]    at Microsoft.Azure.WebJobs.JobHost.Start()

[12/02/2017 17:04:13 > d747a0: ERR ]    at Microsoft.Azure.WebJobs.JobHost.RunAndBlock()

[12/02/2017 17:04:13 > d747a0: ERR ]    at CHO.WebJobs.csRfid.ProcessRfidXml.StartListening() in F:\agent\_work\4\s\CHO.WebJobs\CHO.WebJobs.csRfid\ProcessRfidXml.cs:line 68

[12/02/2017 17:04:13 > d747a0: ERR ]    at CHO.WebJobs.csRfid.Program.Main() in F:\agent\_work\4\s\CHO.WebJobs\CHO.WebJobs.csRfid\Program.cs:line 98

[12/02/2017 17:04:13 > d747a0: SYS ERR ] Job failed due to exit code -532462766

[12/02/2017 17:04:13 > d747a0: SYS INFO] Process went down, waiting for 60 seconds

[12/02/2017 17:04:13 > d747a0: SYS INFO] Status changed to PendingRestart

[12/02/2017 17:05:14 > d747a0: SYS INFO] Run script 'CHO.WebJobs.csRfid.exe' with script host - 'WindowsScriptHost'

[12/02/2017 17:05:14 > d747a0: SYS INFO] Status changed to Running

[12/02/2017 17:05:28 > d747a0: INFO] Found the following functions:

[12/02/2017 17:05:28 > d747a0: INFO] CHO.WebJobs.csRfid.GPOFunctions.ProcessQueueMessage

[12/02/2017 17:05:28 > d747a0: INFO] CHO.WebJobs.csRfid.GPOFunctions.ProcessTimer

[12/02/2017 17:05:29 > d747a0: INFO] Singleton lock acquired (5d3cc9c4e92841579c4df47db66e5bfc/CHO.WebJobs.csRfid.GPOFunctions.ProcessTimer.Listener)

[12/02/2017 17:05:29 > d747a0: INFO] Function 'CHO.WebJobs.csRfid.GPOFunctions.ProcessTimer' initial status: Last='2017-12-02T16:54:06.7331501+00:00', Next='2017-12-02T16:55:06.7331501+00:00'

[12/02/2017 17:05:29 > d747a0: INFO] Function 'CHO.WebJobs.csRfid.GPOFunctions.ProcessTimer' is past due on startup. Executing now.

[12/02/2017 17:05:32 > d747a0: INFO] Executing 'GPOFunctions.ProcessQueueMessage' (Reason='New ServiceBus message detected on 'tprfid/Subscriptions/subRfidUat'.', Id=15bc1f92-4def-4ba2-ba96-5c2f510ee933)

[12/02/2017 17:05:32 > d747a0: INFO] Singleton lock acquired (5d3cc9c4e92841579c4df47db66e5bfc/CHO.WebJobs.csRfid.GPOFunctions.ProcessQueueMessage)

[12/02/2017 17:05:33 > d747a0: INFO] Executing 'GPOFunctions.ProcessTimer' (Reason='Timer fired at 2017-12-02T17:05:29.9786228+00:00', Id=3d6dc09b-82fb-41ae-a8d6-9d140af14945)

[12/02/2017 17:05:33 > d747a0: INFO] Singleton lock acquired (5d3cc9c4e92841579c4df47db66e5bfc/CHO.WebJobs.csRfid.GPOFunctions.ProcessTimer)

[12/02/2017 17:05:33 > d747a0: INFO] 12/2/2017 5:05:33 PM - Rfid processing started for Message Id 3286814.

[12/02/2017 17:05:55 > d747a0: ERR ]

[12/02/2017 17:05:55 > d747a0: ERR ] Unhandled Exception: Microsoft.WindowsAzure.Storage.StorageException: Unable to connect to the remote server ---> System.Net.WebException: Unable to connect to the remote server ---> System.Net.Sockets.SocketException: An attempt was made to access a socket in a way forbidden by its access permissions

[12/02/2017 17:05:55 > d747a0: ERR ]    at System.Net.Sockets.Socket.DoBind(EndPoint endPointSnapshot, SocketAddress socketAddress)

[12/02/2017 17:05:55 > d747a0: ERR ]    at System.Net.Sockets.Socket.InternalBind(EndPoint localEP)

[12/02/2017 17:05:55 > d747a0: ERR ]    at System.Net.Sockets.Socket.BeginConnectEx(EndPoint remoteEP, Boolean flowContext, AsyncCallback callback, Object state)

[12/02/2017 17:05:55 > d747a0: ERR ]    at System.Net.Sockets.Socket.UnsafeBeginConnect(EndPoint remoteEP, AsyncCallback callback, Object state)

[12/02/2017 17:05:55 > d747a0: ERR ]    at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Exception& exception)

[12/02/2017 17:05:55 > d747a0: ERR ]    --- End of inner exception stack trace ---

[12/02/2017 17:05:55 > d747a0: ERR ]    at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)

[12/02/2017 17:05:55 > d747a0: ERR ]    at Microsoft.WindowsAzure.Storage.Core.Executor.Executor.EndGetResponse[T](IAsyncResult getResponseResult) in c:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\ClassLibraryCommon\Core\Executor\Executor.cs:line 284

[12/02/2017 17:05:55 > d747a0: ERR ]    --- End of inner exception stack trace ---

[12/02/2017 17:05:55 > d747a0: ERR ]    at Microsoft.WindowsAzure.Storage.Core.Executor.Executor.EndExecuteAsync[T](IAsyncResult result) in c:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\ClassLibraryCommon\Core\Executor\Executor.cs:line 50

[12/02/2017 17:05:55 > d747a0: ERR ]    at Microsoft.WindowsAzure.Storage.Queue.CloudQueue.EndExists(IAsyncResult asyncResult) in c:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\ClassLibraryCommon\Queue\CloudQueue.cs:line 994

[12/02/2017 17:05:55 > d747a0: ERR ]    at Microsoft.WindowsAzure.Storage.Core.Util.AsyncExtensions.<>c__DisplayClass1`1.<CreateCallback>b__0(IAsyncResult ar) in c:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\ClassLibraryCommon\Core\Util\AsyncExtensions.cs:line 66

[12/02/2017 17:05:55 > d747a0: ERR ] --- End of stack trace from previous location where exception was thrown ---

[12/02/2017 17:05:55 > d747a0: ERR ]    at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)

[12/02/2017 17:05:55 > d747a0: ERR ]    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

[12/02/2017 17:05:55 > d747a0: ERR ]    at Microsoft.Azure.WebJobs.Host.Queues.Listeners.QueueListener.<ExecuteAsync>d__21.MoveNext()

[12/02/2017 17:05:55 > d747a0: ERR ] --- End of stack trace from previous location where exception was thrown ---

[12/02/2017 17:05:55 > d747a0: ERR ]    at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)

[12/02/2017 17:05:55 > d747a0: ERR ]    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

[12/02/2017 17:05:55 > d747a0: ERR ]    at Microsoft.Azure.WebJobs.Host.Timers.TaskSeriesTimer.<RunAsync>d__14.MoveNext()

[12/02/2017 17:05:55 > d747a0: ERR ] --- End of stack trace from previous location where exception was thrown ---

[12/02/2017 17:05:55 > d747a0: ERR ]    at Microsoft.Azure.WebJobs.Host.Timers.WebJobsExceptionHandler.<>c__DisplayClass3_0.<OnUnhandledExceptionAsync>b__0()

[12/02/2017 17:05:55 > d747a0: ERR ]    at System.Threading.ThreadHelper.ThreadStart_Context(Object state)

[12/02/2017 17:05:55 > d747a0: ERR ]    at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)

[12/02/2017 17:05:55 > d747a0: ERR ]    at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)

[12/02/2017 17:05:55 > d747a0: ERR ]    at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)

[12/02/2017 17:05:55 > d747a0: ERR ]    at System.Threading.ThreadHelper.ThreadStart()

[12/02/2017 17:05:55 > d747a0: SYS ERR ] Job failed due to exit code -532462766

[12/02/2017 17:05:55 > d747a0: SYS INFO] Process went down, waiting for 60 seconds

[12/02/2017 17:05:55 > d747a0: SYS INFO] Status changed to PendingRestart


来源: stackexchange

问:
How can I get a row count in DBI without running two separate calls to process?
I'm running DBI in Perl and can't figure out how, when I run a prepared statement, I can figure out if the returned row count is 0.

I realize I can set a counter inside my while loop where I fetch my rows, but I was hoping there was a less ugly way to do it.

答:
As others already said, you really need to get the rows to find out if there are any. If you need to know before starting a loop on every row, and if the expected results are not huge, you can get all results into an array, and then check that.

I recently used something like that:

```<code>foreach my $table ( qw(ACTOR DIRECTOR PRODUCER WRITER) ) {
    my $sth = $dbi->prepare(qq{SELECT * FROM $table WHERE DESCRIPTION != TRIM(DESCRIPTION)})
        or die $dbi->errstr;
    $sth->execute or die $sth->errstr;

    my @rows = @{ $sth->fetchall_arrayref() };

    next unless @rows;

    foreach my $row (@rows) {
        print join(", ", map {qq("$_")} @{$row}), "\n";
    }
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
As others already said, you really need to get the rows to find out if there are any. If you need to know before starting a loop on every row, and if the expected results are not huge, you can get all results into an array, and then check that.

I recently used something like that:

foreach my $table ( qw(ACTOR DIRECTOR PRODUCER WRITER) ) {
    my $sth = $dbi->prepare(qq{SELECT * FROM $table WHERE DESCRIPTION != TRIM(DESCRIPTION)})
        or die $dbi->errstr;
    $sth->execute or die $sth->errstr;

    my @rows = @{ $sth->fetchall_arrayref() };

    next unless @rows;

    foreach my $row (@rows) {
        print join(", ", map {qq("$_")} @{$row}), "\n";
    }
}

ContentLicense: CC BY-SA 3.0


问:
Advanced DateDiff using MSExcel
I have an Excel spreadsheet listing job shifts... four columns that are important for our purposes:

Start Date

Start Time

End Date

End Time

Given this data, I need to abstract the number of hours for each shift that fall between 7am and 7pm.

A few things to keep in mind...
There is no theoretical limit to the length of a shift.  It could run anywhere from 1 hour to 3 days.

I'm open to solutions in C#, VB, PHP, or even an advanced Excel function... anything to get to the solution.

答:
Thank you Remou
Very nice and workable.

I made a change to allow for parts of hours

```<code>Sub DayHours()
Dim i As Integer
Dim ShiftRange As Range
Dim dteStart As Date
Dim dteEnd As Date
Dim MinCount As Double

Set ShiftRange = Sheet1.UsedRange

For i = 3 To ShiftRange.Rows.Count
MinCount = 0
dteStart = CDate(Cells(i, 3) + Cells(i, 4))
dteEnd = CDate(Cells(i, 5) + Cells(i, 6))

Do While dteStart <= dteEnd
    If Format(dteStart, "hh:mm") >= #7:00:00 AM# And Format(dteStart, "hh:mm") < #7:00:00 PM# Then
        MinCount = MinCount + 1
    End If

    dteStart = DateAdd("n", 1, dteStart)
Loop
Cells(i, 10) = MinCount / 60
Next
End Sub
</code>```

Title: Advanced DateDiff using MSExcel

Body:
Thank you Remou
Very nice and workable.

I made a change to allow for parts of hours

Sub DayHours()
Dim i As Integer
Dim ShiftRange As Range
Dim dteStart As Date
Dim dteEnd As Date
Dim MinCount As Double

Set ShiftRange = Sheet1.UsedRange

For i = 3 To ShiftRange.Rows.Count
MinCount = 0
dteStart = CDate(Cells(i, 3) + Cells(i, 4))
dteEnd = CDate(Cells(i, 5) + Cells(i, 6))

Do While dteStart <= dteEnd
    If Format(dteStart, "hh:mm") >= #7:00:00 AM# And Format(dteStart, "hh:mm") < #7:00:00 PM# Then
        MinCount = MinCount + 1
    End If

    dteStart = DateAdd("n", 1, dteStart)
Loop
Cells(i, 10) = MinCount / 60
Next
End Sub


问:
Obtaining JSON data with foreach in PHP
A site contains monthly data in a JSON format. This can be queried like so:

```<code>http://www.example.com?startdate=1-1-1985&enddate=31-1-1985
</code>```

I want to be able to run a script that will obtain the specific data I am looking for, starting from today's month, then work backward until null data is returned. Each month's value needs to add up. So far, this is what I've got:

```<code>//Build base URL:
$userid=$_GET['userid'];
$startdate=/*Beginning of today's month*/;
$enddate=/*End of today's month*/;
$url='http://www.example.com?userid='.$userid.'&startdate='.$startdate.'&enddate='.$enddate;

//Set JSON variables:
$get=file_get_contents($url);
$json=json_decode($get);

//Set loop variables:
$value=0;
$month=0;

/*For each month from today backwards{
    $number=$json->integer;
    if($number!=null){
        $value=$value+$number;
        $month=$month+1;
    }else{
        break;
    }
}
echo $value;
echo $month;
*/
</code>```

The part I'm having problems with is the beginning of the fourth part. How do I run a loop that starts with the range of today's month, obtain $number, then repeat with the previous month, until it reaches a month that returns null?

答:
By using strtotime() and mktime() functions you can while loop until you get Null results. The below code will print 5 urls for 5 months. Change while condition accordingly.

```<code>// define $i
$i=0;
$userid = '343';//$_GET['userid'];  //dont forget to replace with userid
do{
    $timestring =  strtotime("now -$i month");
    //get Month
    $month = date('m',$timestring);
    //get Year
    $year = date('Y',$timestring);
    // First date Month and Year
    $startdate = date('d-m-Y', mktime(0, 0, 0, $month, 1, $year));
    // Last date Month and Year
    $enddate = date('d-m-Y', mktime(0, 0, 0, $month+1, 0,$year));

    $url='http://www.example.com?userid='.$userid.'&startdate='.$startdate.'&enddate='.$enddate;
    // commenting your code
    //Set JSON variables:
    //$get=file_get_contents($url);
    //$json=json_decode($get);
    // $number=$json->integer;
    echo $url;
    echo "\n";
    $i++;
}while ($i!=5); // change while condition according to your requirement. while ($number!=null)
</code>```

Out Put:

```<code>http://www.example.com?userid=343&startdate=01-12-2017&enddate=31-12-2017
http://www.example.com?userid=343&startdate=01-11-2017&enddate=30-11-2017
http://www.example.com?userid=343&startdate=01-10-2017&enddate=31-10-2017
http://www.example.com?userid=343&startdate=01-09-2017&enddate=30-09-2017
http://www.example.com?userid=343&startdate=01-08-2017&enddate=31-08-2017
</code>```

Title: Obtaining JSON data with foreach in PHP

Body:
A site contains monthly data in a JSON format. This can be queried like so:

http://www.example.com?startdate=1-1-1985&enddate=31-1-1985

I want to be able to run a script that will obtain the specific data I am looking for, starting from today's month, then work backward until null data is returned. Each month's value needs to add up. So far, this is what I've got:

//Build base URL:
$userid=$_GET['userid'];
$startdate=/*Beginning of today's month*/;
$enddate=/*End of today's month*/;
$url='http://www.example.com?userid='.$userid.'&startdate='.$startdate.'&enddate='.$enddate;

//Set JSON variables:
$get=file_get_contents($url);
$json=json_decode($get);

//Set loop variables:
$value=0;
$month=0;

/*For each month from today backwards{
    $number=$json->integer;
    if($number!=null){
        $value=$value+$number;
        $month=$month+1;
    }else{
        break;
    }
}
echo $value;
echo $month;
*/

The part I'm having problems with is the beginning of the fourth part. How do I run a loop that starts with the range of today's month, obtain $number, then repeat with the previous month, until it reaches a month that returns null?

Body:
By using strtotime() and mktime() functions you can while loop until you get Null results. The below code will print 5 urls for 5 months. Change while condition accordingly.

// define $i
$i=0;
$userid = '343';//$_GET['userid'];  //dont forget to replace with userid
do{
    $timestring =  strtotime("now -$i month");
    //get Month
    $month = date('m',$timestring);
    //get Year
    $year = date('Y',$timestring);
    // First date Month and Year
    $startdate = date('d-m-Y', mktime(0, 0, 0, $month, 1, $year));
    // Last date Month and Year
    $enddate = date('d-m-Y', mktime(0, 0, 0, $month+1, 0,$year));

    $url='http://www.example.com?userid='.$userid.'&startdate='.$startdate.'&enddate='.$enddate;
    // commenting your code
    //Set JSON variables:
    //$get=file_get_contents($url);
    //$json=json_decode($get);
    // $number=$json->integer;
    echo $url;
    echo "\n";
    $i++;
}while ($i!=5); // change while condition according to your requirement. while ($number!=null)

Out Put:

http://www.example.com?userid=343&startdate=01-12-2017&enddate=31-12-2017
http://www.example.com?userid=343&startdate=01-11-2017&enddate=30-11-2017
http://www.example.com?userid=343&startdate=01-10-2017&enddate=31-10-2017
http://www.example.com?userid=343&startdate=01-09-2017&enddate=30-09-2017
http://www.example.com?userid=343&startdate=01-08-2017&enddate=31-08-2017


问:
how to call method inside class using MooseX::Declare
here "info_vcf" is a class where "info_vcf_function" is a method. "getValueFromInfoColum" and "getValueFromFormatColum" both are method which are present inside the "info_vcf_function" method.
now i want to call "getValueFromInfoColum" and "getValueFromFormatColum" both method from inside "info_vcf_function" method. how to do this ?

it gives me error " Validation failed for 'Tuple[Tuple[Object,Any],Dict[]]' with value "[ [ info_vcf=HASH(0x1ac7fd0), info_vcf=HASH(0x1ac7fd0), "anop" ], {  } ], Internal Validation Error is: \n [+] Valida
tion failed for 'Tuple[Object,Any]' with value "[ info_vcf={  }, info_vcf={  }, "anop" ]"\n  [+] More values than Type Constraints!" at /usr/local/share/perl/5.22.1/MooseX/Method/Signat
ures/Meta/Method.pm line 432.
        MooseX::Method::Signatures::Meta::Method::validate(MooseX::Method::Signatures::Meta::Method=HASH(0x3bd0e60), ARRAY(0x3154e80)) called at /usr/local/share/perl/5.22.1/MooseX/Meth
od/Signatures/Meta/Method.pm line 148
        info_vcf::info_vcf_function(info_vcf=HASH(0x1ac7fd0), info_vcf=HASH(0x1ac7fd0), "anop") called at testone.pl line 24 "

```<code>#!/usr/bin/perl -w
use MooseX::Declare;

class info_vcf {

    method info_vcf_function($selectedVariant) {

        print "$selectedVariant";
        getValueFromInfoColum("singh");
        getValueFromFormatColum("ranawat");

    }
        method getValueFromInfoColum($flag){
            print "$flag\n";
        }
        method getValueFromFormatColum($flag){
            print "$flag\n";
        }

}
1;

my $object = info_vcf->new();
$object->info_vcf_function("anop");
</code>```

答:
Some confusion here. I'm not sure what you think this two lines are doing:

```<code>getValueFromInfoColum("singh");
getValueFromFormatColum("ranawat");
</code>```

These are methods inside your class and need to be called on an object, i.e. like $some_object->getValueFromInfoColumn($string). You can't just call them without an object (update: well, strictly, without an object or a class) as you do in this example. And why would you call them from within the class definition anyway?

With those two lines commented out, your code works as expected (although, it's more common for the class definition and the code that uses the class to be in separate files). But until you explain more about what you think those calls are doing, it's hard to give better advice than "remove the two broken lines".

Update: Also, note that class names in all lower case are reserved for pragmata - that is classes that change the behaviour of the Perl compiler simply by being loaded. Your class is not one of these, so you shouldn't use an all-lowercase name for it.

Update 2: Now you have added this to the question:

now i want to call "getValueFromInfoColum" and "getValueFromFormatColum" both method from inside "info_vcf_function" method. how to do this ?

That's simple. You call a method on a particular object. Inside a method, the current object will be in the $self variable. So I think you want this:

```<code>#!/usr/bin/perl -w
use MooseX::Declare;

class info_vcf {

    method info_vcf_function($selectedVariant) {
        print "$selectedVariant";
        $self->getValueFromInfoColum("singh");
        $self->getValueFromFormatColum("ranawat");
    }

    method getValueFromInfoColum($flag){
        print "$flag\n";
    }

    method getValueFromFormatColum($flag){
        print "$flag\n";
    }
}
1;

my $object = info_vcf->new();
$object->info_vcf_function("anop");
</code>```

As I said in a comment, MooseX::Declare is deprecated. That means you shouldn't be using it for new code. The documentation recommends using Moops instead.

Body:
here "info_vcf" is a class where "info_vcf_function" is a method. "getValueFromInfoColum" and "getValueFromFormatColum" both are method which are present inside the "info_vcf_function" method.
now i want to call "getValueFromInfoColum" and "getValueFromFormatColum" both method from inside "info_vcf_function" method. how to do this ?

it gives me error " Validation failed for 'Tuple[Tuple[Object,Any],Dict[]]' with value "[ [ info_vcf=HASH(0x1ac7fd0), info_vcf=HASH(0x1ac7fd0), "anop" ], {  } ], Internal Validation Error is: \n [+] Valida
tion failed for 'Tuple[Object,Any]' with value "[ info_vcf={  }, info_vcf={  }, "anop" ]"\n  [+] More values than Type Constraints!" at /usr/local/share/perl/5.22.1/MooseX/Method/Signat
ures/Meta/Method.pm line 432.
        MooseX::Method::Signatures::Meta::Method::validate(MooseX::Method::Signatures::Meta::Method=HASH(0x3bd0e60), ARRAY(0x3154e80)) called at /usr/local/share/perl/5.22.1/MooseX/Meth
od/Signatures/Meta/Method.pm line 148
        info_vcf::info_vcf_function(info_vcf=HASH(0x1ac7fd0), info_vcf=HASH(0x1ac7fd0), "anop") called at testone.pl line 24 "

#!/usr/bin/perl -w
use MooseX::Declare;

class info_vcf {

    method info_vcf_function($selectedVariant) {

        print "$selectedVariant";
        getValueFromInfoColum("singh");
        getValueFromFormatColum("ranawat");

    }
        method getValueFromInfoColum($flag){
            print "$flag\n";
        }
        method getValueFromFormatColum($flag){
            print "$flag\n";
        }

}
1;

my $object = info_vcf->new();
$object->info_vcf_function("anop");

Body:
Some confusion here. I'm not sure what you think this two lines are doing:

getValueFromInfoColum("singh");
getValueFromFormatColum("ranawat");

These are methods inside your class and need to be called on an object, i.e. like $some_object->getValueFromInfoColumn($string). You can't just call them without an object (update: well, strictly, without an object or a class) as you do in this example. And why would you call them from within the class definition anyway?

With those two lines commented out, your code works as expected (although, it's more common for the class definition and the code that uses the class to be in separate files). But until you explain more about what you think those calls are doing, it's hard to give better advice than "remove the two broken lines".

Update: Also, note that class names in all lower case are reserved for pragmata - that is classes that change the behaviour of the Perl compiler simply by being loaded. Your class is not one of these, so you shouldn't use an all-lowercase name for it.

Update 2: Now you have added this to the question:

now i want to call "getValueFromInfoColum" and "getValueFromFormatColum" both method from inside "info_vcf_function" method. how to do this ?

That's simple. You call a method on a particular object. Inside a method, the current object will be in the $self variable. So I think you want this:

#!/usr/bin/perl -w
use MooseX::Declare;

class info_vcf {

    method info_vcf_function($selectedVariant) {
        print "$selectedVariant";
        $self->getValueFromInfoColum("singh");
        $self->getValueFromFormatColum("ranawat");
    }

    method getValueFromInfoColum($flag){
        print "$flag\n";
    }

    method getValueFromFormatColum($flag){
        print "$flag\n";
    }
}
1;

my $object = info_vcf->new();
$object->info_vcf_function("anop");

As I said in a comment, MooseX::Declare is deprecated. That means you shouldn't be using it for new code. The documentation recommends using Moops instead.


问:
removing Li if duplicate  tag found
Removing
 if duplicate  tag found (after trimming  for trailing space from url and text).

I am using seen but the duplicate is still showing. It looks like Dashboard is duplicating but the 2nd Dashboard has a trailing space in the link url and title.

var seen = {};
$('.nav-report-category a').each(function() {
  var txt = $(this).text();
  if (seen[txt]) $(this).closest("li").remove();
  else seen[txt] = true;
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.nav-report-category {
  border: none !important;
}

.nav-report-category li {
  font-size: 16px;
  padding: 10px 0px;
  width: 110px;
  display: inline-block;
  background-color: rgb(74, 137, 220);
  color: #fff!important;
  margin-right: 5px;
  text-align: center;
  -moz-border-radius: 9px 9px 0px 0px;
  -webkit-border-radius: 9px 9px 0px 0px;
  border-radius: 9px 9px 0px 0px;
  font-color: #fff!important;
}

.nav-report-category li.active {
  background-color: #CB6015!important;
  color: #fff!important;
}

.nav-report-category li a:visited {
  color: #fff!important;
}

.nav-report-category li a {
  color: #fff!important;
}

.nav-report-category li:Hover {
  background-color: #BE3A34;
  text-decoration: none;
}

.tab-desc {
  background-color: rgb(93, 156, 236);
  color: #fff !important;
  padding: 5px;
}

.tab-desc H2 {
  color: #fff !important;
}

#txt-Business-Function {
  font-family: "Segoe UI Light", "Segoe UI", "Segoe", Tahoma, Helvetica, Arial, sans-serif;
  color: #BE3A34;
  font-size: 22px;
  font-weight: bolder;
}</code>```

Inventory

Manufacturing

Metrics

Operational

Planning

Procurement

Sales Order

Dashboard

International Operations

Purchasing

Dashboard

Strategic Sourcing

```

答:
Working fiddle.

The main problem comes from the HTML entities you've with the text in your anchors, you must remove/replace them when retrieving the text, your second "Dashboard" text is in the fact Dashboard , so it will never match with Dashboard as key.

Remove them from your JS or remove them from you HTML code, e.g :

```<code>var txt = $(this).text().replace(/[^A-Z0-9]+/ig, "");
</code>```

NOTE 1: Use x.hasOwnProperty(y) to check if an object x has a property y, in your case :

```<code>if ( seen.hasOwnProperty( txt ) ){
</code>```

NOTE 2: As @MasterYoda's comment says Your
 elements should be children of either
 or
 not
.

var seen = {};
$('.nav-report-category a').each(function() {
  var txt = $(this).text().replace(/[^A-Z0-9]+/ig, "");

  if (seen.hasOwnProperty(txt)) {
    $(this).closest("li").remove();
  } else {
    seen[txt] = true;
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.nav-report-category {
  border: none !important;
}

.nav-report-category li {
  font-size: 16px;
  padding: 10px 0px;
  width: 110px;
  display: inline-block;
  background-color: rgb(74, 137, 220);
  color: #fff!important;
  margin-right: 5px;
  text-align: center;
  -moz-border-radius: 9px 9px 0px 0px;
  -webkit-border-radius: 9px 9px 0px 0px;
  border-radius: 9px 9px 0px 0px;
  font-color: #fff!important;
}

.nav-report-category li.active {
  background-color: #CB6015!important;
  color: #fff!important;
}

.nav-report-category li a:visited {
  color: #fff!important;
}

.nav-report-category li a {
  color: #fff!important;
}

.nav-report-category li:Hover {
  background-color: #BE3A34;
  text-decoration: none;
}

.tab-desc {
  background-color: rgb(93, 156, 236);
  color: #fff !important;
  padding: 5px;
}

.tab-desc H2 {
  color: #fff !important;
}

#txt-Business-Function {
  font-family: "Segoe UI Light", "Segoe UI", "Segoe", Tahoma, Helvetica, Arial, sans-serif;
  color: #BE3A34;
  font-size: 22px;
  font-weight: bolder;
}</code>```

Inventory

Manufacturing

Metrics

Operational

Planning

Procurement

Sales Order

Dashboard

International Operations

Purchasing

Dashboard

Strategic Sourcing

```

Title: removing Li if duplicate <a> tag found

Body:
Removing
 if duplicate  tag found (after trimming  for trailing space from url and text).

I am using seen but the duplicate is still showing. It looks like Dashboard is duplicating but the 2nd Dashboard has a trailing space in the link url and title.

var seen = {};
$('.nav-report-category a').each(function() {
  var txt = $(this).text();
  if (seen[txt]) $(this).closest("li").remove();
  else seen[txt] = true;
});

.nav-report-category {
  border: none !important;
}

.nav-report-category li {
  font-size: 16px;
  padding: 10px 0px;
  width: 110px;
  display: inline-block;
  background-color: rgb(74, 137, 220);
  color: #fff!important;
  margin-right: 5px;
  text-align: center;
  -moz-border-radius: 9px 9px 0px 0px;
  -webkit-border-radius: 9px 9px 0px 0px;
  border-radius: 9px 9px 0px 0px;
  font-color: #fff!important;
}

.nav-report-category li.active {
  background-color: #CB6015!important;
  color: #fff!important;
}

.nav-report-category li a:visited {
  color: #fff!important;
}

.nav-report-category li a {
  color: #fff!important;
}

.nav-report-category li:Hover {
  background-color: #BE3A34;
  text-decoration: none;
}

.tab-desc {
  background-color: rgb(93, 156, 236);
  color: #fff !important;
  padding: 5px;
}

.tab-desc H2 {
  color: #fff !important;
}

#txt-Business-Function {
  font-family: "Segoe UI Light", "Segoe UI", "Segoe", Tahoma, Helvetica, Arial, sans-serif;
  color: #BE3A34;
  font-size: 22px;
  font-weight: bolder;
}

Inventory

Manufacturing

Metrics

Operational

Planning

Procurement

Sales Order

Dashboard

International Operations

Purchasing

Dashboard

Strategic Sourcing

Body:
Working fiddle.

The main problem comes from the HTML entities you've with the text in your anchors, you must remove/replace them when retrieving the text, your second "Dashboard" text is in the fact Dashboard&nbsp;&lrm;, so it will never match with Dashboard as key.

Remove them from your JS or remove them from you HTML code, e.g :

var txt = $(this).text().replace(/[^A-Z0-9]+/ig, "");

NOTE 1: Use x.hasOwnProperty(y) to check if an object x has a property y, in your case :

if ( seen.hasOwnProperty( txt ) ){

NOTE 2: As @MasterYoda's comment says Your <li> elements should be children of either <ul> or <ol> not <div>.

var seen = {};
$('.nav-report-category a').each(function() {
  var txt = $(this).text().replace(/[^A-Z0-9]+/ig, "");

  if (seen.hasOwnProperty(txt)) {
    $(this).closest("li").remove();
  } else {
    seen[txt] = true;
  }
});

.nav-report-category {
  border: none !important;
}

.nav-report-category li {
  font-size: 16px;
  padding: 10px 0px;
  width: 110px;
  display: inline-block;
  background-color: rgb(74, 137, 220);
  color: #fff!important;
  margin-right: 5px;
  text-align: center;
  -moz-border-radius: 9px 9px 0px 0px;
  -webkit-border-radius: 9px 9px 0px 0px;
  border-radius: 9px 9px 0px 0px;
  font-color: #fff!important;
}

.nav-report-category li.active {
  background-color: #CB6015!important;
  color: #fff!important;
}

.nav-report-category li a:visited {
  color: #fff!important;
}

.nav-report-category li a {
  color: #fff!important;
}

.nav-report-category li:Hover {
  background-color: #BE3A34;
  text-decoration: none;
}

.tab-desc {
  background-color: rgb(93, 156, 236);
  color: #fff !important;
  padding: 5px;
}

.tab-desc H2 {
  color: #fff !important;
}

#txt-Business-Function {
  font-family: "Segoe UI Light", "Segoe UI", "Segoe", Tahoma, Helvetica, Arial, sans-serif;
  color: #BE3A34;
  font-size: 22px;
  font-weight: bolder;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="nav-report-category">
  <li><a href="https://myanalytix-beta.myexterran.com/Pages/AllReports.aspx?BF=Supply Chain&amp;RC=Inventory">Inventory</a></li>
  <li><a href="https://analytix.my.com/Pages/AllReports.aspx?BF=Supply Chain&amp;RC=Manufacturing">Manufacturing</a></li>
  <li><a href="https://analytix.my.com/Pages/AllReports.aspx?BF=Supply Chain&amp;RC=Metrics">Metrics</a></li>
  <li><a href="https://analytix.my.com/Pages/AllReports.aspx?BF=Supply Chain&amp;RC=Operational">Operational</a></li>
  <li><a href="https://analytix.my.com/Pages/AllReports.aspx?BF=Supply Chain&amp;RC=Planning">Planning</a></li>
  <li><a href="https://analytix.my.com/Pages/AllReports.aspx?BF=Supply Chain&amp;RC=Procurement">Procurement</a></li>
  <li><a href="https://analytix.my.com/Pages/AllReports.aspx?BF=Supply Chain&amp;RC=Sales Order">Sales Order</a></li>
  <li><a href="https://analytix.my.com/Pages/AllReports.aspx?BF=Supply Chain&amp;RC=Dashboard">Dashboard</a></li>
  <li><a href="https://analytix.my.com/Pages/AllReports.aspx?BF=Supply Chain&amp;RC=International Operations">International Operations</a></li>
  <li><a href="https://analytix.my.com/Pages/AllReports.aspx?BF=Supply Chain&amp;RC=Purchasing">Purchasing</a></li>
  <li><a href="https://analytix.my.com/Pages/AllReports.aspx?BF=Supply Chain&amp;RC=Dashboard&nbsp;">Dashboard&nbsp;</a></li>
  <li><a href="https://analytix.my.com/Pages/AllReports.aspx?BF=Supply Chain&amp;RC=Strategic Sourcing">Strategic Sourcing</a></li>
</div>


问:
trouble hooking in some jquery wordpress
I'm in the process of hooking in some JavaScript and jQuery to this WordPress but I need help with the last 10%. I've attached a script to the navbar so that it changes color with the scroll. when you scroll down, the navbar background turns white with black font and a box shadow. Then when you scroll up, the navbar background turns transparent, the font changes color to white and the box shadow disappears. The problem is that last part isn't happening. When I scroll up, the white background remains.

here's the jQuery:

```<code>var $j = jQuery.noConflict();

$j(document).ready(function(){
    var scroll_start = 0;
    var startchange = $j('.banner'); //this is where the transition starts. it starts at the banner
    var offset = startchange.offset();
    if (startchange.length){

        $j(document).scroll(function(){
            scroll_start = $j(this).scrollTop();
            if(scroll_start > offset.top) {
                $j(".navbar-default").css('background', 'white'); //this is the changing color
                $j(".navbar-brand").css('color', 'black'); //this is the changing font color
                $j(".navbar-dilly").css('color', 'black'); //this is the right side font color
                $j(".navbar-default").css('box-shadow', '0 2px 0 0 #000');
            } else {
                $j(".navbar-default").css('background', 'transparent'); // this is the starting color
                $j(".navbar-brand").css('color', 'white'); // this is the starting font color
                $j(".navbar-dilly").css('color', 'white'); // this is the right side font color
                $j(".navbar-default").css('box-shadow', 'none');
            }
        });
    }
});
</code>```

答:
I edited your code a little bit. All you've got to do is integrate the change in start. You issue was that you were setting scroll_start from 0 to another value.

```<code>var lastScrollTop = 0;
$j(window).scroll(function(event) {
    var st = $j(this).scrollTop();
    if (st > lastScrollTop) {
        $j(".navbar-default").css('background', 'white'); //this is the changing color
        $j(".navbar-brand").css('color', 'black'); //this is the changing font color
        $j(".navbar-dilly").css('color', 'black'); //this is the right side font color
        $j(".navbar-default").css('box-shadow', '0 2px 0 0 #000');
    } else {
        $j(".navbar-default").css('background', 'transparent'); // this is the starting color
        $j(".navbar-brand").css('color', 'white'); // this is the starting font color
        $j(".navbar-dilly").css('color', 'white'); // this is the right side font color
        $j(".navbar-default").css('box-shadow', 'none');
    }
    lastScrollTop = st;
});
</code>```

I have tested your code on the website and it works, except for the feature which you need to add in.

Source : How can I determine the direction of a jQuery scroll event?

Body:
I'm in the process of hooking in some JavaScript and jQuery to this WordPress but I need help with the last 10%. I've attached a script to the navbar so that it changes color with the scroll. when you scroll down, the navbar background turns white with black font and a box shadow. Then when you scroll up, the navbar background turns transparent, the font changes color to white and the box shadow disappears. The problem is that last part isn't happening. When I scroll up, the white background remains.

here's the jQuery:

var $j = jQuery.noConflict();

$j(document).ready(function(){
    var scroll_start = 0;
    var startchange = $j('.banner'); //this is where the transition starts. it starts at the banner
    var offset = startchange.offset();
    if (startchange.length){

        $j(document).scroll(function(){
            scroll_start = $j(this).scrollTop();
            if(scroll_start > offset.top) {
                $j(".navbar-default").css('background', 'white'); //this is the changing color
                $j(".navbar-brand").css('color', 'black'); //this is the changing font color
                $j(".navbar-dilly").css('color', 'black'); //this is the right side font color
                $j(".navbar-default").css('box-shadow', '0 2px 0 0 #000');
            } else {
                $j(".navbar-default").css('background', 'transparent'); // this is the starting color
                $j(".navbar-brand").css('color', 'white'); // this is the starting font color
                $j(".navbar-dilly").css('color', 'white'); // this is the right side font color
                $j(".navbar-default").css('box-shadow', 'none');
            }
        });
    }
});

Body:
I edited your code a little bit. All you've got to do is integrate the change in start. You issue was that you were setting scroll_start from 0 to another value.

var lastScrollTop = 0;
$j(window).scroll(function(event) {
    var st = $j(this).scrollTop();
    if (st > lastScrollTop) {
        $j(".navbar-default").css('background', 'white'); //this is the changing color
        $j(".navbar-brand").css('color', 'black'); //this is the changing font color
        $j(".navbar-dilly").css('color', 'black'); //this is the right side font color
        $j(".navbar-default").css('box-shadow', '0 2px 0 0 #000');
    } else {
        $j(".navbar-default").css('background', 'transparent'); // this is the starting color
        $j(".navbar-brand").css('color', 'white'); // this is the starting font color
        $j(".navbar-dilly").css('color', 'white'); // this is the right side font color
        $j(".navbar-default").css('box-shadow', 'none');
    }
    lastScrollTop = st;
});

I have tested your code on the website and it works, except for the feature which you need to add in.

Source : How can I determine the direction of a jQuery scroll event?


问:
How to compare through complete JSON and bind it to another JSON

I have a JSON which looks like this:-

```<code>{
    "property" : value,
    "property" : value,
    "subProperty" : {
        "subProperty1" : {
            "subProperty1a" : {
                "property" : value,
                "property" : value
            },
            "subProperty1b" : {
                "property" : ["1", "2"],
                "property" : value
            },
            .....
        },
        "subProperty2" : {
            "subProperty2a" : {
                "property" : value,
                "property" : value
            },
            "subProperty2b" : {
                "property" : value,
                "property" : value
            },
            .....
        },
        "subProperty3" : {
            "subProperty3a" : {
                "property" : value,
                "property" : value
            },
            "subProperty3b" : {
                "property" : value,
                "property" : value
            },
            .....
        }
    }
}
</code>```

This JSON can have any number of fields added later on in any position.What I want is when I add new fields, then I want to compare old JSON with new JSON. If any propert is missing, bind that property with new one.

Right now I am using following code to achieve this:-

```<code>    scope.tempObj = {};
    scope.findObjectByLabel = function(obj1, obj2, obj3){
                        for(var i in obj1)
                            {
                                obj3[i] = obj2[i];
                                if(obj2[i] == undefined)
                                {
                                    obj3[i] = obj1[i];
                                }
                                if(typeof(obj1[i]) == 'object')
                                {
                                    scope.findObjectByLabel(obj1[i], obj2[i],obj3[i]);
                                }
                            }
                            return obj3;
                    }

scope.newJSON = scope.findObjectByLabel(scope.newJSON, scope.oldJSON ,scope.tempObj);
</code>```

But the above code can only compare through one level. Can any one suggest me any improvement on the above code so that it can compare through entire JSON.

答:
To merge two object try like below.

```<code>function merge(oldObj, newObj){
   for (var prop in newObj) {
     if(typeof newObj[prop] === 'object'){
            merge(oldObj[prop], newObj[prop]);
     }

     if(typeof newObj[prop] !== 'object')
        oldObj[prop] = newObj[prop];
    }
    return oldObj
}

console.log(merge(oldObj, newObj, oldObjTemp));
</code>```

https://jsfiddle.net/8n244fmb/2/

To find the missing properties and values in multiple level.

```<code>var oldObj = {
     "name": "Bob Odenkirk",
     "title": "Software Engineer",
     "location": {
         "locality": "San Francisco",
         "region": "CA",
         "country": "United States"
     },
     "age": 62,
     "status": "Active"
};
var newObj = {
     "name": "Bob Odenkirk",
     "title": "Software Engineer",
     "location": {
         "locality": "San Francisco",
         "country": "United States"
     },
     "age": 62,
     "company": "Accenture"
};

var missingProps = {};

function getMissingProps(oldObj, newObj){
     for (var prop in oldObj) {
     if(newObj.hasOwnProperty(prop) && typeof oldObj[prop] === 'object')
       missingProps = getMissingProps(oldObj[prop], newObj[prop]);
     else if(!newObj.hasOwnProperty(prop))
         missingProps[prop] =  oldObj[prop] ;
   }

   return missingProps;
}

console.log(getMissingProps(oldObj, newObj));
</code>```

https://jsfiddle.net/8n244fmb/

if you want complete missing Json props structure try this

```<code>var oldObj = oldObjTemp = {
     "name": "Bob Odenkirk",
     "title": "Software Engineer",
     "location": {
         "locality": "San Francisco",
         "region": "CA",
         "country": {"name" : "United States", "code":"US"}
     },
     "age": 62,
     "status": "Active"
};
var newObj = {
     "name": "Bob Odenkirk",
     "title": "Software Engineer",
     "location": {
         "locality": "San Francisco",
         "country": {"name" : "United States"}
     },
     "age": 62,
     "company": "Accenture"
};

var missingProps = {};

function getMissingProps(oldObj, newObj, oldObjTemp){
   for (var prop in oldObj) {
     if(newObj.hasOwnProperty(prop) && typeof oldObj[prop] === 'object'){
            getMissingProps(oldObj[prop], newObj[prop], oldObjTemp[prop]);
     }
     else if(newObj.hasOwnProperty(prop)){
            delete oldObjTemp[prop];
     }
    }
}

getMissingProps(oldObj, newObj, oldObjTemp);

console.log(oldObjTemp);
</code>```

https://jsfiddle.net/8n244fmb/1/

Body:
I have a JSON which looks like this:-

{
    "property" : value,
    "property" : value,
    "subProperty" : {
        "subProperty1" : {
            "subProperty1a" : {
                "property" : value,
                "property" : value
            },
            "subProperty1b" : {
                "property" : ["1", "2"],
                "property" : value
            },
            .....
        },
        "subProperty2" : {
            "subProperty2a" : {
                "property" : value,
                "property" : value
            },
            "subProperty2b" : {
                "property" : value,
                "property" : value
            },
            .....
        },
        "subProperty3" : {
            "subProperty3a" : {
                "property" : value,
                "property" : value
            },
            "subProperty3b" : {
                "property" : value,
                "property" : value
            },
            .....
        }
    }
}

This JSON can have any number of fields added later on in any position.What I want is when I add new fields, then I want to compare old JSON with new JSON. If any propert is missing, bind that property with new one.

Right now I am using following code to achieve this:-

    scope.tempObj = {};
    scope.findObjectByLabel = function(obj1, obj2, obj3){
                        for(var i in obj1)
                            {
                                obj3[i] = obj2[i];
                                if(obj2[i] == undefined)
                                {
                                    obj3[i] = obj1[i];
                                }
                                if(typeof(obj1[i]) == 'object')
                                {
                                    scope.findObjectByLabel(obj1[i], obj2[i],obj3[i]);
                                }
                            }
                            return obj3;
                    }

scope.newJSON = scope.findObjectByLabel(scope.newJSON, scope.oldJSON ,scope.tempObj);

But the above code can only compare through one level. Can any one suggest me any improvement on the above code so that it can compare through entire JSON.

Body:
To merge two object try like below.

function merge(oldObj, newObj){
   for (var prop in newObj) {
     if(typeof newObj[prop] === 'object'){
            merge(oldObj[prop], newObj[prop]);
     }

     if(typeof newObj[prop] !== 'object')
        oldObj[prop] = newObj[prop];
    }
    return oldObj
}

console.log(merge(oldObj, newObj, oldObjTemp));

https://jsfiddle.net/8n244fmb/2/

To find the missing properties and values in multiple level.

var oldObj = {
     "name": "Bob Odenkirk",
     "title": "Software Engineer",
     "location": {
         "locality": "San Francisco",
         "region": "CA",
         "country": "United States"
     },
     "age": 62,
     "status": "Active"
};
var newObj = {
     "name": "Bob Odenkirk",
     "title": "Software Engineer",
     "location": {
         "locality": "San Francisco",
         "country": "United States"
     },
     "age": 62,
     "company": "Accenture"
};

var missingProps = {};

function getMissingProps(oldObj, newObj){
     for (var prop in oldObj) {
     if(newObj.hasOwnProperty(prop) && typeof oldObj[prop] === 'object')
       missingProps = getMissingProps(oldObj[prop], newObj[prop]);
     else if(!newObj.hasOwnProperty(prop))
         missingProps[prop] =  oldObj[prop] ;
   }

   return missingProps;
}

console.log(getMissingProps(oldObj, newObj));

https://jsfiddle.net/8n244fmb/

if you want complete missing Json props structure try this

var oldObj = oldObjTemp = {
     "name": "Bob Odenkirk",
     "title": "Software Engineer",
     "location": {
         "locality": "San Francisco",
         "region": "CA",
         "country": {"name" : "United States", "code":"US"}
     },
     "age": 62,
     "status": "Active"
};
var newObj = {
     "name": "Bob Odenkirk",
     "title": "Software Engineer",
     "location": {
         "locality": "San Francisco",
         "country": {"name" : "United States"}
     },
     "age": 62,
     "company": "Accenture"
};

var missingProps = {};

function getMissingProps(oldObj, newObj, oldObjTemp){
   for (var prop in oldObj) {
     if(newObj.hasOwnProperty(prop) && typeof oldObj[prop] === 'object'){
            getMissingProps(oldObj[prop], newObj[prop], oldObjTemp[prop]);
     }
     else if(newObj.hasOwnProperty(prop)){
            delete oldObjTemp[prop];
     }
    }
}

getMissingProps(oldObj, newObj, oldObjTemp);

console.log(oldObjTemp);

https://jsfiddle.net/8n244fmb/1/


问:
How to find the depth of a binary tree using Prolog
I am learning Prolog and am trying to find the depth of a binary tree using Prolog.
I represent a tree like this:

```<code>nil is a tree.
tree(1,nil,nil) this is a leaf.
tree(1,tree(1,nil,nil),nil) this is a tree with root 1 and has a left leaf 1.
</code>```

I want a depth predicate that depth(T, N) that will be true if N is the depth of the tree T.
I assume that I'll use the depth predicate when T isn't a variable but N can be a variable.
Examples:

```<code>?- depth(nil,N).
N = 0.

?- depth(tree(1,tree(2,nil,tree(3,nil,nil)),tree(5,tree(6,nil,nil),nil)),N).
N = 3.

?- depth(tree(1,nil,tree(2,nil,nil)),N).
N = 2.
</code>```

I am not sure how do that N will be the maximum between the 2 subtrees.

Thanks for any help.

Solution:

```<code>depth(nil,0).
depth(tree(_,nil,nil),1).
depth(tree(_,Left,Right), D) :-
    depth(Left,DLeft),
    depth(Right,DRight),
    D is max(DLeft, DRight) + 1.
</code>```

答:
Easy as pie: the depth of nil is 0:

```<code>depth(nil,0).
</code>```

For the tree case, recursively call depth/2 on both branches and max them:

```<code>depth(Left,DLeft),
depth(Right,DRight),
D is max(DLeft, DRight) + 1.
</code>```

Body:
I am learning Prolog and am trying to find the depth of a binary tree using Prolog.
I represent a tree like this:

nil is a tree.
tree(1,nil,nil) this is a leaf.
tree(1,tree(1,nil,nil),nil) this is a tree with root 1 and has a left leaf 1.

I want a depth predicate that depth(T, N) that will be true if N is the depth of the tree T.
I assume that I'll use the depth predicate when T isn't a variable but N can be a variable.
Examples:

?- depth(nil,N).
N = 0.

?- depth(tree(1,tree(2,nil,tree(3,nil,nil)),tree(5,tree(6,nil,nil),nil)),N).
N = 3.

?- depth(tree(1,nil,tree(2,nil,nil)),N).
N = 2.

I am not sure how do that N will be the maximum between the 2 subtrees.

Thanks for any help.

Solution:

depth(nil,0).
depth(tree(_,nil,nil),1).
depth(tree(_,Left,Right), D) :-
    depth(Left,DLeft),
    depth(Right,DRight),
    D is max(DLeft, DRight) + 1.

Body:
Easy as pie: the depth of nil is 0:

depth(nil,0).

For the tree case, recursively call depth/2 on both branches and max them:

depth(Left,DLeft),
depth(Right,DRight),
D is max(DLeft, DRight) + 1.


问:
Python weird behaviour List of inherited classes
I am building a speech recognition system and for that I build an interface for the commands. They are made up by subjects, verbs, adjectives and wildcards. I implemented it this way:

```<code>class IWord(object):
    strings = []

    def recognize(self, word):
        return word in self.strings

    def add_synonym(self, word):
        self.strings.append(word)

class Verb(IWord):
    def __init__(self, words):
        for word in words:
            self.add_synonym(word)

class Adjective(IWord):
    def __init__(self, words):
        for word in words:
            self.add_synonym(word)

class Object(IWord):
    def __init__(self, words):
        for word in words:
            self.add_synonym(word)

class WildCard(IWord):
    def recognize(self, word):
        return word is not None & word

class ICommand(object):
    words = []
    parameters = []
</code>```

However I got two classes inheriting from ICommand:

```<code>class Command1(ICommand):

    def __init__(self):
        self.words.append(Verb(['do']))
        self.words.append(Object(['some']))
        self.words.append(WildCard())

class Command1(ICommand):

    def __init__(self):
        self.words.append(Verb(['lorem']))
</code>```

When I am debugging this part:

```<code>for command in self.Commands:
    if command.recognize(text):
        return command
</code>```

It seems like command.words contains 'do', 'some', the wildcard and 'lorem'. I don't get what went wrong there.

答:
Writing words = [],... in the class definition makes words a class-bound variable. Using self.words now returns the (initially empty) dictionary defined for the class bound variable which is shared among the derived classes.

Better: Remove definition and add self.words = [] in the __init__s of the derived classes.

Body:
I am building a speech recognition system and for that I build an interface for the commands. They are made up by subjects, verbs, adjectives and wildcards. I implemented it this way:

class IWord(object):
    strings = []

    def recognize(self, word):
        return word in self.strings

    def add_synonym(self, word):
        self.strings.append(word)

class Verb(IWord):
    def __init__(self, words):
        for word in words:
            self.add_synonym(word)

class Adjective(IWord):
    def __init__(self, words):
        for word in words:
            self.add_synonym(word)

class Object(IWord):
    def __init__(self, words):
        for word in words:
            self.add_synonym(word)

class WildCard(IWord):
    def recognize(self, word):
        return word is not None & word

class ICommand(object):
    words = []
    parameters = []

However I got two classes inheriting from ICommand:

class Command1(ICommand):

    def __init__(self):
        self.words.append(Verb(['do']))
        self.words.append(Object(['some']))
        self.words.append(WildCard())

class Command1(ICommand):

    def __init__(self):
        self.words.append(Verb(['lorem']))

When I am debugging this part:

for command in self.Commands:
    if command.recognize(text):
        return command

It seems like command.words contains 'do', 'some', the wildcard and 'lorem'. I don't get what went wrong there.


问:
i used getid3_write_lyrics3 library. not working
I used getid3_write_lyrics3 library. not working

This my code:

```<code>// Enter your filename here
$filename = 'C:\xampp\htdocs\source2\test.mp3';

//Include getID3() library (can be in a different
                         directory if full path is specified)
require_once('getid3.php');

// Include desired writer module
require_once('write.lyrics3.php');

//Instantiate desired tag class
$tw = new getid3_write_lyrics3($filename);

// Attempt to write new tag  -- NOTE: all values must be in ISO-8859-1
try
{
    $tw->title      = 'bhavi';
    $tw->artist     = 'asas';
    $tw->album      = 'A new album';
    $tw->author     = 'bhavi author';
    $tw->comment    = 'bhavika commment';
    $tw->images     = 'C:\xampp\htdocs\source2\image.jpg';

    $tw->synched    = true;
    $tw->lyrics     = "[00:02]Let's talk about time\r\n[00:02]tickin' away
      every day\r\n[00:05]so wake on up before it's gone away\r\n";

    if(!$tw->write())
    {
        echo "not success";
    }else{
        print 'New tag written<br>';
    }
 }catch (Exception $e)
 {
   print $e->message;
 }
</code>```

OUTPUT

New tag written

but MP# file show blank MP3 Tags. show my below screenshot.

Screenshot:

答:
Since the OP hasn't really ask for a question, and mention in a comment that he wanted to add lyrics to mp3 with id3, then I'm answering.
You don't have to use lyrics3, you can just use normal id3v2.

I had similar problem to get the lyrics saved with getID3 package. It is because of a grammar issue in getID3 in file "getID3/getid3/write.id3v2.php" Line 1982 and Line 2057.

I would simply comment in of @Tom answer, but I can't comment yet. So I'm using his codes:

```<code>$filename = 'fullpath/to/your/music.mp3' ;
$sLyrics = "the lyrics go here" ;

$TextEncoding = 'UTF-8';
require_once('./getid3/getid3/getid3.php');

$getID3 = new getID3;
$getID3->setOption(array('encoding'=>$TextEncoding));

require_once('./getid3/getid3/write.php');

$tagwriter = new getid3_writetags;
$tagwriter->filename = $filename ;
$tagwriter->tagformats = array('id3v2.3');
$tagwriter->overwrite_tags    = true;
$tagwriter->remove_other_tags = false;
$tagwriter->tag_encoding      = $TextEncoding;

$TagData = array(
    'unsychronised_lyric' => array( $sLyrics ),
);
$tagwriter->tag_data = $TagData;

$tagwriter->WriteTags();
</code>```

The key is to change 'unsynchronised_lyrics' to 'unsychronised_lyric' with their misspelling error.
I opened an issue for this in JamesHeinrich getId3, so be careful when you update the package if they change it back to normal in the future so that your codes don't stop writing the lyrics.

UPDATE ---

As I received an immediate answer, the typo error was not from getID3 package, but from id3 Org directly, so it will stay as is. So use 'unsychronised_lyric' safely.

Body:
I used getid3_write_lyrics3 library. not working

This my code:

// Enter your filename here
$filename = 'C:\xampp\htdocs\source2\test.mp3';

//Include getID3() library (can be in a different
                         directory if full path is specified)
require_once('getid3.php');

// Include desired writer module
require_once('write.lyrics3.php');

//Instantiate desired tag class
$tw = new getid3_write_lyrics3($filename);

// Attempt to write new tag  -- NOTE: all values must be in ISO-8859-1
try
{
    $tw->title      = 'bhavi';
    $tw->artist     = 'asas';
    $tw->album      = 'A new album';
    $tw->author     = 'bhavi author';
    $tw->comment    = 'bhavika commment';
    $tw->images     = 'C:\xampp\htdocs\source2\image.jpg';

    $tw->synched    = true;
    $tw->lyrics     = "[00:02]Let's talk about time\r\n[00:02]tickin' away
      every day\r\n[00:05]so wake on up before it's gone away\r\n";

    if(!$tw->write())
    {
        echo "not success";
    }else{
        print 'New tag written
';
    }
 }catch (Exception $e)
 {
   print $e->message;
 }

OUTPUT

New tag written

but MP# file show blank MP3 Tags. show my below screenshot.

Screenshot:

Body:
Since the OP hasn't really ask for a question, and mention in a comment that he wanted to add lyrics to mp3 with id3, then I'm answering.
You don't have to use lyrics3, you can just use normal id3v2.

I had similar problem to get the lyrics saved with getID3 package. It is because of a grammar issue in getID3 in file "getID3/getid3/write.id3v2.php" Line 1982 and Line 2057.

I would simply comment in of @Tom answer, but I can't comment yet. So I'm using his codes:

$filename = 'fullpath/to/your/music.mp3' ;
$sLyrics = "the lyrics go here" ;

$TextEncoding = 'UTF-8';
require_once('./getid3/getid3/getid3.php');

$getID3 = new getID3;
$getID3->setOption(array('encoding'=>$TextEncoding));

require_once('./getid3/getid3/write.php');

$tagwriter = new getid3_writetags;
$tagwriter->filename = $filename ;
$tagwriter->tagformats = array('id3v2.3');
$tagwriter->overwrite_tags    = true;
$tagwriter->remove_other_tags = false;
$tagwriter->tag_encoding      = $TextEncoding;

$TagData = array(
    'unsychronised_lyric' => array( $sLyrics ),
);
$tagwriter->tag_data = $TagData;

$tagwriter->WriteTags();

The key is to change 'unsynchronised_lyrics' to 'unsychronised_lyric' with their misspelling error.
I opened an issue for this in JamesHeinrich getId3, so be careful when you update the package if they change it back to normal in the future so that your codes don't stop writing the lyrics.

UPDATE ---

As I received an immediate answer, the typo error was not from getID3 package, but from id3 Org directly, so it will stay as is. So use 'unsychronised_lyric' safely.


问:
Change button behaviour on (same) button click - jquery
I'm really sorry if this was already asked, but my searching skills just didn't find something similar.

So I have a form with multiple subsections.
I need to hide/show subsections and 'simulate' the page as if it had 3 different parts.
There is no access to the source code, so everything has to be done through css/js applied over existing code.
Keep in mind that there is already a button (I'll call it continueBtn here) that submits the form when pressed and I added a back button. Assume that all the variables (allSections, sectionOne etc. exist, they are not the problem).

I created a function that shows/hides/changes text based on what step of the form we are in; example code:

```<code>function showHideOnStep(step){

            allSections.hide();
            continueBtn.unbind('click');
            backBtn.unbind('click');

            switch (step){
                case 1:
                    sectionOne.show();

                    continueBtn.attr('type','button');//make continue button to not submit
                    continueBtn.text("Go to step 2");

                    backBtn.click(function(){
                        //go to previous browser page, literally
                    })
                    continueBtn.click(function(){
                        showHideOnStep(2);
                    })
                    break;
                case 2:
                    sectionTwo.show();
                    continueBtn.text("Go to step 3");
                    continueBtn.attr('type','button');//make continue button to not submit (in case it's a back from step 3)

                    continueBtn.click(function(){
                        showHideOnStep(1);
                    })
                    backBtn.click(function(){
                        showHideOnStep(3);
                    })
                    break;
                case 3:
                    sectionThree.show();

                    continueBtn.text("Submit");

                    backBtn.click(function(){
                        showHideOnStep(2);
                    })

                    continueBtn.removeAttr('type');//make continue button to submit again
                    break;
            }
        }
</code>```

So let's say page loads and showHideOnStep(1) is applied by default. Everything's fine, clicking back will back, clicking Continue will go to Step 2.
But now, when clicking Continue, it will jump to submitting, instead of going to case 3 first.

It's like the actual "clicking" ends after it removes the "type=button" from the button and it propagates into that.
Same issue will happen when Backing from Step 2. Instead of going to Step 1, it will back for good.

I'm sure there is either of

a) a fairly simple fix for this or
b) a much better/cleaner way to do what I want

Any suggestion will be highly appreciated.

答:
Please include the button html script! If the button was made from a form submit tag, it will submit without going to the next. Trying using a button tag.

//  for checking
var secondbutton = false;

// checks if its been clicked
var firstb = document.getElementById('first');

function second() {
  if(secondbutton == false) {
    alert("first");
    firstb.innerHTML = "Second";
    secondbutton = true;
  }
  else {
    alert("second")
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button id="first" onclick="second()">First</button></code>```

This creates the illusion that it changed!

Body:
I'm really sorry if this was already asked, but my searching skills just didn't find something similar.

So I have a form with multiple subsections.
I need to hide/show subsections and 'simulate' the page as if it had 3 different parts.
There is no access to the source code, so everything has to be done through css/js applied over existing code.
Keep in mind that there is already a button (I'll call it continueBtn here) that submits the form when pressed and I added a back button. Assume that all the variables (allSections, sectionOne etc. exist, they are not the problem).

I created a function that shows/hides/changes text based on what step of the form we are in; example code:

function showHideOnStep(step){

            allSections.hide();
            continueBtn.unbind('click');
            backBtn.unbind('click');

            switch (step){
                case 1:
                    sectionOne.show();

                    continueBtn.attr('type','button');//make continue button to not submit
                    continueBtn.text("Go to step 2");

                    backBtn.click(function(){
                        //go to previous browser page, literally
                    })
                    continueBtn.click(function(){
                        showHideOnStep(2);
                    })
                    break;
                case 2:
                    sectionTwo.show();
                    continueBtn.text("Go to step 3");
                    continueBtn.attr('type','button');//make continue button to not submit (in case it's a back from step 3)

                    continueBtn.click(function(){
                        showHideOnStep(1);
                    })
                    backBtn.click(function(){
                        showHideOnStep(3);
                    })
                    break;
                case 3:
                    sectionThree.show();

                    continueBtn.text("Submit");

                    backBtn.click(function(){
                        showHideOnStep(2);
                    })

                    continueBtn.removeAttr('type');//make continue button to submit again
                    break;
            }
        }

So let's say page loads and showHideOnStep(1) is applied by default. Everything's fine, clicking back will back, clicking Continue will go to Step 2.
But now, when clicking Continue, it will jump to submitting, instead of going to case 3 first.

It's like the actual "clicking" ends after it removes the "type=button" from the button and it propagates into that.
Same issue will happen when Backing from Step 2. Instead of going to Step 1, it will back for good.

I'm sure there is either of

a) a fairly simple fix for this or
b) a much better/cleaner way to do what I want

Any suggestion will be highly appreciated.

Body:
Please include the button html script! If the button was made from a form submit tag, it will submit without going to the next. Trying using a button tag.

//  for checking
var secondbutton = false;

// checks if its been clicked
var firstb = document.getElementById('first');

function second() {
  if(secondbutton == false) {
    alert("first");
    firstb.innerHTML = "Second";
    secondbutton = true;
  }
  else {
    alert("second")
  }
}

<button id="first" onclick="second()">First</button>

This creates the illusion that it changed!


问:
Does ReactDOM.render wait for the document to be loaded before rendering?
I'm wondering if I need to wait for the document to be loaded (i.e. listen to DOMCOntentLoaded) before calling ReactDOM.render(...).  It doesn't seem like other React example apps are doing so, so I'm guessing inside the implementation of ReactDOM.render they already wait?

答:
You just need to ensure that the DOM element that your react code renders into is available at the time the

<script type="text/javascript" src="./my-react-script.js"></script>

```

Body:
You just need to ensure that the DOM element that your react code renders into is available at the time the <script> is evaluated. You can do this by placing the script after the dom element in your index.html file.

<!-- this will work -->
<div id="react-app"></div>
<script type="text/javascript" src="./my-react-script.js"></script>

<!-- this will NOT work -->
<script type="text/javascript" src="./my-react-script.js"></script>
<div id="react-app"></div>