问:
dump file where is monitor.wait entry point? and how i can find the reason of wait?
in the following dump file

windbg !dumpstack

where is monitor.wait entry point?

and how i can find the reason of wait?

and the function that causes the wait?

i'm sure that wait is happening here but i cant find my way through the dump file

which function the wait is happening on?

how can i further investigate the reason of the wait?

is there any resource or tutorial on finding the reason of this kind of wait?

```<code>ntdll!NtWaitForMultipleObjects+14
KERNELBASE!WaitForMultipleObjectsEx+ef
coreclr!Thread::DoAppropriateWaitWorker+fe
coreclr!Thread::DoAppropriateWait+7d
coreclr!CLREventBase::WaitEx+7f
coreclr!SyncBlock::Wait+194
[[GCFrame]]
coreclr!ObjectNative::WaitTimeout+d4
[[HelperMethodFrame_1OBJ] (System.Threading.Monitor.ObjWait)] System.Threading.Monitor.ObjWait(Boolean, Int32, System.Object)
System.Threading.ManualResetEventSlim.Wait(Int32, System.Threading.CancellationToken)+398
System.Threading.Tasks.Task.SpinThenBlockingWait(Int32, System.Threading.CancellationToken)+b9
System.Threading.Tasks.Task.InternalWait(Int32, System.Threading.CancellationToken)+1a2
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(System.Threading.Tasks.Task)+25
Microsoft.AspNetCore.Mvc.Rendering.HtmlHelperPartialExtensions.Partial(Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper, System.String, System.Object, Microsoft.AspNetCore.Mvc.ViewFeatures.ViewDataDictionary)+3c
AspNetCore._Areas_Article_Views_Article_Index_cshtml+<ExecuteAsync>d__86.MoveNext()+2c2
System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start[[AspNetCore._Areas_Article_Views_Article_Index_cshtml+<ExecuteAsync>d__86, fkzqs1mt.znn]](<ExecuteAsync>d__86 ByRef)+45
AspNetCore._Areas_Article_Views_Article_Index_cshtml.ExecuteAsync()+7e
Microsoft.AspNetCore.Mvc.Razor.RazorView+<RenderPageAsync>d__14.MoveNext()+367
System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1[[System.__Canon, System.Private.CoreLib]].Start[[Microsoft.AspNetCore.Mvc.Razor.RazorView+<RenderPageAsync>d__14, Microsoft.AspNetCore.Mvc.Razor]](<RenderPageAsync>d__14 ByRef)+4d
Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageAsync(Microsoft.AspNetCore.Mvc.Razor.IRazorPage, Microsoft.AspNetCore.Mvc.Rendering.ViewContext, Boolean)+ac
Microsoft.AspNetCore.Mvc.Razor.RazorView+<RenderAsync>d__13.MoveNext()+a6
System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start[[Microsoft.AspNetCore.Mvc.Razor.RazorView+<RenderAsync>d__13, Microsoft.AspNetCore.Mvc.Razor]](<RenderAsync>d__13 ByRef)+45
Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderAsync(Microsoft.AspNetCore.Mvc.Rendering.ViewContext)+89
Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor+<ExecuteAsync>d__18.MoveNext()+2e5
System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start[[Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor+<ExecuteAsync>d__18, Microsoft.AspNetCore.Mvc.ViewFeatures]](<ExecuteAsync>d__18 ByRef)+45
Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(Microsoft.AspNetCore.Mvc.ActionContext, Microsoft.AspNetCore.Mvc.ViewEngines.IView, Microsoft.AspNetCore.Mvc.ViewFeatures.ViewDataDictionary, Microsoft.AspNetCore.Mvc.ViewFeatures.ITempDataDictionary, System.String, System.Nullable`1<Int32>)+cc
Microsoft.AspNetCore.Mvc.ViewFeatures.Internal.ViewResultExecutor.ExecuteAsync(Microsoft.AspNetCore.Mvc.ActionContext, Microsoft.AspNetCore.Mvc.ViewEngines.IView, Microsoft.AspNetCore.Mvc.ViewResult)+8a
Microsoft.AspNetCore.Mvc.ViewResult+<ExecuteResultAsync>d__26.MoveNext()+e5
System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start[[Microsoft.AspNetCore.Mvc.ViewResult+<ExecuteResultAsync>d__26, Microsoft.AspNetCore.Mvc.ViewFeatures]](<ExecuteResultAsync>d__26 ByRef)+45
Microsoft.AspNetCore.Mvc.ViewResult.ExecuteResultAsync(Microsoft.AspNetCore.Mvc.ActionContext)+89
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker+<InvokeResultAsync>d__30.MoveNext()+88
System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start[[Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker+<InvokeResultAsync>d__30, Microsoft.AspNetCore.Mvc.Core]](<InvokeResultAsync>d__30 ByRef)+45
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeResultAsync(Microsoft.AspNetCore.Mvc.IActionResult)+89
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State ByRef, Scope ByRef, System.Object ByRef, Boolean ByRef)+1351
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker+<InvokeNextResultFilterAsync>d__28.MoveNext()+b0
System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start[[Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker+<InvokeNextResultFilterAsync>d__28, Microsoft.AspNetCore.Mvc.Core]](<InvokeNextResultFilterAsync>d__28 ByRef)+45
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeNextResultFilterAsync()+84
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State ByRef, Scope ByRef, System.Object ByRef, Boolean ByRef)+128e
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker+<InvokeNextResourceFilter>d__22.MoveNext()+b0
System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start[[Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker+<InvokeNextResourceFilter>d__22, Microsoft.AspNetCore.Mvc.Core]](<InvokeNextResourceFilter>d__22 ByRef)+45
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeNextResourceFilter()+84
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State ByRef, Scope ByRef, System.Object ByRef, Boolean ByRef)+583
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker+<InvokeAsync>d__20.MoveNext()+1f3
System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start[[Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker+<InvokeAsync>d__20, Microsoft.AspNetCore.Mvc.Core]](<InvokeAsync>d__20 ByRef)+45
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeAsync()+9b
Microsoft.AspNetCore.Builder.RouterMiddleware+<Invoke>d__4.MoveNext()+2e4
System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start[[Microsoft.AspNetCore.Builder.RouterMiddleware+<Invoke>d__4, Microsoft.AspNetCore.Routing]](<Invoke>d__4 ByRef)+45
Microsoft.AspNetCore.Builder.RouterMiddleware.Invoke(Microsoft.AspNetCore.Http.HttpContext)+89
NWebsec.AspNetCore.Middleware.Middleware.MiddlewareBase+<Invoke>d__2.MoveNext()+68
System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start[[NWebsec.AspNetCore.Middleware.Middleware.MiddlewareBase+<Invoke>d__2, NWebsec.AspNetCore.Middleware]](<Invoke>d__2 ByRef)+45
NWebsec.AspNetCore.Middleware.Middleware.MiddlewareBase.Invoke(Microsoft.AspNetCore.Http.HttpContext)+83
NWebsec.AspNetCore.Middleware.Middleware.MiddlewareBase+<Invoke>d__2.MoveNext()+68
System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start[[NWebsec.AspNetCore.Middleware.Middleware.MiddlewareBase+<Invoke>d__2, NWebsec.AspNetCore.Middleware]](<Invoke>d__2 ByRef)+45
NWebsec.AspNetCore.Middleware.Middleware.MiddlewareBase.Invoke(Microsoft.AspNetCore.Http.HttpContext)+83
NWebsec.AspNetCore.Middleware.Middleware.MiddlewareBase+<Invoke>d__2.MoveNext()+68
System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start[[NWebsec.AspNetCore.Middleware.Middleware.MiddlewareBase+<Invoke>d__2, NWebsec.AspNetCore.Middleware]](<Invoke>d__2 ByRef)+45
NWebsec.AspNetCore.Middleware.Middleware.MiddlewareBase.Invoke(Microsoft.AspNetCore.Http.HttpContext)+83
Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(Microsoft.AspNetCore.Http.HttpContext)+21b
Microsoft.AspNetCore.Authentication.AuthenticationMiddleware`1+<Invoke>d__18[[System.__Canon, System.Private.CoreLib]].MoveNext()+2e1
System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start[[Microsoft.AspNetCore.Authentication.AuthenticationMiddleware`1+<Invoke>d__18[[System.__Canon, System.Private.CoreLib]], Microsoft.AspNetCore.Authentication]](<Invoke>d__18<System.__Canon> ByRef)+7e
Microsoft.AspNetCore.Authentication.AuthenticationMiddleware`1[[System.__Canon, System.Private.CoreLib]].Invoke(Microsoft.AspNetCore.Http.HttpContext)+b9
Microsoft.AspNetCore.Authentication.AuthenticationMiddleware`1+<Invoke>d__18[[System.__Canon, System.Private.CoreLib]].MoveNext()+2e1
System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start[[Microsoft.AspNetCore.Authentication.AuthenticationMiddleware`1+<Invoke>d__18[[System.__Canon, System.Private.CoreLib]], Microsoft.AspNetCore.Authentication]](<Invoke>d__18<System.__Canon> ByRef)+7e
Microsoft.AspNetCore.Authentication.AuthenticationMiddleware`1[[System.__Canon, System.Private.CoreLib]].Invoke(Microsoft.AspNetCore.Http.HttpContext)+b9
Microsoft.AspNetCore.Authentication.AuthenticationMiddleware`1+<Invoke>d__18[[System.__Canon, System.Private.CoreLib]].MoveNext()+2e1
System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start[[Microsoft.AspNetCore.Authentication.AuthenticationMiddleware`1+<Invoke>d__18[[System.__Canon, System.Private.CoreLib]], Microsoft.AspNetCore.Authentication]](<Invoke>d__18<System.__Canon> ByRef)+7e
Microsoft.AspNetCore.Authentication.AuthenticationMiddleware`1[[System.__Canon, System.Private.CoreLib]].Invoke(Microsoft.AspNetCore.Http.HttpContext)+b9
Microsoft.AspNetCore.Authentication.AuthenticationMiddleware`1+<Invoke>d__18[[System.__Canon, System.Private.CoreLib]].MoveNext()+2e1
System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start[[Microsoft.AspNetCore.Authentication.AuthenticationMiddleware`1+<Invoke>d__18[[System.__Canon, System.Private.CoreLib]], Microsoft.AspNetCore.Authentication]](<Invoke>d__18<System.__Canon> ByRef)+7e
Microsoft.AspNetCore.Authentication.AuthenticationMiddleware`1[[System.__Canon, System.Private.CoreLib]].Invoke(Microsoft.AspNetCore.Http.HttpContext)+b9
Microsoft.AspNetCore.Session.SessionMiddleware+<Invoke>d__9.MoveNext()+2a6
System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start[[Microsoft.AspNetCore.Session.SessionMiddleware+<Invoke>d__9, Microsoft.AspNetCore.Session]](<Invoke>d__9 ByRef)+45
Microsoft.AspNetCore.Session.SessionMiddleware.Invoke(Microsoft.AspNetCore.Http.HttpContext)+89
Microsoft.AspNetCore.Builder.RouterMiddleware+<Invoke>d__4.MoveNext()+1c9
System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start[[Microsoft.AspNetCore.Builder.RouterMiddleware+<Invoke>d__4, Microsoft.AspNetCore.Routing]](<Invoke>d__4 ByRef)+45
Microsoft.AspNetCore.Builder.RouterMiddleware.Invoke(Microsoft.AspNetCore.Http.HttpContext)+89
Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware+<Invoke>d__6.MoveNext()+76
System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start[[Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware+<Invoke>d__6, Microsoft.AspNetCore.Diagnostics]](<Invoke>d__6 ByRef)+45
Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.Invoke(Microsoft.AspNetCore.Http.HttpContext)+8f
Microsoft.AspNetCore.Diagnostics.StatusCodePagesMiddleware+<Invoke>d__3.MoveNext()+ba
System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start[[Microsoft.AspNetCore.Diagnostics.StatusCodePagesMiddleware+<Invoke>d__3, Microsoft.AspNetCore.Diagnostics]](<Invoke>d__3 ByRef)+45
Microsoft.AspNetCore.Diagnostics.StatusCodePagesMiddleware.Invoke(Microsoft.AspNetCore.Http.HttpContext)+89
Microsoft.AspNetCore.Server.IISIntegration.IISMiddleware+<Invoke>d__8.MoveNext()+3c5
System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start[[Microsoft.AspNetCore.Server.IISIntegration.IISMiddleware+<Invoke>d__8, Microsoft.AspNetCore.Server.IISIntegration]](<Invoke>d__8 ByRef)+45
Microsoft.AspNetCore.Server.IISIntegration.IISMiddleware.Invoke(Microsoft.AspNetCore.Http.HttpContext)+89
Microsoft.AspNetCore.Hosting.Internal.RequestServicesContainerMiddleware+<Invoke>d__3.MoveNext()+205
System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start[[Microsoft.AspNetCore.Hosting.Internal.RequestServicesContainerMiddleware+<Invoke>d__3, Microsoft.AspNetCore.Hosting]](<Invoke>d__3 ByRef)+45
Microsoft.AspNetCore.Hosting.Internal.RequestServicesContainerMiddleware.Invoke(Microsoft.AspNetCore.Http.HttpContext)+89
Microsoft.AspNetCore.Hosting.Internal.HostingApplication.ProcessRequestAsync(Context)+39
Microsoft.AspNetCore.Server.Kestrel.Internal.Http.Frame`1+<RequestProcessingAsync>d__2[[Microsoft.AspNetCore.Hosting.Internal.HostingApplication+Context, Microsoft.AspNetCore.Hosting]].MoveNext()+63e
System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start[[Microsoft.AspNetCore.Server.Kestrel.Internal.Http.Frame`1+<RequestProcessingAsync>d__2[[Microsoft.AspNetCore.Hosting.Internal.HostingApplication+Context, Microsoft.AspNetCore.Hosting]], Microsoft.AspNetCore.Server.Kestrel]](<RequestProcessingAsync>d__2<Context> ByRef)+45
Microsoft.AspNetCore.Server.Kestrel.Internal.Http.Frame`1[[Microsoft.AspNetCore.Hosting.Internal.HostingApplication+Context, Microsoft.AspNetCore.Hosting]].RequestProcessingAsync()+ad
System.Threading.Tasks.Task`1[[System.__Canon, System.Private.CoreLib]].InnerInvoke()+9b
System.Threading.Tasks.Task.Execute()+49
System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object)+97
System.Threading.Tasks.Task.ExecuteWithThreadLocal(System.Threading.Tasks.Task ByRef)+23e
System.Threading.Tasks.Task.ExecuteEntry(Boolean)+a2
System.Threading.ThreadPoolWorkQueue.Dispatch()+1e2
coreclr!CallDescrWorkerInternal+83
coreclr!MethodDescCallSite::CallTargetWorker+14e
coreclr!QueueUserWorkItemManagedCallback+38
coreclr!QueueUserWorkItemManagedCallback+2df
coreclr!QueueUserWorkItemManagedCallback+234
coreclr!QueueUserWorkItemManagedCallback+161
[[DebuggerU2MCatchHandlerFrame]]
coreclr!QueueUserWorkItemManagedCallback+7b
coreclr!ManagedPerAppDomainTPCount::DispatchWorkItem+8e
coreclr!ThreadpoolMgr::WorkerThreadStart+188
coreclr!Thread::intermediateThreadProc+8b
kernel32!BaseThreadInitThunk+14
ntdll!RtlUserThreadStart+21
</code>```

答:
Monitor.Wait is called within ManualResetEventSlim.Wait.

The ManualResetEventSlim class does some spinning while it is waiting for an event to be set and will call Monitor.Wait if the event isn't set while it is polling/spinning.

A quick scan of your stack trace it looks like you waiting on a async task to be completed.   Here is where the waiting looks to begin .. Just follow the stack traces (dump stack objects to find and further analyze the bolded task being passed in or !clrstack -a  might get you some more parameter and locals information).

```<code>            System.Threading.Tasks.Task.InternalWait(Int32, System.Threading.CancellationToken)+1a2
            System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(**System.Threading.Tasks.Task**)+25
            Microsoft.AspNetCore.Mvc.Rendering.HtmlHelperPartialExtensions.Partial(Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper, System.String, System.Object, Microsoft.AspNetCore.Mvc.ViewFeatures.ViewDataDictionary)+3c
            AspNetCore._Areas_Article_Views_Article_Index_cshtml+<ExecuteAsync>d__86.MoveNext()+2c2
            System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start[[AspNetCore._Areas_Article_Views_Article_Index_cshtml+<ExecuteAsync>d__86, fkzqs1mt.znn]](<ExecuteAsync>d__86 ByRef)+45
            AspNetCore._Areas_Article_Views_Article_Index_cshtml.ExecuteAsync()+7e
</code>```

Body:
in the following dump file

windbg !dumpstack

where is monitor.wait entry point?

and how i can find the reason of wait?

and the function that causes the wait?

i'm sure that wait is happening here but i cant find my way through the dump file

which function the wait is happening on?

how can i further investigate the reason of the wait?

is there any resource or tutorial on finding the reason of this kind of wait?

ntdll!NtWaitForMultipleObjects+14
KERNELBASE!WaitForMultipleObjectsEx+ef
coreclr!Thread::DoAppropriateWaitWorker+fe
coreclr!Thread::DoAppropriateWait+7d
coreclr!CLREventBase::WaitEx+7f
coreclr!SyncBlock::Wait+194
[[GCFrame]]
coreclr!ObjectNative::WaitTimeout+d4
[[HelperMethodFrame_1OBJ] (System.Threading.Monitor.ObjWait)] System.Threading.Monitor.ObjWait(Boolean, Int32, System.Object)
System.Threading.ManualResetEventSlim.Wait(Int32, System.Threading.CancellationToken)+398
System.Threading.Tasks.Task.SpinThenBlockingWait(Int32, System.Threading.CancellationToken)+b9
System.Threading.Tasks.Task.InternalWait(Int32, System.Threading.CancellationToken)+1a2
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(System.Threading.Tasks.Task)+25
Microsoft.AspNetCore.Mvc.Rendering.HtmlHelperPartialExtensions.Partial(Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper, System.String, System.Object, Microsoft.AspNetCore.Mvc.ViewFeatures.ViewDataDictionary)+3c
AspNetCore._Areas_Article_Views_Article_Index_cshtml+<ExecuteAsync>d__86.MoveNext()+2c2
System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start[[AspNetCore._Areas_Article_Views_Article_Index_cshtml+<ExecuteAsync>d__86, fkzqs1mt.znn]](<ExecuteAsync>d__86 ByRef)+45
AspNetCore._Areas_Article_Views_Article_Index_cshtml.ExecuteAsync()+7e
Microsoft.AspNetCore.Mvc.Razor.RazorView+<RenderPageAsync>d__14.MoveNext()+367
System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1[[System.__Canon, System.Private.CoreLib]].Start[[Microsoft.AspNetCore.Mvc.Razor.RazorView+<RenderPageAsync>d__14, Microsoft.AspNetCore.Mvc.Razor]](<RenderPageAsync>d__14 ByRef)+4d
Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageAsync(Microsoft.AspNetCore.Mvc.Razor.IRazorPage, Microsoft.AspNetCore.Mvc.Rendering.ViewContext, Boolean)+ac
Microsoft.AspNetCore.Mvc.Razor.RazorView+<RenderAsync>d__13.MoveNext()+a6
System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start[[Microsoft.AspNetCore.Mvc.Razor.RazorView+<RenderAsync>d__13, Microsoft.AspNetCore.Mvc.Razor]](<RenderAsync>d__13 ByRef)+45
Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderAsync(Microsoft.AspNetCore.Mvc.Rendering.ViewContext)+89
Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor+<ExecuteAsync>d__18.MoveNext()+2e5
System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start[[Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor+<ExecuteAsync>d__18, Microsoft.AspNetCore.Mvc.ViewFeatures]](<ExecuteAsync>d__18 ByRef)+45
Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(Microsoft.AspNetCore.Mvc.ActionContext, Microsoft.AspNetCore.Mvc.ViewEngines.IView, Microsoft.AspNetCore.Mvc.ViewFeatures.ViewDataDictionary, Microsoft.AspNetCore.Mvc.ViewFeatures.ITempDataDictionary, System.String, System.Nullable`1<Int32>)+cc
Microsoft.AspNetCore.Mvc.ViewFeatures.Internal.ViewResultExecutor.ExecuteAsync(Microsoft.AspNetCore.Mvc.ActionContext, Microsoft.AspNetCore.Mvc.ViewEngines.IView, Microsoft.AspNetCore.Mvc.ViewResult)+8a
Microsoft.AspNetCore.Mvc.ViewResult+<ExecuteResultAsync>d__26.MoveNext()+e5
System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start[[Microsoft.AspNetCore.Mvc.ViewResult+<ExecuteResultAsync>d__26, Microsoft.AspNetCore.Mvc.ViewFeatures]](<ExecuteResultAsync>d__26 ByRef)+45
Microsoft.AspNetCore.Mvc.ViewResult.ExecuteResultAsync(Microsoft.AspNetCore.Mvc.ActionContext)+89
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker+<InvokeResultAsync>d__30.MoveNext()+88
System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start[[Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker+<InvokeResultAsync>d__30, Microsoft.AspNetCore.Mvc.Core]](<InvokeResultAsync>d__30 ByRef)+45
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeResultAsync(Microsoft.AspNetCore.Mvc.IActionResult)+89
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State ByRef, Scope ByRef, System.Object ByRef, Boolean ByRef)+1351
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker+<InvokeNextResultFilterAsync>d__28.MoveNext()+b0
System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start[[Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker+<InvokeNextResultFilterAsync>d__28, Microsoft.AspNetCore.Mvc.Core]](<InvokeNextResultFilterAsync>d__28 ByRef)+45
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeNextResultFilterAsync()+84
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State ByRef, Scope ByRef, System.Object ByRef, Boolean ByRef)+128e
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker+<InvokeNextResourceFilter>d__22.MoveNext()+b0
System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start[[Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker+<InvokeNextResourceFilter>d__22, Microsoft.AspNetCore.Mvc.Core]](<InvokeNextResourceFilter>d__22 ByRef)+45
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeNextResourceFilter()+84
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State ByRef, Scope ByRef, System.Object ByRef, Boolean ByRef)+583
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker+<InvokeAsync>d__20.MoveNext()+1f3
System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start[[Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker+<InvokeAsync>d__20, Microsoft.AspNetCore.Mvc.Core]](<InvokeAsync>d__20 ByRef)+45
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeAsync()+9b
Microsoft.AspNetCore.Builder.RouterMiddleware+<Invoke>d__4.MoveNext()+2e4
System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start[[Microsoft.AspNetCore.Builder.RouterMiddleware+<Invoke>d__4, Microsoft.AspNetCore.Routing]](<Invoke>d__4 ByRef)+45
Microsoft.AspNetCore.Builder.RouterMiddleware.Invoke(Microsoft.AspNetCore.Http.HttpContext)+89
NWebsec.AspNetCore.Middleware.Middleware.MiddlewareBase+<Invoke>d__2.MoveNext()+68
System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start[[NWebsec.AspNetCore.Middleware.Middleware.MiddlewareBase+<Invoke>d__2, NWebsec.AspNetCore.Middleware]](<Invoke>d__2 ByRef)+45
NWebsec.AspNetCore.Middleware.Middleware.MiddlewareBase.Invoke(Microsoft.AspNetCore.Http.HttpContext)+83
NWebsec.AspNetCore.Middleware.Middleware.MiddlewareBase+<Invoke>d__2.MoveNext()+68
System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start[[NWebsec.AspNetCore.Middleware.Middleware.MiddlewareBase+<Invoke>d__2, NWebsec.AspNetCore.Middleware]](<Invoke>d__2 ByRef)+45
NWebsec.AspNetCore.Middleware.Middleware.MiddlewareBase.Invoke(Microsoft.AspNetCore.Http.HttpContext)+83
NWebsec.AspNetCore.Middleware.Middleware.MiddlewareBase+<Invoke>d__2.MoveNext()+68
System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start[[NWebsec.AspNetCore.Middleware.Middleware.MiddlewareBase+<Invoke>d__2, NWebsec.AspNetCore.Middleware]](<Invoke>d__2 ByRef)+45
NWebsec.AspNetCore.Middleware.Middleware.MiddlewareBase.Invoke(Microsoft.AspNetCore.Http.HttpContext)+83
Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(Microsoft.AspNetCore.Http.HttpContext)+21b
Microsoft.AspNetCore.Authentication.AuthenticationMiddleware`1+<Invoke>d__18[[System.__Canon, System.Private.CoreLib]].MoveNext()+2e1
System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start[[Microsoft.AspNetCore.Authentication.AuthenticationMiddleware`1+<Invoke>d__18[[System.__Canon, System.Private.CoreLib]], Microsoft.AspNetCore.Authentication]](<Invoke>d__18<System.__Canon> ByRef)+7e
Microsoft.AspNetCore.Authentication.AuthenticationMiddleware`1[[System.__Canon, System.Private.CoreLib]].Invoke(Microsoft.AspNetCore.Http.HttpContext)+b9
Microsoft.AspNetCore.Authentication.AuthenticationMiddleware`1+<Invoke>d__18[[System.__Canon, System.Private.CoreLib]].MoveNext()+2e1
System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start[[Microsoft.AspNetCore.Authentication.AuthenticationMiddleware`1+<Invoke>d__18[[System.__Canon, System.Private.CoreLib]], Microsoft.AspNetCore.Authentication]](<Invoke>d__18<System.__Canon> ByRef)+7e
Microsoft.AspNetCore.Authentication.AuthenticationMiddleware`1[[System.__Canon, System.Private.CoreLib]].Invoke(Microsoft.AspNetCore.Http.HttpContext)+b9
Microsoft.AspNetCore.Authentication.AuthenticationMiddleware`1+<Invoke>d__18[[System.__Canon, System.Private.CoreLib]].MoveNext()+2e1
System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start[[Microsoft.AspNetCore.Authentication.AuthenticationMiddleware`1+<Invoke>d__18[[System.__Canon, System.Private.CoreLib]], Microsoft.AspNetCore.Authentication]](<Invoke>d__18<System.__Canon> ByRef)+7e
Microsoft.AspNetCore.Authentication.AuthenticationMiddleware`1[[System.__Canon, System.Private.CoreLib]].Invoke(Microsoft.AspNetCore.Http.HttpContext)+b9
Microsoft.AspNetCore.Authentication.AuthenticationMiddleware`1+<Invoke>d__18[[System.__Canon, System.Private.CoreLib]].MoveNext()+2e1
System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start[[Microsoft.AspNetCore.Authentication.AuthenticationMiddleware`1+<Invoke>d__18[[System.__Canon, System.Private.CoreLib]], Microsoft.AspNetCore.Authentication]](<Invoke>d__18<System.__Canon> ByRef)+7e
Microsoft.AspNetCore.Authentication.AuthenticationMiddleware`1[[System.__Canon, System.Private.CoreLib]].Invoke(Microsoft.AspNetCore.Http.HttpContext)+b9
Microsoft.AspNetCore.Session.SessionMiddleware+<Invoke>d__9.MoveNext()+2a6
System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start[[Microsoft.AspNetCore.Session.SessionMiddleware+<Invoke>d__9, Microsoft.AspNetCore.Session]](<Invoke>d__9 ByRef)+45
Microsoft.AspNetCore.Session.SessionMiddleware.Invoke(Microsoft.AspNetCore.Http.HttpContext)+89
Microsoft.AspNetCore.Builder.RouterMiddleware+<Invoke>d__4.MoveNext()+1c9
System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start[[Microsoft.AspNetCore.Builder.RouterMiddleware+<Invoke>d__4, Microsoft.AspNetCore.Routing]](<Invoke>d__4 ByRef)+45
Microsoft.AspNetCore.Builder.RouterMiddleware.Invoke(Microsoft.AspNetCore.Http.HttpContext)+89
Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware+<Invoke>d__6.MoveNext()+76
System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start[[Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware+<Invoke>d__6, Microsoft.AspNetCore.Diagnostics]](<Invoke>d__6 ByRef)+45
Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.Invoke(Microsoft.AspNetCore.Http.HttpContext)+8f
Microsoft.AspNetCore.Diagnostics.StatusCodePagesMiddleware+<Invoke>d__3.MoveNext()+ba
System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start[[Microsoft.AspNetCore.Diagnostics.StatusCodePagesMiddleware+<Invoke>d__3, Microsoft.AspNetCore.Diagnostics]](<Invoke>d__3 ByRef)+45
Microsoft.AspNetCore.Diagnostics.StatusCodePagesMiddleware.Invoke(Microsoft.AspNetCore.Http.HttpContext)+89
Microsoft.AspNetCore.Server.IISIntegration.IISMiddleware+<Invoke>d__8.MoveNext()+3c5
System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start[[Microsoft.AspNetCore.Server.IISIntegration.IISMiddleware+<Invoke>d__8, Microsoft.AspNetCore.Server.IISIntegration]](<Invoke>d__8 ByRef)+45
Microsoft.AspNetCore.Server.IISIntegration.IISMiddleware.Invoke(Microsoft.AspNetCore.Http.HttpContext)+89
Microsoft.AspNetCore.Hosting.Internal.RequestServicesContainerMiddleware+<Invoke>d__3.MoveNext()+205
System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start[[Microsoft.AspNetCore.Hosting.Internal.RequestServicesContainerMiddleware+<Invoke>d__3, Microsoft.AspNetCore.Hosting]](<Invoke>d__3 ByRef)+45
Microsoft.AspNetCore.Hosting.Internal.RequestServicesContainerMiddleware.Invoke(Microsoft.AspNetCore.Http.HttpContext)+89
Microsoft.AspNetCore.Hosting.Internal.HostingApplication.ProcessRequestAsync(Context)+39
Microsoft.AspNetCore.Server.Kestrel.Internal.Http.Frame`1+<RequestProcessingAsync>d__2[[Microsoft.AspNetCore.Hosting.Internal.HostingApplication+Context, Microsoft.AspNetCore.Hosting]].MoveNext()+63e
System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start[[Microsoft.AspNetCore.Server.Kestrel.Internal.Http.Frame`1+<RequestProcessingAsync>d__2[[Microsoft.AspNetCore.Hosting.Internal.HostingApplication+Context, Microsoft.AspNetCore.Hosting]], Microsoft.AspNetCore.Server.Kestrel]](<RequestProcessingAsync>d__2<Context> ByRef)+45
Microsoft.AspNetCore.Server.Kestrel.Internal.Http.Frame`1[[Microsoft.AspNetCore.Hosting.Internal.HostingApplication+Context, Microsoft.AspNetCore.Hosting]].RequestProcessingAsync()+ad
System.Threading.Tasks.Task`1[[System.__Canon, System.Private.CoreLib]].InnerInvoke()+9b
System.Threading.Tasks.Task.Execute()+49
System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object)+97
System.Threading.Tasks.Task.ExecuteWithThreadLocal(System.Threading.Tasks.Task ByRef)+23e
System.Threading.Tasks.Task.ExecuteEntry(Boolean)+a2
System.Threading.ThreadPoolWorkQueue.Dispatch()+1e2
coreclr!CallDescrWorkerInternal+83
coreclr!MethodDescCallSite::CallTargetWorker+14e
coreclr!QueueUserWorkItemManagedCallback+38
coreclr!QueueUserWorkItemManagedCallback+2df
coreclr!QueueUserWorkItemManagedCallback+234
coreclr!QueueUserWorkItemManagedCallback+161
[[DebuggerU2MCatchHandlerFrame]]
coreclr!QueueUserWorkItemManagedCallback+7b
coreclr!ManagedPerAppDomainTPCount::DispatchWorkItem+8e
coreclr!ThreadpoolMgr::WorkerThreadStart+188
coreclr!Thread::intermediateThreadProc+8b
kernel32!BaseThreadInitThunk+14
ntdll!RtlUserThreadStart+21

Body:
Monitor.Wait is called within ManualResetEventSlim.Wait.

The ManualResetEventSlim class does some spinning while it is waiting for an event to be set and will call Monitor.Wait if the event isn't set while it is polling/spinning.

A quick scan of your stack trace it looks like you waiting on a async task to be completed.   Here is where the waiting looks to begin .. Just follow the stack traces (dump stack objects to find and further analyze the bolded task being passed in or !clrstack -a  might get you some more parameter and locals information).

            System.Threading.Tasks.Task.InternalWait(Int32, System.Threading.CancellationToken)+1a2
            System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(**System.Threading.Tasks.Task**)+25
            Microsoft.AspNetCore.Mvc.Rendering.HtmlHelperPartialExtensions.Partial(Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper, System.String, System.Object, Microsoft.AspNetCore.Mvc.ViewFeatures.ViewDataDictionary)+3c
            AspNetCore._Areas_Article_Views_Article_Index_cshtml+<ExecuteAsync>d__86.MoveNext()+2c2
            System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start[[AspNetCore._Areas_Article_Views_Article_Index_cshtml+<ExecuteAsync>d__86, fkzqs1mt.znn]](<ExecuteAsync>d__86 ByRef)+45
            AspNetCore._Areas_Article_Views_Article_Index_cshtml.ExecuteAsync()+7e


来源: stackexchange

问:
How to reuse Android axml layout design inside another axml layout in xamarin
I have a axml layout design which i want to use in another next layout? How can i do that if it is possible.
My reusable sample axml code as follows

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:focusable="true"
    android:paddingLeft="10dp"
    android:paddingRight="10dp"
    android:paddingTop="10dp"
    android:paddingBottom="10dp"
    android:clickable="true"
    android:weightSum="100"
    android:background="@android:color/background_light"
    android:orientation="horizontal">
     <LinearLayout
      android:layout_width="0dp"
      android:layout_height="wrap_content"
      android:layout_weight="20"
      android:gravity="center_horizontal">
    <refractored.controls.CircleImageView
     xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/door_image"
        android:layout_width="70dp"
        android:layout_height="70dp"
        app:civ_border_width="0dp"
        app:civ_border_color="#FF000000"
        android:src="@drawable/fingerprint_icon" />
     </LinearLayout>
     </LinearLayout>```

答:
If you already know the layout that you want to re-use, create a new XML file and define the layout. For example, here's a layout that defines a title bar to be included in each activity (titlebar.xml):

```<code><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/titlebar_bg"
    tools:showIn="@layout/activity_main" >

    <ImageView android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:src="@drawable/gafricalogo" />
</FrameLayout>
</code>```

The root View should be exactly how you'd like it to appear in each layout to which you add this layout.

Use the include Tag

Inside the layout to which you want to add the re-usable component, add the  tag. For example, here's a layout that includes the title bar from above:

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/app_bg"
    android:gravity="center_horizontal">

    <include layout="@layout/titlebar"/>

    <TextView android:layout_width="match_parent"
              android:layout_height="wrap_content"
              android:text="@string/hello"
              android:padding="10dp" />

    ...

</LinearLayout>
</code>```

Source: https://developer.android.com/training/improving-layouts/reusing-layouts.html#Include

ContentLicense: CC BY-SA 3.0

Body:
If you already know the layout that you want to re-use, create a new XML file and define the layout. For example, here's a layout that defines a title bar to be included in each activity (titlebar.xml):

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/titlebar_bg"
    tools:showIn="@layout/activity_main" >

    <ImageView android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:src="@drawable/gafricalogo" />
</FrameLayout>

The root View should be exactly how you'd like it to appear in each layout to which you add this layout.

Use the include Tag

Inside the layout to which you want to add the re-usable component, add the  tag. For example, here's a layout that includes the title bar from above:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/app_bg"
    android:gravity="center_horizontal">

    <include layout="@layout/titlebar"/>

    <TextView android:layout_width="match_parent"
              android:layout_height="wrap_content"
              android:text="@string/hello"
              android:padding="10dp" />

    ...

</LinearLayout>

Source: https://developer.android.com/training/improving-layouts/reusing-layouts.html#Include


问:
How can i grab pdf links from website with Python script
Quite often i have to download the pdfs from websites but sometimes they are not on one page.
They have divided the links in pagination and I have to click on every page of get the links.

I am learning python and i want to code some script where i can put the weburl and it extracts the pdf links from that webiste.

I am new to python so can anyone please give me the directions how can i do it

答:
By phone, maybe it is not very readable

If you is going to gran things from website which are all static pages or other things. You can easily grab html by requests

```<code>import requests
page_content=requests.get(url)
</code>```

But if you grab things like some communication website. There will be some anti-grabing ways.(how to break these noisy things will be the problem)

Frist way:make your requests more like a browser(human).
add the headers(you can use the dev tools by Chrome or Fiddle to copy the headers)
make the right post form.This one should copy the ways you post the form by browser.
get the cookies, and add it to requests

Second way. use selenium and browser driver. Selenium will use true browser driver(like me, i use chromedriver)
 remeber to add chromedriver to the path
 Or use code to load the driver.exe
driver=WebDriver.Chrome(path)
not sure is this set up code

driver.get(url)
It is trully surf the url by browser, so it will decrease the difficulty of grabing things

get the web page
page=driver.page_soruces

some of the website will jump several page. This will cause some error. Make your website wait for some certain element showing.

try:
     certain_element=ExpectedConditions.presenceOfElementLocated(By.id,'youKnowThereIsAElement'sID)
  WebDriverWait(certain_element)

or  use implict wait:  wait the time you like

driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS)

And you can controll the website by WebDriver. Here is not going to describe. You can search the module.

ContentLicense: CC BY-SA 4.0

Body:
By phone, maybe it is not very readable

If you is going to gran things from website which are all static pages or other things. You can easily grab html by requests

import requests
page_content=requests.get(url)

But if you grab things like some communication website. There will be some anti-grabing ways.(how to break these noisy things will be the problem)

Frist way:make your requests more like a browser(human).
add the headers(you can use the dev tools by Chrome or Fiddle to copy the headers)
make the right post form.This one should copy the ways you post the form by browser.
get the cookies, and add it to requests

Second way. use selenium and browser driver. Selenium will use true browser driver(like me, i use chromedriver)
 remeber to add chromedriver to the path
 Or use code to load the driver.exe
driver=WebDriver.Chrome(path)
not sure is this set up code

driver.get(url)
It is trully surf the url by browser, so it will decrease the difficulty of grabing things

get the web page
page=driver.page_soruces

some of the website will jump several page. This will cause some error. Make your website wait for some certain element showing.

try:
     certain_element=ExpectedConditions.presenceOfElementLocated(By.id,'youKnowThereIsAElement'sID)
  WebDriverWait(certain_element)

or  use implict wait:  wait the time you like

driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS)

And you can controll the website by WebDriver. Here is not going to describe. You can search the module.


问:
Is it okay to declare angular services, controllers etc in angular in a Typescript project?
I am currently learning typescript with angular 2. In the tutorial mostly angular 2 services, factories, controllers are implemented using typescript, which are complex to implement. I feel its easier to implement services and controllers without only using Angular and not typescript. So is it important to learn to implement using typescript or I am better off implementing them in angular itself?
I am asking if the angular can be used in javascript and explicitly not in typescript. I am asking if is it okay to not use typescript(i.e modules, namespaces etc) while declaring angular function in a typescript project.</p>

答: You can use plain JavaScript as well if you are comfortable with that. But its better to use typescript as all new versions of angular are mainly written in Typescript. Angular 2 documentation is available in both JavaScript as well as typescript. Happy coding!</p>


问:
best way for sorting some arrays
I have some array:

```<code>trade_prices[n]
trade_volumes[n]
trade_dates[n]
trade_tickers[n]
</code>```

and I want to sort them by tickers and then by dates.

how can I sort them?

答:
Define inner class Trade like this.

```<code>int n = 10;
int[] trade_prices = new int[n];
int[] trade_volumes = new int[n];
Date[] trade_dates = new Date[n];
String[] trade_tickers = new String[n];
// fill data...
class Trade {
    final int i;
    Trade(int i) { this.i = i; }
    int price() { return trade_prices[i]; }
    int volume() { return trade_volumes[i]; }
    Date date() { return trade_dates[i]; }
    String ticker() { return trade_tickers[i]; }
}
Trade[] trades = IntStream.range(0, n)
    .mapToObj(Trade::new)
    .sorted(Comparator.comparing(Trade::ticker).thenComparing(Trade::date))
    .toArray(Trade[]::new);
</code>```

Then you can get sorted first price as trades[0].price().
Original arrays are not changed.

Title: best way for sorting some arrays

Body:
I have some array:

trade_prices[n]
trade_volumes[n]
trade_dates[n]
trade_tickers[n]

and I want to sort them by tickers and then by dates.

how can I sort them?

Body:
Define inner class Trade like this.

int n = 10;
int[] trade_prices = new int[n];
int[] trade_volumes = new int[n];
Date[] trade_dates = new Date[n];
String[] trade_tickers = new String[n];
// fill data...
class Trade {
    final int i;
    Trade(int i) { this.i = i; }
    int price() { return trade_prices[i]; }
    int volume() { return trade_volumes[i]; }
    Date date() { return trade_dates[i]; }
    String ticker() { return trade_tickers[i]; }
}
Trade[] trades = IntStream.range(0, n)
    .mapToObj(Trade::new)
    .sorted(Comparator.comparing(Trade::ticker).thenComparing(Trade::date))
    .toArray(Trade[]::new);

Then you can get sorted first price as trades[0].price().
Original arrays are not changed.


问:
How to use HM-10/HC-08 in AT command mode?
I have bought HM-10 but its name is showing HC-08. I want to know how will i use it in AT mode. I have arduino mega. I am using HC-05 in AT mode by setting 34th(key) pin high. </p>

答:
For HM-10 or HC-08 there are several AT commands lists (access via serial).

For example for the HC-08:

AT responds OK

AT + BAUDx responds with OKn where x is 1 - n is 1200, 2 - 2400, 3 -
4800, 4 - 9600 (default), 5 - 19200, 6 - 38400, 7 - 57600, 8 -
115200.

Note: module must be reset after power-on for the new serial port baud rate to take effect.

AT + NAME name responds OKsetname - name is the Bluetooth device name to be set and must be 13 characters or fewer. Retained across power offs.

Note: module must be reset after power-on for the new device name to take effect.

You can find complete lists if you search to "HC-08 AT commands list" in the web.


问:
Extracting geometry in geopandas (worldmap) into my dataframe
My dataframe has a country name but not the location (coordinates) so I am trying to extract that from geopandas worldmap. Does anyone know how to get the geometry column from world geopandans to match with the country name of my drink.csv dataframe in order to create a new column in my drinks.csv

world data from geopandas

my data set = drinks.csv

![[1]: https://i.stack.imgur.com/v0qp8.jpg
  [2]:]2 https://i.stack.imgur.com/UGr3O.jpg

答:
I would suggest you use indexing and slicing with column values:</p>

```<code># set index of the country shapes to the name of the country
country_shapes_newindex = country_shapes.set_index('name')

# slice on the country shapes using the names of the countries from your drinks dataframe.
# the result is a DataFrame, select the geomtry column, and get their values.
# finally store this in a new column in your drinks DataFrame
drinks['geometry'] = country_shapes_newindex.loc[drinks['Country'].values]['geometry'].values
</code>```

Body:
I would suggest you use indexing and slicing with column values:

# set index of the country shapes to the name of the country
country_shapes_newindex = country_shapes.set_index('name')

# slice on the country shapes using the names of the countries from your drinks dataframe.
# the result is a DataFrame, select the geomtry column, and get their values.
# finally store this in a new column in your drinks DataFrame
drinks['geometry'] = country_shapes_newindex.loc[drinks['Country'].values]['geometry'].values


答:
Pointer arithmetic is still valid arithmetic ;-)

And as in valid arithmetic, it holds that (x+1)-x = x - x + 1 = 1.

So in your case (a+1) means not pointer to second element of an array, but pointer to the byte after the end of the array.

ContentLicense: CC BY-SA 2.5

Title: How to understand the output?

Body:
int a[2][3];
cout << a+1 << " " << a << " " << (a+1) - a << endl;

Output:

0029FAC0 0029FAB4 1

Shouldn't (a+1)-a be 0029FAC0-0029FAB4=12 ?


问:
Dotnet isn't aware of environment specific appsettings file
First of all this question is not same issue with dotnet publish doesn´t publish correct appsettings.{env.EnvironmentName}.json and i am sure there is no problem with name of environment.

os: linux(ubuntu 14.04)

dotnet --version: 1.0.3

Shell script:

export ASPNETCORE_ENVIRONMENT=Cloud9

cd ../../src/Project

dotnet restore

dotnet publish -c Debug -o bin/Debug/out/

cp ../../.config/Project /appsettings.Cloud9.json bin/Debug/out/     #copy settings file into publish directory

dotnet bin/Debug/out/Project.dll --urls "http://0.0.0.0:8080"

When i run above script it successfully serves site but with appsettings.json values instead of appsettings.Cloud9.json.

Here is my Startup.cs constructor and Program.cs:

```<code>    //Sturtup.cs
    public IConfigurationRoot Configuration { get; }
    public Startup(ILoggerFactory loggerFactory, IHostingEnvironment environment)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(environment.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"appsettings.{environment.EnvironmentName}.json", optional: true);

        builder.AddEnvironmentVariables();
        Configuration = builder.Build();
    }

    //Program.cs
    public static void Main(string[] args)
    {
        var config = new ConfigurationBuilder()
            .AddCommandLine(args)
            .Build();
        var host = new WebHostBuilder()
            .UseKestrel()
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseStartup<Startup>()
            .UseConfiguration(config)
            .Build();

        host.Run();
    }
</code>```

A note: if i execute dotnet run --urls ... without publish it runs as expected.

Second note: i see appsettings.Cloud9.json in the out directory.

答:
Solved after adding cd ./bin/Debug/out. So correct script is:

```<code>export ASPNETCORE_ENVIRONMENT=Cloud9
cd ../../src/Project
dotnet restore
dotnet publish -c Debug -o bin/Debug/out/
cp ../../.config/Project /appsettings.Cloud9.json bin/Debug/out/
</code>```

Key point:

```<code>cd ./bin/Debug/out
dotnet Project.dll --urls "http://0.0.0.0:8080"
</code>```

Body:
First of all this question is not same issue with dotnet publish doesn´t publish correct appsettings.{env.EnvironmentName}.json and i am sure there is no problem with name of environment.

os: linux(ubuntu 14.04)

dotnet --version: 1.0.3

Shell script:

export ASPNETCORE_ENVIRONMENT=Cloud9

cd ../../src/Project

dotnet restore

dotnet publish -c Debug -o bin/Debug/out/

cp ../../.config/Project /appsettings.Cloud9.json bin/Debug/out/     #copy settings file into publish directory

dotnet bin/Debug/out/Project.dll --urls "http://0.0.0.0:8080"

When i run above script it successfully serves site but with appsettings.json values instead of appsettings.Cloud9.json.

Here is my Startup.cs constructor and Program.cs:

    //Sturtup.cs
    public IConfigurationRoot Configuration { get; }
    public Startup(ILoggerFactory loggerFactory, IHostingEnvironment environment)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(environment.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"appsettings.{environment.EnvironmentName}.json", optional: true);

        builder.AddEnvironmentVariables();
        Configuration = builder.Build();
    }

    //Program.cs
    public static void Main(string[] args)
    {
        var config = new ConfigurationBuilder()
            .AddCommandLine(args)
            .Build();
        var host = new WebHostBuilder()
            .UseKestrel()
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseStartup<Startup>()
            .UseConfiguration(config)
            .Build();

        host.Run();
    }

A note: if i execute dotnet run --urls ... without publish it runs as expected.

Second note: i see appsettings.Cloud9.json in the out directory.

Body:
Solved after adding cd ./bin/Debug/out. So correct script is:

export ASPNETCORE_ENVIRONMENT=Cloud9
cd ../../src/Project
dotnet restore
dotnet publish -c Debug -o bin/Debug/out/
cp ../../.config/Project /appsettings.Cloud9.json bin/Debug/out/

Key point:

cd ./bin/Debug/out
dotnet Project.dll --urls "http://0.0.0.0:8080"


问:
React Native - Error calling AppRegistry.runApplication
When I run a simple "AwesomeProject" app as stated in React Native Getting started page, the app runs on Nexus6 API 23 but error  is shown. I also tried the following methods to solve the error:

adb reverse tcp:8081 tcp:8081, but doesn't work.

"react-native start" in command line before running the app but it does not show anything after "Loading Dependency Graph, done."

Running it on Nexus5X API 25 but still error occurs.
How do I solve it?

答:
I found out that by typing:
react-native start --port 8081
in the command line, and running app by opening another cmd shell, I was able to run the app successfully. Thanks.</p>


问:
php - Data does not insert into table using checkbox
the checkbox is not working.. I could not insert new data into the table
there is nothing happen when I click the "add to cart" button.

```<code><div class="carousel-inner">
<div class="item">
<ul class="thumbnails">
<?php

$query = mysql_query("SELECT * FROM product where pro_category='3' LIMIT 0,4 ");

while ($data = mysql_fetch_assoc($query)):
?>
<li class="span3">
<div class="product-box">
<span class="sale_tag"></span>
<?php echo '<p><a href="product_det.php?id='.$data['code'].'"><img src="admin/pro_image/'.$data['image'].'" /></a></p>'; ?>
<?php echo '<a href="product_det.php?id='.$data['code'].'" class="title">'.$data['name_nl'].'</a>'; ?>
<br/>

<td><input class='minuman' type='checkbox' name='add[]' value='<?php echo '<a class="btn btn-success" href="cart.php?add='.$data['code'].'" class="category">
</a>'; ?>'></td>
<p class="price"><?php echo 'RM '.$data['price']; ?></p>
</div>
</li>
<?php endwhile; ?>
</ul>
</div>
</div>

<ul class="thumbnails" align="center">
<div id="single_product" align="center">

<?php echo '<a class="btn btn-success" href="cart.php?add='.$data['code'].'" class="category">Add to Cart</a>'; ?>

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

this is my code for insert cart:

```<code>if(isset($_GET['add'])){
    $id = $_GET['add'];
    $qt = mysql_query("SELECT code, quantity FROM product WHERE code='$id'");
    while($qt_row = mysql_fetch_assoc($qt)){
        if($qt_row['quantity'] != $_SESSION['cart_'.$_GET['add']] && $qt_row['quantity'] > 0){
            $_SESSION['cart_'.$_GET['add']]+='1';
            header("Location: keranjang.php");
        } else {
            echo '<script language="javascript">alert("Stok produk tidak mencukupi!"); document.location="index.php";</script>';
        }
    }
}
</code>```

答:
According to PHP Documentation, mysql_query is deprecated since PHP 5.5.0, and removed in PHP 7.0.0. You may use mysqli or PDO instead.

This row might cause problems, because it's not escaped:

```<code><td><input class='minuman' type='checkbox' name='add[]' value='<?php echo '<a class="btn btn-success" href="cart.php?add='.$data['code'].'" class="category">
</a>'; ?>'></td>
</code>```

and this is one of the ways to escape:

```<code><td>
    <input class="minuman" type="checkbox" name="add[]" value="<?php echo '<a class="btn btn-success" href="cart.php?add=' . $data['code'] . '" class="category"></a>'; ?>" />
</td>
</code>```

About "add to cart" - You can store the products in the session or in a cookie (I think cookies can be a better option), and then show them in the cart.

Body:
the checkbox is not working.. I could not insert new data into the table
there is nothing happen when I click the "add to cart" button.

<?php

$query = mysql_query("SELECT * FROM product where pro_category='3' LIMIT 0,4 ");

while ($data = mysql_fetch_assoc($query)):
?>

<?php echo '

'; ?>
<?php echo ''.$data['name_nl'].''; ?>

<input class='minuman' type='checkbox' name='add[]' value='<?php echo '
'; ?>'>

<?php echo 'RM '.$data['price']; ?>

<?php endwhile; ?>

<?php echo 'Add to Cart'; ?>

this is my code for insert cart:

if(isset($_GET['add'])){
    $id = $_GET['add'];
    $qt = mysql_query("SELECT code, quantity FROM product WHERE code='$id'");
    while($qt_row = mysql_fetch_assoc($qt)){
        if($qt_row['quantity'] != $_SESSION['cart_'.$_GET['add']] && $qt_row['quantity'] > 0){
            $_SESSION['cart_'.$_GET['add']]+='1';
            header("Location: keranjang.php");
        } else {
            echo '';
        }
    }
}

Body:
According to PHP Documentation, mysql_query is deprecated since PHP 5.5.0, and removed in PHP 7.0.0. You may use mysqli or PDO instead.

This row might cause problems, because it's not escaped:

<td><input class='minuman' type='checkbox' name='add[]' value='<?php echo '<a class="btn btn-success" href="cart.php?add='.$data['code'].'" class="category">
</a>'; ?>'></td>

and this is one of the ways to escape:

<td>
    <input class="minuman" type="checkbox" name="add[]" value="<?php echo '&lt;a class="btn btn-success" href="cart.php?add=' . $data['code'] . '" class="category"&gt;&lt;/a&gt;'; ?>" />
</td>

About "add to cart" - You can store the products in the session or in a cookie (I think cookies can be a better option), and then show them in the cart.


问:
Why does my PHP email come without HTML and utf-8?
I have a contact form and want to format the output email in HTML and use charset utf-8 as I need some special character. I have following code, but it's not working.
Edit: The email is sent, but without html and utf-8.</p>

```<code><?php
if ($_POST["email"]<>'') {
    $ToEmail = 'contact@domain.com';
    $EmailSubject = 'Email Subject';
    $mailheader = 'From: donotreply@domain.com' . "\r\n" .
        'Reply-To:' .$_POST["email"]. "\r\n" .
        'X-Mailer: PHP/' . phpversion();
        'MIME-Version: 1.0'."\r\n".
        'Content-Type: text/html; charset=utf-8'."\r\n".
    $MESSAGE_BODY .= "<b>Navn:</b> ".$_POST["name"]."\r\n";
    $MESSAGE_BODY .= "<b>Telefon:</b> ".$_POST["telephone"]."\r\n";
    $MESSAGE_BODY .= "<b>Email:</b> ".$_POST["email"]."\r\n\r\n";
    $MESSAGE_BODY .= "".nl2br($_POST["message"])."\r\n";
    mail($ToEmail, $EmailSubject, $MESSAGE_BODY, $mailheader) or die ("Failure");
?>
</code>```

答:
Try changing header from

```<code>$headers .= "Content-Type: text/html; charset=UTF-8\r\n";
to
$headers .= "Content-Type: text/html; charset=iso-8859-1\r\n";
</code>```

Its better use PHPMailer This will allow you to send mails via a SMTP server

Body:
I have a contact form and want to format the output email in HTML and use charset utf-8 as I need some special character. I have following code, but it's not working.
Edit: The email is sent, but without html and utf-8.

<?php
if ($_POST["email"]<>'') {
    $ToEmail = 'contact@domain.com';
    $EmailSubject = 'Email Subject';
    $mailheader = 'From: donotreply@domain.com' . "\r\n" .
        'Reply-To:' .$_POST["email"]. "\r\n" .
        'X-Mailer: PHP/' . phpversion();
        'MIME-Version: 1.0'."\r\n".
        'Content-Type: text/html; charset=utf-8'."\r\n".
    $MESSAGE_BODY .= "Navn: ".$_POST["name"]."\r\n";
    $MESSAGE_BODY .= "Telefon: ".$_POST["telephone"]."\r\n";
    $MESSAGE_BODY .= "Email: ".$_POST["email"]."\r\n\r\n";
    $MESSAGE_BODY .= "".nl2br($_POST["message"])."\r\n";
    mail($ToEmail, $EmailSubject, $MESSAGE_BODY, $mailheader) or die ("Failure");
?>

Body:
Try changing header from

$headers .= "Content-Type: text/html; charset=UTF-8\r\n";
to
$headers .= "Content-Type: text/html; charset=iso-8859-1\r\n";

Its better use PHPMailer This will allow you to send mails via a SMTP server


问:
Meteor JS ReactMeteorData - CreateContainer - Super expression must either be null or a function
After upgrading to Meteor 1.5 from 1.4, createContainer function from react-meteor-data gives the following error:

```<code>Uncaught TypeError: Super expression must either be null or a function, not undefined
    at exports.default (modules.js?hash=fb99b6a…:1144)
    at ReactMeteorData.jsx:6
    at ReactMeteorData.jsx:6
    at createContainer (createContainer.jsx:16)
    at AppContainer.jsx (AppContainer.jsx:8)
</code>```

AppContainer.jsx:

```<code>import { Meteor } from 'meteor/meteor';

import { Session } from 'meteor/session';
import { createContainer } from 'meteor/react-meteor-data';

import App from '../layouts/App.jsx';

export default AppContainer = createContainer(props => {
  return {
    currentUser: Meteor.user(),
  };
}, App);
</code>```

App file below, in constructor i am performing super(props) however error is still thrown

App.jsx:

```<code>class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      menuOpen: false,
      showConnectionIssue: false,
      headerTitle: null,
    };
    this.setHeaderTitle = this.setHeaderTitle.bind(this);
    this.logout = this.logout.bind(this);
  }

  logout() {
    Meteor.logout();
    this.context.router.replace(`/home`);
  }

  render() {
    ... omitted render function
  }
}

App.propTypes = {
  user: React.PropTypes.object,      // current meteor user
  connected: React.PropTypes.bool,   // server connection status
  loading: React.PropTypes.bool,     // subscription status
  menuOpen: React.PropTypes.bool,    // is side menu open?
  children: React.PropTypes.element, // matched child route component
  location: React.PropTypes.object,  // current router location
  params: React.PropTypes.object,    // parameters of the current route
};

App.contextTypes = {
  router: React.PropTypes.object,
};

export default App;
</code>```

答:
Try following snippet:</p>

```<code>export default AppContainer = createContainer((props) => {
  // do subscriptions if you have any
  return {
    currentUser: Meteor.user(),
  };
}, App);
</code>```

Body:
After upgrading to Meteor 1.5 from 1.4, createContainer function from react-meteor-data gives the following error:

Uncaught TypeError: Super expression must either be null or a function, not undefined
    at exports.default (modules.js?hash=fb99b6a…:1144)
    at ReactMeteorData.jsx:6
    at ReactMeteorData.jsx:6
    at createContainer (createContainer.jsx:16)
    at AppContainer.jsx (AppContainer.jsx:8)

AppContainer.jsx:

import { Meteor } from 'meteor/meteor';

import { Session } from 'meteor/session';
import { createContainer } from 'meteor/react-meteor-data';

import App from '../layouts/App.jsx';

export default AppContainer = createContainer(props => {
  return {
    currentUser: Meteor.user(),
  };
}, App);

App file below, in constructor i am performing super(props) however error is still thrown

App.jsx:

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      menuOpen: false,
      showConnectionIssue: false,
      headerTitle: null,
    };
    this.setHeaderTitle = this.setHeaderTitle.bind(this);
    this.logout = this.logout.bind(this);
  }

  logout() {
    Meteor.logout();
    this.context.router.replace(`/home`);
  }

  render() {
    ... omitted render function
  }
}

App.propTypes = {
  user: React.PropTypes.object,      // current meteor user
  connected: React.PropTypes.bool,   // server connection status
  loading: React.PropTypes.bool,     // subscription status
  menuOpen: React.PropTypes.bool,    // is side menu open?
  children: React.PropTypes.element, // matched child route component
  location: React.PropTypes.object,  // current router location
  params: React.PropTypes.object,    // parameters of the current route
};

App.contextTypes = {
  router: React.PropTypes.object,
};

export default App;

Body:
Try following snippet:

export default AppContainer = createContainer((props) => {
  // do subscriptions if you have any
  return {
    currentUser: Meteor.user(),
  };
}, App);


问:
Add My Order link active in customer account
Right now in default magento when customer login into his/her account then Active menu shown to customer is Account Dashboard

I want to show My orders when customer login into account.
I used this peace of code.

```<code><customer_account>
<reference name="customer_account_navigation">
            <action method="setActive"><name>orders</name><path>sales/order/history/</path></action>
        </reference>
</customer_account>
</code>```

but it didn't work. Please suggest me any solution or give me an alternate idea to do that.

答:
you can try below code in controller.

```<code>$this->loadLayout();

// add layout handle so that we will have the customer navigation on the right hand side

    $layout = $this->getLayout();
    $update = $layout->getUpdate();
    $this->addActionLayoutHandles();
    $update->addHandle('customer_account'); // add the customer navigation bar on the side
    $this->loadLayoutUpdates();
    $this->generateLayoutXml();
    $this->generateLayoutBlocks();
    $navigationBlock = $layout->getBlock('customer_account_navigation');
    // make sure we have an instantiation
    if ($navigationBlock) {
        $navigationBlock->setActive('path/to/highlight'); // example: 'customer/address'
    }
    $this->_isLayoutLoaded = true;

    // render the layout
    $this->renderLayout();
</code>```

So, please try this and let me know in case of any query.

Thanks

Body:
Right now in default magento when customer login into his/her account then Active menu shown to customer is Account Dashboard

I want to show My orders when customer login into account.
I used this peace of code.

<customer_account>
<reference name="customer_account_navigation">
            <action method="setActive"><name>orders</name><path>sales/order/history/</path></action>
        </reference>
</customer_account>

but it didn't work. Please suggest me any solution or give me an alternate idea to do that.

Body:
you can try below code in controller.

$this->loadLayout();

// add layout handle so that we will have the customer navigation on the right hand side

    $layout = $this->getLayout();
    $update = $layout->getUpdate();
    $this->addActionLayoutHandles();
    $update->addHandle('customer_account'); // add the customer navigation bar on the side
    $this->loadLayoutUpdates();
    $this->generateLayoutXml();
    $this->generateLayoutBlocks();
    $navigationBlock = $layout->getBlock('customer_account_navigation');
    // make sure we have an instantiation
    if ($navigationBlock) {
        $navigationBlock->setActive('path/to/highlight'); // example: 'customer/address'
    }
    $this->_isLayoutLoaded = true;

    // render the layout
    $this->renderLayout();

So, please try this and let me know in case of any query.

Thanks


问:
How do i select multiple rows which match the value of an item in an array?
I have written a php script that returns an arbitrary number of specific ids (which are in the format of numbers) in an array. I would like to make a new query that selects each row from a table that belongs to each id. I know i can do 1 query to get one row with the matching id. But i would like to do this all in one query. Here is my code:</p>

```<code>$id = array(1,4,7,3,11,120); // The array containing the ids

$query = mysql_query("SELECT *
                        FROM posts
                       WHERE id = '$id[0]'");
// I would like to Do this for each id in the array and return it as one group of rows.`
</code>```

答:
Use PHP's implode function to convert the array into a comma separated value string.

Then, you can use the SQL IN clause to run a single SQL statement containing the values associated with the ids you captured from PHP:

```<code>$id = array(1,4,7,3,11,120);
$csv = implode(',', $id);

$query = sprintf("SELECT *
                    FROM posts
                   WHERE id IN (%s)",
                  mysql_real_escape_string($csv));

$result = mysql_query($query)
</code>```

I omitted the single quotes because they aren't necessary when dealing with numeric values in SQL.  If the id values were strings, each would have to be encapsulated inside of single quotes.

Body:
I have written a php script that returns an arbitrary number of specific ids (which are in the format of numbers) in an array. I would like to make a new query that selects each row from a table that belongs to each id. I know i can do 1 query to get one row with the matching id. But i would like to do this all in one query. Here is my code:

$id = array(1,4,7,3,11,120); // The array containing the ids

$query = mysql_query("SELECT *
                        FROM posts
                       WHERE id = '$id[0]'");
// I would like to Do this for each id in the array and return it as one group of rows.`

Body:
Use PHP's implode function to convert the array into a comma separated value string.

Then, you can use the SQL IN clause to run a single SQL statement containing the values associated with the ids you captured from PHP:

$id = array(1,4,7,3,11,120);
$csv = implode(',', $id);

$query = sprintf("SELECT *
                    FROM posts
                   WHERE id IN (%s)",
                  mysql_real_escape_string($csv));

$result = mysql_query($query)

I omitted the single quotes because they aren't necessary when dealing with numeric values in SQL.  If the id values were strings, each would have to be encapsulated inside of single quotes.


问:
Semimagic Square
I have to create function which generate random NxN magic square with all sums of columns and rows equal to S. Variables N and S have to be users input. I've already create function which draws squares and breaks the loop when meet given conditions. It's working fine for small squars like 3x3 or 4x4 but it`s extremly unefficient for larger ones. All numbers inside the matrix have to be integer, there is no need diagonals be equal rows sums.
Any suggestion how to solve this problem? </p>

答:
As any magic square is a semimagic one too (which doesn't have to have diagonals to sum up to the magic constant), to answer the question it's enough to provide an efficient algorithm for generating truly magic squares. One of classical algorithms to solve magic squares is the following (citation by Robin K. S. Hankin):

In a square of order 4m, shade the long major diagonal. Then shade all
major diagonals distant by a multiple of 4 cells from the long
diagonal. Do the same with the minor diagonals. Then, starting with
“1” at the top left corner and proceeding from left to right and top
to bottom, count from 1 to n^2, filling in the shaded squares with the
appropriate number and omitting the unshaded ones. Fill in the
remaining (unshaded) squares in the same way, starting at the lower
right corner, moving leftwards and upward.

You might find R package magic a useful resource for studying efficient magic square generation algorithms. It becomes clear from the package sources that the problem can be divided into three separate cases:

```<code>"magic" <-
function (n)
{
    if(length(n)>1){
      return(sapply(n,match.fun(sys.call()[[1]])))
    }
    n <- round(n)
    if (n == 2) {
        stop("Normal magic squares of order 2 do not exist")
    }
    if (n%%2 == 1) {
        return(as.standard(magic.2np1(floor(n/2))))
    }
    if (n%%4 == 0) {
        return(as.standard(magic.4n(round(n/4))))
    }
    if (n%%4 == 2) {
        return(as.standard(magic.4np2(round((n - 2)/4))))
    }
    stop("This cannot happen")
}
</code>```

The execution time of magic is surprisingly small even for large n:

```<code>> system.time(result <- magic(2017))
   user  system elapsed
  1.256   0.316   1.573
</code>```

Finally, if you really want just a semimagic square instead of a truly magic one, you can always exchange any two columns of resulting square matrix. This operation wouldn't affect sums in rows and columns, but will definitely break sums of diagonals.

Title: Semimagic Square

Body:
As any magic square is a semimagic one too (which doesn't have to have diagonals to sum up to the magic constant), to answer the question it's enough to provide an efficient algorithm for generating truly magic squares. One of classical algorithms to solve magic squares is the following (citation by Robin K. S. Hankin):

In a square of order 4m, shade the long major diagonal. Then shade all
major diagonals distant by a multiple of 4 cells from the long
diagonal. Do the same with the minor diagonals. Then, starting with
“1” at the top left corner and proceeding from left to right and top
to bottom, count from 1 to n^2, filling in the shaded squares with the
appropriate number and omitting the unshaded ones. Fill in the
remaining (unshaded) squares in the same way, starting at the lower
right corner, moving leftwards and upward.

You might find R package magic a useful resource for studying efficient magic square generation algorithms. It becomes clear from the package sources that the problem can be divided into three separate cases:

"magic" <-
function (n)
{
    if(length(n)>1){
      return(sapply(n,match.fun(sys.call()[[1]])))
    }
    n <- round(n)
    if (n == 2) {
        stop("Normal magic squares of order 2 do not exist")
    }
    if (n%%2 == 1) {
        return(as.standard(magic.2np1(floor(n/2))))
    }
    if (n%%4 == 0) {
        return(as.standard(magic.4n(round(n/4))))
    }
    if (n%%4 == 2) {
        return(as.standard(magic.4np2(round((n - 2)/4))))
    }
    stop("This cannot happen")
}

The execution time of magic is surprisingly small even for large n:

> system.time(result <- magic(2017))
   user  system elapsed
  1.256   0.316   1.573

Finally, if you really want just a semimagic square instead of a truly magic one, you can always exchange any two columns of resulting square matrix. This operation wouldn't affect sums in rows and columns, but will definitely break sums of diagonals.


问:
Customer Order Totals
How would I execute a sub that allows me to determine a customer as defined by their (customer ID) to determine how much they have spent in total for over ($3000). As well as find the total spent by each  customer on the list and reports those whose total is more than the amount provided by the user on a new worksheet (Ex $3000) into a sheet that produces how much each customer spent along with their total amount spent to the right in a different cell.

Example of data:

current:

```<code>Sub test()

Sheets.Add after:=Sheets(Sheets.Count)
Sheets(ActiveSheet.Name).Name = "Report"

Lastrow = Sheets("Data").UsedRange.Rows.Count

Sheets("Data").Range("B3:B" & Lastrow).Copy

With Sheets("Report")
    .Range("A1").PasteSpecial Paste:=xlPasteValues
    .Activate
    .Range("B1").Select
    .Range(Range("A1"), Range("A1").End(xlDown)).RemoveDuplicates Columns:=1, Header:=xlYes
    .Cells(1, 2).Value = "Subtotal"
End With

For i = 2 To ActiveSheet.UsedRange.Rows.Count
    Cells(i, 2).Value = Application.WorksheetFunction.SumIf(Sheets("Data").Range("B:B"), "=" & Cells(i, 1).Value, Sheets("Data").Range("C:C"))

Next

For i = ActiveSheet.UsedRange.Rows.Count To 2 Step -1
    If Cells(i, 2).Value < 3000 Then
        Cells(i, 2).EntireRow.Delete
    End If
Next

Sheets("Report").Range("A1:B" & ActiveSheet.UsedRange.Rows.Count).Sort KEY1:=Range("B1:B" & ActiveSheet.UsedRange.Rows.Count), Order1:=xlAscending, Header:=xlYes

End Sub
</code>```

答:
The following will do the trick.  I have not used dynamic ranges for the sake of saving me typing more, but these can be done.

```<code>Sub CustomerSpending(cusID as Integer, overAmount as Double)

  'Point it at the correct worksheet where your data is.  Don't use Activesheet
  Dim ws as Worksheet
  Set ws = Thisworkbook.Worksheets("Your Worksheet Name")

  Dim TotalCustomerSpend as Double 'This is your final figure

  'Loop through every ID in the list of data
  For Each ID In ws.Range("Specify Your column and range here")
    'Check if the ID matches the one you are looking for
    If ID = cusID Then
      'Look at the column 1 accross from the ID (The spending amount)
      'Check if the spending amount is greater than the amount you specified
      If ID.Offset(0,1).Value > overAmount Then
        'If the amount is greater than what you specified then add it to the total
        TotalCustomerSpend = TotalCustomerSpend + ID.Offset(0,1).Value
      End If
    End If
  Next ID
</code>```

You can then call the sub with

```<code>Call CustomerSpending(192,3000.00)
</code>```

This will return a sum of all spending for customer 192 over $3000.  For all spending do the following

```<code>Call CustomerSpending(192,0)
</code>```

Which will report all spending by 192 over $0

Title: Customer Order Totals

Body:
How would I execute a sub that allows me to determine a customer as defined by their (customer ID) to determine how much they have spent in total for over ($3000). As well as find the total spent by each  customer on the list and reports those whose total is more than the amount provided by the user on a new worksheet (Ex $3000) into a sheet that produces how much each customer spent along with their total amount spent to the right in a different cell.

Example of data:

current:

Sub test()

Sheets.Add after:=Sheets(Sheets.Count)
Sheets(ActiveSheet.Name).Name = "Report"

Lastrow = Sheets("Data").UsedRange.Rows.Count

Sheets("Data").Range("B3:B" & Lastrow).Copy

With Sheets("Report")
    .Range("A1").PasteSpecial Paste:=xlPasteValues
    .Activate
    .Range("B1").Select
    .Range(Range("A1"), Range("A1").End(xlDown)).RemoveDuplicates Columns:=1, Header:=xlYes
    .Cells(1, 2).Value = "Subtotal"
End With

For i = 2 To ActiveSheet.UsedRange.Rows.Count
    Cells(i, 2).Value = Application.WorksheetFunction.SumIf(Sheets("Data").Range("B:B"), "=" & Cells(i, 1).Value, Sheets("Data").Range("C:C"))

Next

For i = ActiveSheet.UsedRange.Rows.Count To 2 Step -1
    If Cells(i, 2).Value < 3000 Then
        Cells(i, 2).EntireRow.Delete
    End If
Next

Sheets("Report").Range("A1:B" & ActiveSheet.UsedRange.Rows.Count).Sort KEY1:=Range("B1:B" & ActiveSheet.UsedRange.Rows.Count), Order1:=xlAscending, Header:=xlYes

End Sub

Body:
The following will do the trick.  I have not used dynamic ranges for the sake of saving me typing more, but these can be done.

Sub CustomerSpending(cusID as Integer, overAmount as Double)

  'Point it at the correct worksheet where your data is.  Don't use Activesheet
  Dim ws as Worksheet
  Set ws = Thisworkbook.Worksheets("Your Worksheet Name")

  Dim TotalCustomerSpend as Double 'This is your final figure

  'Loop through every ID in the list of data
  For Each ID In ws.Range("Specify Your column and range here")
    'Check if the ID matches the one you are looking for
    If ID = cusID Then
      'Look at the column 1 accross from the ID (The spending amount)
      'Check if the spending amount is greater than the amount you specified
      If ID.Offset(0,1).Value > overAmount Then
        'If the amount is greater than what you specified then add it to the total
        TotalCustomerSpend = TotalCustomerSpend + ID.Offset(0,1).Value
      End If
    End If
  Next ID

You can then call the sub with

Call CustomerSpending(192,3000.00)

This will return a sum of all spending for customer 192 over $3000.  For all spending do the following

Call CustomerSpending(192,0)

Which will report all spending by 192 over $0


问:
SSHKit::Runner::ExecuteError: Exception while executing on host
Trying to deploy a rails application to digital ocean following this tutorial:

https://www.digitalocean.com/community/tutorials/deploying-a-rails-app-on-ubuntu-14-04-with-capistrano-nginx-and-puma

but keep getting an error:
cap aborted!
SSHKit::Runner::ExecuteError: Exception while executing on host xxx.xx.xx.xx: connection closed by remote host. Need help have been at this for the past four hours

```<code>>> cap production deploy:initial --trace

    1 ↵
** Invoke production (first_time)
** Execute production
** Invoke load:defaults (first_time)
** Execute load:defaults
** Invoke bundler:map_bins (first_time)
** Execute bundler:map_bins
** Invoke deploy:set_rails_env (first_time)
** Execute deploy:set_rails_env
** Invoke deploy:set_rails_env
** Invoke rvm:hook (first_time)
** Execute rvm:hook
DEBUG [5976e045] Running /usr/bin/env [ -d ~/.rvm ] on xxx.xx.xx.xxx
DEBUG [5976e045] Command: [ -d ~/.rvm ]
cap aborted!
SSHKit::Runner::ExecuteError: Exception while executing on host xxx.xx.xx.xx: connection closed by remote host
/Users/andela/.rvm/gems/ruby-2.2.1/gems/sshkit-1.7.1/lib/sshkit/runners/parallel.rb:16:in `rescue in block (2 levels) in execute'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/sshkit-1.7.1/lib/sshkit/runners/parallel.rb:12:in `block (2 levels) in execute'
Net::SSH::Disconnect: connection closed by remote host
/Users/andela/.rvm/gems/ruby-2.2.1/gems/net-ssh-2.9.2/lib/net/ssh/transport/server_version.rb:50:in `rescue in block (2 levels) in negotiate!'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/net-ssh-2.9.2/lib/net/ssh/transport/server_version.rb:46:in `block (2 levels) in negotiate!'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/net-ssh-2.9.2/lib/net/ssh/transport/server_version.rb:45:in `loop'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/net-ssh-2.9.2/lib/net/ssh/transport/server_version.rb:45:in `block in negotiate!'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/net-ssh-2.9.2/lib/net/ssh/transport/server_version.rb:43:in `loop'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/net-ssh-2.9.2/lib/net/ssh/transport/server_version.rb:43:in `negotiate!'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/net-ssh-2.9.2/lib/net/ssh/transport/server_version.rb:32:in `initialize'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/net-ssh-2.9.2/lib/net/ssh/transport/session.rb:84:in `new'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/net-ssh-2.9.2/lib/net/ssh/transport/session.rb:84:in `block in initialize'
/Users/andela/.rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/timeout.rb:74:in `timeout'
/Users/andela/.rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/timeout.rb:125:in `timeout'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/net-ssh-2.9.2/lib/net/ssh/transport/session.rb:84:in `initialize'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/net-ssh-2.9.2/lib/net/ssh.rb:207:in `new'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/net-ssh-2.9.2/lib/net/ssh.rb:207:in `start'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/sshkit-1.7.1/lib/sshkit/backends/connection_pool.rb:50:in `call'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/sshkit-1.7.1/lib/sshkit/backends/connection_pool.rb:50:in `create_new_entry'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/sshkit-1.7.1/lib/sshkit/backends/connection_pool.rb:22:in `checkout'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/sshkit-1.7.1/lib/sshkit/backends/netssh.rb:187:in `with_ssh'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/sshkit-1.7.1/lib/sshkit/backends/netssh.rb:137:in `block in _execute'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/sshkit-1.7.1/lib/sshkit/backends/netssh.rb:133:in `tap'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/sshkit-1.7.1/lib/sshkit/backends/netssh.rb:133:in `_execute'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/sshkit-1.7.1/lib/sshkit/backends/netssh.rb:62:in `test'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/capistrano-rvm-0.1.2/lib/capistrano/tasks/rvm.rake:21:in `block (3 levels) in <top (required)>'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/sshkit-1.7.1/lib/sshkit/backends/netssh.rb:54:in `instance_exec'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/sshkit-1.7.1/lib/sshkit/backends/netssh.rb:54:in `run'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/sshkit-1.7.1/lib/sshkit/runners/parallel.rb:13:in `block (2 levels) in execute'
EOFError: end of file reached
/Users/andela/.rvm/gems/ruby-2.2.1/gems/net-ssh-2.9.2/lib/net/ssh/transport/server_version.rb:47:in `readpartial'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/net-ssh-2.9.2/lib/net/ssh/transport/server_version.rb:47:in `block (2 levels) in negotiate!'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/net-ssh-2.9.2/lib/net/ssh/transport/server_version.rb:45:in `loop'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/net-ssh-2.9.2/lib/net/ssh/transport/server_version.rb:45:in `block in negotiate!'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/net-ssh-2.9.2/lib/net/ssh/transport/server_version.rb:43:in `loop'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/net-ssh-2.9.2/lib/net/ssh/transport/server_version.rb:43:in `negotiate!'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/net-ssh-2.9.2/lib/net/ssh/transport/server_version.rb:32:in `initialize'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/net-ssh-2.9.2/lib/net/ssh/transport/session.rb:84:in `new'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/net-ssh-2.9.2/lib/net/ssh/transport/session.rb:84:in `block in initialize'
/Users/andela/.rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/timeout.rb:74:in `timeout'
/Users/andela/.rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/timeout.rb:125:in `timeout'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/net-ssh-2.9.2/lib/net/ssh/transport/session.rb:84:in `initialize'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/net-ssh-2.9.2/lib/net/ssh.rb:207:in `new'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/net-ssh-2.9.2/lib/net/ssh.rb:207:in `start'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/sshkit-1.7.1/lib/sshkit/backends/connection_pool.rb:50:in `call'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/sshkit-1.7.1/lib/sshkit/backends/connection_pool.rb:50:in `create_new_entry'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/sshkit-1.7.1/lib/sshkit/backends/connection_pool.rb:22:in `checkout'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/sshkit-1.7.1/lib/sshkit/backends/netssh.rb:187:in `with_ssh'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/sshkit-1.7.1/lib/sshkit/backends/netssh.rb:137:in `block in _execute'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/sshkit-1.7.1/lib/sshkit/backends/netssh.rb:133:in `tap'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/sshkit-1.7.1/lib/sshkit/backends/netssh.rb:133:in `_execute'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/sshkit-1.7.1/lib/sshkit/backends/netssh.rb:62:in `test'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/capistrano-rvm-0.1.2/lib/capistrano/tasks/rvm.rake:21:in `block (3 levels) in <top (required)>'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/sshkit-1.7.1/lib/sshkit/backends/netssh.rb:54:in `instance_exec'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/sshkit-1.7.1/lib/sshkit/backends/netssh.rb:54:in `run'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/sshkit-1.7.1/lib/sshkit/runners/parallel.rb:13:in `block (2 levels) in execute'
Tasks: TOP => rvm:hook
</code>```

答:
I had the same issue recently, I think there is a mistake in the tutorial.

Here's what I changed.

set :ssh_options, { forward_agent: true, user: fetch(:user), keys: %w(~/.ssh/id_rsa) }

I removed .pub from the id_rsa. And now I can deploy using the tutorial from Digital ocean.

Body:
Trying to deploy a rails application to digital ocean following this tutorial:

https://www.digitalocean.com/community/tutorials/deploying-a-rails-app-on-ubuntu-14-04-with-capistrano-nginx-and-puma

but keep getting an error:
cap aborted!
SSHKit::Runner::ExecuteError: Exception while executing on host xxx.xx.xx.xx: connection closed by remote host. Need help have been at this for the past four hours

>> cap production deploy:initial --trace

    1 ↵
** Invoke production (first_time)
** Execute production
** Invoke load:defaults (first_time)
** Execute load:defaults
** Invoke bundler:map_bins (first_time)
** Execute bundler:map_bins
** Invoke deploy:set_rails_env (first_time)
** Execute deploy:set_rails_env
** Invoke deploy:set_rails_env
** Invoke rvm:hook (first_time)
** Execute rvm:hook
DEBUG [5976e045] Running /usr/bin/env [ -d ~/.rvm ] on xxx.xx.xx.xxx
DEBUG [5976e045] Command: [ -d ~/.rvm ]
cap aborted!
SSHKit::Runner::ExecuteError: Exception while executing on host xxx.xx.xx.xx: connection closed by remote host
/Users/andela/.rvm/gems/ruby-2.2.1/gems/sshkit-1.7.1/lib/sshkit/runners/parallel.rb:16:in `rescue in block (2 levels) in execute'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/sshkit-1.7.1/lib/sshkit/runners/parallel.rb:12:in `block (2 levels) in execute'
Net::SSH::Disconnect: connection closed by remote host
/Users/andela/.rvm/gems/ruby-2.2.1/gems/net-ssh-2.9.2/lib/net/ssh/transport/server_version.rb:50:in `rescue in block (2 levels) in negotiate!'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/net-ssh-2.9.2/lib/net/ssh/transport/server_version.rb:46:in `block (2 levels) in negotiate!'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/net-ssh-2.9.2/lib/net/ssh/transport/server_version.rb:45:in `loop'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/net-ssh-2.9.2/lib/net/ssh/transport/server_version.rb:45:in `block in negotiate!'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/net-ssh-2.9.2/lib/net/ssh/transport/server_version.rb:43:in `loop'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/net-ssh-2.9.2/lib/net/ssh/transport/server_version.rb:43:in `negotiate!'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/net-ssh-2.9.2/lib/net/ssh/transport/server_version.rb:32:in `initialize'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/net-ssh-2.9.2/lib/net/ssh/transport/session.rb:84:in `new'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/net-ssh-2.9.2/lib/net/ssh/transport/session.rb:84:in `block in initialize'
/Users/andela/.rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/timeout.rb:74:in `timeout'
/Users/andela/.rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/timeout.rb:125:in `timeout'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/net-ssh-2.9.2/lib/net/ssh/transport/session.rb:84:in `initialize'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/net-ssh-2.9.2/lib/net/ssh.rb:207:in `new'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/net-ssh-2.9.2/lib/net/ssh.rb:207:in `start'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/sshkit-1.7.1/lib/sshkit/backends/connection_pool.rb:50:in `call'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/sshkit-1.7.1/lib/sshkit/backends/connection_pool.rb:50:in `create_new_entry'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/sshkit-1.7.1/lib/sshkit/backends/connection_pool.rb:22:in `checkout'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/sshkit-1.7.1/lib/sshkit/backends/netssh.rb:187:in `with_ssh'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/sshkit-1.7.1/lib/sshkit/backends/netssh.rb:137:in `block in _execute'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/sshkit-1.7.1/lib/sshkit/backends/netssh.rb:133:in `tap'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/sshkit-1.7.1/lib/sshkit/backends/netssh.rb:133:in `_execute'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/sshkit-1.7.1/lib/sshkit/backends/netssh.rb:62:in `test'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/capistrano-rvm-0.1.2/lib/capistrano/tasks/rvm.rake:21:in `block (3 levels) in <top (required)>'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/sshkit-1.7.1/lib/sshkit/backends/netssh.rb:54:in `instance_exec'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/sshkit-1.7.1/lib/sshkit/backends/netssh.rb:54:in `run'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/sshkit-1.7.1/lib/sshkit/runners/parallel.rb:13:in `block (2 levels) in execute'
EOFError: end of file reached
/Users/andela/.rvm/gems/ruby-2.2.1/gems/net-ssh-2.9.2/lib/net/ssh/transport/server_version.rb:47:in `readpartial'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/net-ssh-2.9.2/lib/net/ssh/transport/server_version.rb:47:in `block (2 levels) in negotiate!'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/net-ssh-2.9.2/lib/net/ssh/transport/server_version.rb:45:in `loop'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/net-ssh-2.9.2/lib/net/ssh/transport/server_version.rb:45:in `block in negotiate!'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/net-ssh-2.9.2/lib/net/ssh/transport/server_version.rb:43:in `loop'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/net-ssh-2.9.2/lib/net/ssh/transport/server_version.rb:43:in `negotiate!'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/net-ssh-2.9.2/lib/net/ssh/transport/server_version.rb:32:in `initialize'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/net-ssh-2.9.2/lib/net/ssh/transport/session.rb:84:in `new'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/net-ssh-2.9.2/lib/net/ssh/transport/session.rb:84:in `block in initialize'
/Users/andela/.rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/timeout.rb:74:in `timeout'
/Users/andela/.rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/timeout.rb:125:in `timeout'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/net-ssh-2.9.2/lib/net/ssh/transport/session.rb:84:in `initialize'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/net-ssh-2.9.2/lib/net/ssh.rb:207:in `new'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/net-ssh-2.9.2/lib/net/ssh.rb:207:in `start'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/sshkit-1.7.1/lib/sshkit/backends/connection_pool.rb:50:in `call'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/sshkit-1.7.1/lib/sshkit/backends/connection_pool.rb:50:in `create_new_entry'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/sshkit-1.7.1/lib/sshkit/backends/connection_pool.rb:22:in `checkout'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/sshkit-1.7.1/lib/sshkit/backends/netssh.rb:187:in `with_ssh'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/sshkit-1.7.1/lib/sshkit/backends/netssh.rb:137:in `block in _execute'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/sshkit-1.7.1/lib/sshkit/backends/netssh.rb:133:in `tap'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/sshkit-1.7.1/lib/sshkit/backends/netssh.rb:133:in `_execute'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/sshkit-1.7.1/lib/sshkit/backends/netssh.rb:62:in `test'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/capistrano-rvm-0.1.2/lib/capistrano/tasks/rvm.rake:21:in `block (3 levels) in <top (required)>'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/sshkit-1.7.1/lib/sshkit/backends/netssh.rb:54:in `instance_exec'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/sshkit-1.7.1/lib/sshkit/backends/netssh.rb:54:in `run'
/Users/andela/.rvm/gems/ruby-2.2.1/gems/sshkit-1.7.1/lib/sshkit/runners/parallel.rb:13:in `block (2 levels) in execute'
Tasks: TOP => rvm:hook


问:
REACT: Unhandled Rejection (TypeError): this.props.flights.forEach is not a function
I am trying to learn React, and I stumbled upon the error from the title in my program. Here is my code:

```<code>class FlightRow extends React.Component{

handleClicke=(event)=>{
    console.log('delete button pentru '+this.props.flight.flightId);
    this.props.deleteFunc(this.props.flight.flightId);
}

render() {
    return (
        <tr>
            <td>{this.props.flight.flightId}</td>
            <td>{this.props.flight.destination}</td>
            <td>{this.props.flight.airport}</td>
            <td>{this.props.flight.freeseats}</td>
            <td>{this.props.flight.datehour}</td>
            <td><button  onClick={this.handleClicke}>Delete</button></td>
        </tr>
    );
}
}

class FlightTable extends React.Component {
render() {
    var rows = [];
    var functieStergere=this.props.deleteFunc;
    this.props.flights.forEach(function(flight) {

        rows.push(<FlightRow flight={flight} key={flight.flightId} deleteFunc={functieStergere} />);
    });
    return (<div className="FlightTable">

        <table className="center">
            <thead>
            <tr>
                <th>FlightId</th>
                <th>Destination</th>
                <th>Airport</th>
                <th>Freeseats</th>
                <th>Datehour</th>
                <th></th>
            </tr>
            </thead>
            <tbody>{rows}</tbody>
        </table>

        </div>
    );
}
}

export default FlightTable;
</code>```

I am getting the error in the first lines of the FlightTable class, when I am trying to fill it. Immediately after I start the app, I see for like one second the table filled exactly how it should be, then I receive the error.

Here is where I declare my "flights" array.

```<code>class FlightApp extends React.Component{
constructor(props){
    super(props);
    this.state={flights:[{"flightId":12,"destination":"CCCCC","airport":"AAAAA","freeseats":100,"datehour":"2017-02-02"},{"flightId":13,"destination":"CCCCC","airport":"AAAAA","freeseats":100,"datehour":"2017-02-02"}],
        deleteFunc:this.deleteFunc.bind(this),
        addFunc:this.addFunc.bind(this),
    }
    console.log('FlightApp constructor')
}

addFunc(flight){
    console.log('inside add Func '+flight);
    AddFlight(flight)
        .then(res=> GetFlights())
        .then(flights=>this.setState({flights}))
        .catch(erorr=>console.log('eroare add ',erorr));
}

deleteFunc(flight){
    console.log('inside deleteFunc '+flight);
    DeleteFlight(flight)
        .then(res=> GetFlights())
        .then(flights=>this.setState({flights}))
        .catch(error=>console.log('eroare delete', error));
}

componentDidMount(){
    console.log('inside componentDidMount')
    GetFlights().then(flights=>this.setState({flights}));
}

render(){
    return(
        <div className="FlightApp">
            <h1>Flight Management</h1>
            <FlightForm addFunc={this.state.addFunc}/>
            <br/>
            <br/>
             <FlightTable flights={this.state.flights} deleteFunc={this.state.deleteFunc}/>
        </div>
    );
}
}

export default FlightApp;
</code>```

The "GetFlights()" method looks like this, and it calls a method from a Java REST Spring Server that return a List

```<code>export function GetFlights(){
var headers = new Headers();
headers.append('Accept', 'application/json');
var myInit = { method: 'GET',
    headers: headers,
    mode: 'cors'};
var request = new Request(CHAT_USERS_BASE_URL, myInit);
console.log('Inainte de fetch pentru '+CHAT_USERS_BASE_URL)
return fetch(request)
    .then(status)
    .then(json)
    .then(data=> {
         console.log('Request succeeded with JSON response', data);
         return data;
     }).catch(error=>{
            console.log('Request failed', error);
            return error;
      });

}
</code>```

How could I fix this error? Thank you.

答: Fixed this error I had and now everything works good. In my Spring Controller, I added as an annotation @CrossOrigin(origins = "http://localhost:3000"), and now everything works as it should.

Body:
I am trying to learn React, and I stumbled upon the error from the title in my program. Here is my code:

class FlightRow extends React.Component{

handleClicke=(event)=>{
    console.log('delete button pentru '+this.props.flight.flightId);
    this.props.deleteFunc(this.props.flight.flightId);
}

render() {
    return (

            {this.props.flight.flightId}
            {this.props.flight.destination}
            {this.props.flight.airport}
            {this.props.flight.freeseats}
            {this.props.flight.datehour}
            <button  onClick={this.handleClicke}>Delete</button>

    );
}
}

class FlightTable extends React.Component {
render() {
    var rows = [];
    var functieStergere=this.props.deleteFunc;
    this.props.flights.forEach(function(flight) {

        rows.push(<FlightRow flight={flight} key={flight.flightId} deleteFunc={functieStergere} />);
    });
    return (

                FlightId
                Destination
                Airport
                Freeseats
                Datehour

{rows}

    );
}
}

export default FlightTable;

I am getting the error in the first lines of the FlightTable class, when I am trying to fill it. Immediately after I start the app, I see for like one second the table filled exactly how it should be, then I receive the error.

Here is where I declare my "flights" array.

class FlightApp extends React.Component{
constructor(props){
    super(props);
    this.state={flights:[{"flightId":12,"destination":"CCCCC","airport":"AAAAA","freeseats":100,"datehour":"2017-02-02"},{"flightId":13,"destination":"CCCCC","airport":"AAAAA","freeseats":100,"datehour":"2017-02-02"}],
        deleteFunc:this.deleteFunc.bind(this),
        addFunc:this.addFunc.bind(this),
    }
    console.log('FlightApp constructor')
}

addFunc(flight){
    console.log('inside add Func '+flight);
    AddFlight(flight)
        .then(res=> GetFlights())
        .then(flights=>this.setState({flights}))
        .catch(erorr=>console.log('eroare add ',erorr));
}

deleteFunc(flight){
    console.log('inside deleteFunc '+flight);
    DeleteFlight(flight)
        .then(res=> GetFlights())
        .then(flights=>this.setState({flights}))
        .catch(error=>console.log('eroare delete', error));
}

componentDidMount(){
    console.log('inside componentDidMount')
    GetFlights().then(flights=>this.setState({flights}));
}

render(){
    return(

Flight Management

            <FlightForm addFunc={this.state.addFunc}/>

             <FlightTable flights={this.state.flights} deleteFunc={this.state.deleteFunc}/>

    );
}
}

export default FlightApp;

The "GetFlights()" method looks like this, and it calls a method from a Java REST Spring Server that return a List

export function GetFlights(){
var headers = new Headers();
headers.append('Accept', 'application/json');
var myInit = { method: 'GET',
    headers: headers,
    mode: 'cors'};
var request = new Request(CHAT_USERS_BASE_URL, myInit);
console.log('Inainte de fetch pentru '+CHAT_USERS_BASE_URL)
return fetch(request)
    .then(status)
    .then(json)
    .then(data=> {
         console.log('Request succeeded with JSON response', data);
         return data;
     }).catch(error=>{
            console.log('Request failed', error);
            return error;
      });

}

How could I fix this error? Thank you.