问:
How to resolve "System.UnauthorizedAccessException: Authorization for Microsoft App ID xxx failed with status code Unauthorized"
I've created a simple bot using the .net framework. Messages are received but when replying, the application throw the exception below

```<code>System.AggregateException: One or more errors occurred. ---> System.UnauthorizedAccessException: Authorization for Microsoft App ID xxx failed with status code Unauthorized and reason phrase 'Unauthorized' ---> System.Net.Http.HttpRequestException: Response status code does not indicate success: 401 (Unauthorized).
   at System.Net.Http.HttpResponseMessage.EnsureSuccessStatusCode()
   at Microsoft.Bot.Connector.JwtTokenRefresher.<SendAsync>d__2.MoveNext()
   --- End of inner exception stack trace ---
   at Microsoft.Bot.Connector.JwtTokenRefresher.<SendAsync>d__2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
   at Microsoft.Bot.Connector.BotState.<GetConversationDataWithHttpMessagesAsync>d__8.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Connector.BotStateExtensions.<GetConversationDataAsync>d__7.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Dialogs.Internals.ConnectorStore.<Microsoft-Bot-Builder-Dialogs-Internals-IBotDataStore<Microsoft-Bot-Connector-BotData>-LoadAsync>d__2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Dialogs.Internals.CachingBotDataStore.<LoadFromInnerAndCache>d__8.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Dialogs.Internals.CachingBotDataStore.<Microsoft-Bot-Builder-Dialogs-Internals-IBotDataStore<Microsoft-Bot-Connector-BotData>-LoadAsync>d__6.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Dialogs.Internals.BotDataBase`1.<LoadData>d__16.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Dialogs.Internals.BotDataBase`1.<LoadAsync>d__8.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Dialogs.Internals.DialogTaskManagerBotDataLoader.<LoadAsync>d__11.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Dialogs.Internals.PersistentDialogTask.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Dialogs.Internals.ExceptionTranslationDialogTask.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d__2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Dialogs.Internals.SerializeByConversation.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Dialogs.Internals.PostUnhandledExceptionToUser.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.Bot.Builder.Dialogs.Internals.PostUnhandledExceptionToUser.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Dialogs.Internals.LogPostToBot.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Dialogs.Conversation.<SendAsync>d__9.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Dialogs.Conversation.<SendAsync>d__6.MoveNext()
   --- End of inner exception stack trace ---
---> (Inner Exception #0) System.UnauthorizedAccessException: Authorization for Microsoft App ID 9d88e9f7-289e-45d2-8215-8f539955335d failed with status code Unauthorized and reason phrase 'Unauthorized' ---> System.Net.Http.HttpRequestException: Response status code does not indicate success: 401 (Unauthorized).
   at System.Net.Http.HttpResponseMessage.EnsureSuccessStatusCode()
   at Microsoft.Bot.Connector.JwtTokenRefresher.<SendAsync>d__2.MoveNext()
   --- End of inner exception stack trace ---
   at Microsoft.Bot.Connector.JwtTokenRefresher.<SendAsync>d__2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
   at Microsoft.Bot.Connector.BotState.<GetConversationDataWithHttpMessagesAsync>d__8.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Connector.BotStateExtensions.<GetConversationDataAsync>d__7.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Dialogs.Internals.ConnectorStore.<Microsoft-Bot-Builder-Dialogs-Internals-IBotDataStore<Microsoft-Bot-Connector-BotData>-LoadAsync>d__2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Dialogs.Internals.CachingBotDataStore.<LoadFromInnerAndCache>d__8.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Dialogs.Internals.CachingBotDataStore.<Microsoft-Bot-Builder-Dialogs-Internals-IBotDataStore<Microsoft-Bot-Connector-BotData>-LoadAsync>d__6.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Dialogs.Internals.BotDataBase`1.<LoadData>d__16.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Dialogs.Internals.BotDataBase`1.<LoadAsync>d__8.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Dialogs.Internals.DialogTaskManagerBotDataLoader.<LoadAsync>d__11.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Dialogs.Internals.PersistentDialogTask.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Dialogs.Internals.ExceptionTranslationDialogTask.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d__2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Dialogs.Internals.SerializeByConversation.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Dialogs.Internals.PostUnhandledExceptionToUser.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.Bot.Builder.Dialogs.Internals.PostUnhandledExceptionToUser.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Dialogs.Internals.LogPostToBot.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Dialogs.Conversation.<SendAsync>d__9.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Dialogs.Conversation.<SendAsync>d__6.MoveNext()<---
</code>```

Code

```<code>open System
open System.Text
open Hopac
open Hopac.Hopac
open Microsoft.Bot.Connector
open Suave
open Suave.Successful
open Suave.Filters
open Suave.Operators
open Microsoft.Bot.Builder.Dialogs
open Newtonsoft.Json
open System.Threading.Tasks
open Microsoft.Bot.Builder.Dialogs.Internals

type RootDialog () =
  let rec onMessageReceived (context: IDialogContext) (result: IAwaitable<obj>) =
    job {

      //let! activity = result
      do! context.PostAsync ("Sweet") |> Job.awaitUnitTask
      context.Wait (ResumeAfter onMessageReceived) }
    |> startAsTask |> unbox
  interface IDialog<obj> with
    member x.StartAsync (context: IDialogContext) =
      context.Wait (ResumeAfter (onMessageReceived))
      Task.CompletedTask

let getActivity request =
  let body = request.rawForm |> Encoding.UTF8.GetString
  let activity = JsonConvert.DeserializeObject<Activity> (body)
  activity

let handleSystemMessage (activity: Activity) =
  match activity.Type with
  | ActivityTypes.DeleteUserData
  | _ -> ()

let post (activity: Activity) ctx =
  job {
    match activity.Type with
    | ActivityTypes.Message ->
        do! Conversation.SendAsync (activity, fun () -> RootDialog() :> _) |> Job.awaitUnitTask
    | _ -> handleSystemMessage activity
    return! OK "Got it" ctx }

let part =
  choose [
    POST >=> path "/bot/messages" >=> request (getActivity >> (fun a b -> post a b |> Job.toAsync)) ]
</code>```

PS:

I followed the tutorial here and it fails at step 3. Everything works fine when security is disabled.

Checking with fiddler shows that multiple requests are made to login.microsoftonline.com and all such requests are successful so I don't think it is the credentials. What could be the problem?

答:
In the end, the solution was to add the line below before do! Conversation.SendAsync ...

MicrosoftAppCredentials.TrustServiceUrl (activity.ServiceUrl)

PS:
I'm not really sure why this must be done but any comments on the reason for this might help make the solution more meaningful.

Body:
I've created a simple bot using the .net framework. Messages are received but when replying, the application throw the exception below

System.AggregateException: One or more errors occurred. ---> System.UnauthorizedAccessException: Authorization for Microsoft App ID xxx failed with status code Unauthorized and reason phrase 'Unauthorized' ---> System.Net.Http.HttpRequestException: Response status code does not indicate success: 401 (Unauthorized).
   at System.Net.Http.HttpResponseMessage.EnsureSuccessStatusCode()
   at Microsoft.Bot.Connector.JwtTokenRefresher.<SendAsync>d__2.MoveNext()
   --- End of inner exception stack trace ---
   at Microsoft.Bot.Connector.JwtTokenRefresher.<SendAsync>d__2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
   at Microsoft.Bot.Connector.BotState.<GetConversationDataWithHttpMessagesAsync>d__8.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Connector.BotStateExtensions.<GetConversationDataAsync>d__7.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Dialogs.Internals.ConnectorStore.<Microsoft-Bot-Builder-Dialogs-Internals-IBotDataStore<Microsoft-Bot-Connector-BotData>-LoadAsync>d__2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Dialogs.Internals.CachingBotDataStore.<LoadFromInnerAndCache>d__8.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Dialogs.Internals.CachingBotDataStore.<Microsoft-Bot-Builder-Dialogs-Internals-IBotDataStore<Microsoft-Bot-Connector-BotData>-LoadAsync>d__6.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Dialogs.Internals.BotDataBase`1.<LoadData>d__16.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Dialogs.Internals.BotDataBase`1.<LoadAsync>d__8.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Dialogs.Internals.DialogTaskManagerBotDataLoader.<LoadAsync>d__11.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Dialogs.Internals.PersistentDialogTask.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Dialogs.Internals.ExceptionTranslationDialogTask.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d__2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Dialogs.Internals.SerializeByConversation.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Dialogs.Internals.PostUnhandledExceptionToUser.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.Bot.Builder.Dialogs.Internals.PostUnhandledExceptionToUser.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Dialogs.Internals.LogPostToBot.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Dialogs.Conversation.<SendAsync>d__9.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Dialogs.Conversation.<SendAsync>d__6.MoveNext()
   --- End of inner exception stack trace ---
---> (Inner Exception #0) System.UnauthorizedAccessException: Authorization for Microsoft App ID 9d88e9f7-289e-45d2-8215-8f539955335d failed with status code Unauthorized and reason phrase 'Unauthorized' ---> System.Net.Http.HttpRequestException: Response status code does not indicate success: 401 (Unauthorized).
   at System.Net.Http.HttpResponseMessage.EnsureSuccessStatusCode()
   at Microsoft.Bot.Connector.JwtTokenRefresher.<SendAsync>d__2.MoveNext()
   --- End of inner exception stack trace ---
   at Microsoft.Bot.Connector.JwtTokenRefresher.<SendAsync>d__2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
   at Microsoft.Bot.Connector.BotState.<GetConversationDataWithHttpMessagesAsync>d__8.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Connector.BotStateExtensions.<GetConversationDataAsync>d__7.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Dialogs.Internals.ConnectorStore.<Microsoft-Bot-Builder-Dialogs-Internals-IBotDataStore<Microsoft-Bot-Connector-BotData>-LoadAsync>d__2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Dialogs.Internals.CachingBotDataStore.<LoadFromInnerAndCache>d__8.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Dialogs.Internals.CachingBotDataStore.<Microsoft-Bot-Builder-Dialogs-Internals-IBotDataStore<Microsoft-Bot-Connector-BotData>-LoadAsync>d__6.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Dialogs.Internals.BotDataBase`1.<LoadData>d__16.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Dialogs.Internals.BotDataBase`1.<LoadAsync>d__8.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Dialogs.Internals.DialogTaskManagerBotDataLoader.<LoadAsync>d__11.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Dialogs.Internals.PersistentDialogTask.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Dialogs.Internals.ExceptionTranslationDialogTask.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d__2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Dialogs.Internals.SerializeByConversation.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Dialogs.Internals.PostUnhandledExceptionToUser.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.Bot.Builder.Dialogs.Internals.PostUnhandledExceptionToUser.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Dialogs.Internals.LogPostToBot.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Dialogs.Conversation.<SendAsync>d__9.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Bot.Builder.Dialogs.Conversation.<SendAsync>d__6.MoveNext()<---

Code

open System
open System.Text
open Hopac
open Hopac.Hopac
open Microsoft.Bot.Connector
open Suave
open Suave.Successful
open Suave.Filters
open Suave.Operators
open Microsoft.Bot.Builder.Dialogs
open Newtonsoft.Json
open System.Threading.Tasks
open Microsoft.Bot.Builder.Dialogs.Internals

type RootDialog () =
  let rec onMessageReceived (context: IDialogContext) (result: IAwaitable<obj>) =
    job {

      //let! activity = result
      do! context.PostAsync ("Sweet") |> Job.awaitUnitTask
      context.Wait (ResumeAfter onMessageReceived) }
    |> startAsTask |> unbox
  interface IDialog<obj> with
    member x.StartAsync (context: IDialogContext) =
      context.Wait (ResumeAfter (onMessageReceived))
      Task.CompletedTask

let getActivity request =
  let body = request.rawForm |> Encoding.UTF8.GetString
  let activity = JsonConvert.DeserializeObject<Activity> (body)
  activity

let handleSystemMessage (activity: Activity) =
  match activity.Type with
  | ActivityTypes.DeleteUserData
  | _ -> ()

let post (activity: Activity) ctx =
  job {
    match activity.Type with
    | ActivityTypes.Message ->
        do! Conversation.SendAsync (activity, fun () -> RootDialog() :> _) |> Job.awaitUnitTask
    | _ -> handleSystemMessage activity
    return! OK "Got it" ctx }

let part =
  choose [
    POST >=> path "/bot/messages" >=> request (getActivity >> (fun a b -> post a b |> Job.toAsync)) ]

PS:

I followed the tutorial here and it fails at step 3. Everything works fine when security is disabled.

Checking with fiddler shows that multiple requests are made to login.microsoftonline.com and all such requests are successful so I don't think it is the credentials. What could be the problem?


来源: stackexchange

问:
Statistics on number of Google Spreadsheets using the new Google Drive User Metrics
Google Admin SDK used to have the "Google Docs" User Metrics for reporting. With it we were able to fetch the property "docs:num_spreadsheets" to get the number of spreadsheets owned by the each user. The Google docs metrics are now being deprecated, replaced by Google Drive metrics. However I don't any way to get the number of spreadsheets of a user. I can get the number of spreadsheets created by a user during a certain period (which period exactly, I couldn't figure out) but not the total number of Spreadsheets owned by them.
In this page it's written that drive:num_owned_google_spreadsheets_delta replaces the deprecated docs:num_spreadsheets but these are not the same metrics.
Any idea on how to address that?
Thanks a lot,
Rafael</p>

答:
As an alternative to the Admin SDK metrics, using the Drive API and generating the metrics user by user may be an option for you.

If so, in summary the pseudocode is: using a Service Account to impersonate each user and get an OAuth2 token , call the Drive REST API files.list method with a query (&q=...) of all files of mimetype of application/vnd.google-apps.spreadsheet and the user's email in owners. The length of the result set's files.files array is the count of the files (the metric) you want.

ContentLicense: CC BY-SA 3.0


问:
Stop node-debug from opening a new browser window
The command:

```<code>node-debug sls offline
</code>```

opens a new browser window every time it is run.

How do we stop it from opening a new window every time? I want to reuse the existing window!

答:
This is a known issue with node inspector. Take a look here.

Since 0.9.0 we use https://github.com/benderjs/browser-launcher2 to
  start the browser, and make sure it's Chrome/Chromium/Opera (i.e. the
  browsers that can properly render node inspector; we detect installed
  browsers in the system and choose the most appropriate one; earlier we
  used opener module which just delegated opening the browser to the OS,
  which would open the defaul browser, which could have been e.g.
  Firefox) and this could be the reason why the behavior has changed.

browser-launcher2 actually does a bit more than just launching a
  browser, for instance it creates a new profile for Chrome in a
  subfolder of ~/ - this is probably the issue that @CalvinScott
  reported (i.e. Chrome that was opened was the new profile created by
  browser-launcher, not your original profile; you should be able to
  open your original profile of Chrome normally)

Also, you may consider this:

Since version 6.3, Node.js provides a buit-in DevTools-based debugger
  which mostly deprecates Node Inspector, see e.g. this blog post to get
  started. The built-in debugger is developed directly by the
  V8/Chromium team and provides certain advanced features (e.g.
  long/async stack traces) that are too difficult to implement in Node
  Inspector.

Body:
The command:

node-debug sls offline

opens a new browser window every time it is run.

How do we stop it from opening a new window every time? I want to reuse the existing window!


问:
ffmpeg (libavcodec) warning: encoded frame too large
I'm trying to use libavcodec (ffmpeg) to encode raw pixel data to mp4 format. Every thing goes well and I'm getting .avi file with decent quality but some times the codec gives "encoded frame too large" warning. And when ever it does that, a part of some frames (usually bottom portion of the frame) look garbled or all mixed up. Can any one tell me when this warning is given. Following are the settings I'm using for encoder:

```<code>qmax = 6;
qmin = 2;
bit_rate = 200000; // if I increase this, I get more warnings.
width = 1360;
height = 768;
time_base.den = 15; // frames per second
time_base.num = 1;
gop_size = 48;
pix_fmt = PIX_FMT_YUV420P;
</code>```

Regards,

答:
From what I can gather ffmpeg allocates a constant buffer size of 2MB to hold a compressed
frame. 1080p is 3MB uncompressed for example, and the codec can't always compress a large frame into less than 2MB.

You can possibly fix this by increasing the buffer size, and/or making it dynamic.

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to use libavcodec (ffmpeg) to encode raw pixel data to mp4 format. Every thing goes well and I'm getting .avi file with decent quality but some times the codec gives "encoded frame too large" warning. And when ever it does that, a part of some frames (usually bottom portion of the frame) look garbled or all mixed up. Can any one tell me when this warning is given. Following are the settings I'm using for encoder:

qmax = 6;
qmin = 2;
bit_rate = 200000; // if I increase this, I get more warnings.
width = 1360;
height = 768;
time_base.den = 15; // frames per second
time_base.num = 1;
gop_size = 48;
pix_fmt = PIX_FMT_YUV420P;

Regards,


问:
How do I return a unsure type?
I have a parent Class named 'Shape' and write a method in it
I want any class extends from it can call the bigger method for other use.
simple logic like this:

```<code>public abstract Class Shape{
    public int size;
    public Shape() {}
    public Class<? extends Shape> bigger() {
        this.size += 1;
        return this; // ← Here,How can I return it with unsure type?
    }
}
</code>```

but how can I return a unsure type in here ?
thanks for any ideas!

====

and if I have a class Square extends Shape;

and I want use it like this:

```<code>Square S = new Square().bigger();
</code>```

And it will return a Shape Class, not a Square Class.

but I don't wanna use: (Square) new Square.bigger();

I hope it can automatic recognize what Class a using this method

And return the correct type.

答:
You don't return a Class here, just a Shape. Something like,

```<code>public abstract class Shape { // <- class
    public int size;

    public Shape() {
    }

    public Shape bigger() { // <-- a Shape. By definition of a sub-class because
        this.size += 1; // <-- "this" class is abstract
        return this;
    }
}
</code>```

Title: How do I return a unsure type?

Body:
I have a parent Class named 'Shape' and write a method in it
I want any class extends from it can call the bigger method for other use.
simple logic like this:

public abstract Class Shape{
    public int size;
    public Shape() {}
    public Class<? extends Shape> bigger() {
        this.size += 1;
        return this; // ← Here,How can I return it with unsure type?
    }
}

but how can I return a unsure type in here ?
thanks for any ideas!

====

and if I have a class Square extends Shape;

and I want use it like this:

Square S = new Square().bigger();

And it will return a Shape Class, not a Square Class.

but I don't wanna use: (Square) new Square.bigger();

I hope it can automatic recognize what Class a using this method

And return the correct type.

Body:
You don't return a Class here, just a Shape. Something like,

public abstract class Shape { // <- class
    public int size;

    public Shape() {
    }

    public Shape bigger() { // <-- a Shape. By definition of a sub-class because
        this.size += 1; // <-- "this" class is abstract
        return this;
    }
}


问:
why did the value of "x" change?
Here is my code:

```<code>x = [[1],[1],[1],[-1]]
a = [[-2,-1,-1,-2],[1,-2,2,-1],[-1,-2,-2,-1],[2,-1,1,-2]]
h = 0.1
def K(h,a,x):
    cont = [1,2,3,4]
    k = []
    for i in range(len(cont)):
        k.append(h*cont[i])
    y = x
    print('original value',x)
    for j in range(len(y)):
        y[j][0] += k[j]/4
        print('modified value',x)
K(h,a,x)
</code>```

So the question is why did the value of x change if it has not received anything?

答:
When you write:

```<code>y = x
</code>```

You're literally saying that x equals y. This doesn't make a copy of x. Whatever you do to x will happen to y and vice versa. You need to make a copy of x if you want them to be independent.

Title: why did the value of "x" change?

Body:
Here is my code:

x = [[1],[1],[1],[-1]]
a = [[-2,-1,-1,-2],[1,-2,2,-1],[-1,-2,-2,-1],[2,-1,1,-2]]
h = 0.1
def K(h,a,x):
    cont = [1,2,3,4]
    k = []
    for i in range(len(cont)):
        k.append(h*cont[i])
    y = x
    print('original value',x)
    for j in range(len(y)):
        y[j][0] += k[j]/4
        print('modified value',x)
K(h,a,x)

So the question is why did the value of x change if it has not received anything?

Body:
When you write:

y = x

You're literally saying that x equals y. This doesn't make a copy of x. Whatever you do to x will happen to y and vice versa. You need to make a copy of x if you want them to be independent.


问:
How to map Json to Java object using jackson
I am using jackson to map json which I get from my post rest api to map to a java object.

the json is represent by

```<code>{
  "baseName": "xyz",
  "salary": [
    {
      "id": 1,
      "info": {
        "ename": "john",
        "eid": 143
      }
    },
    {
      "id": 2,
      "info": {
        "ename": "bg",
        "eid": 123
      }
    }
  ]
}
</code>```

The java class are represent by

BaseInfo.java

```<code>class BaseInfo {
     String baseName;
     ArrayList<salary> salaries = new ArrayList<salary>();
}
</code>```

Salary.java

```<code>class Salary {
    int id;
    EmplInfo emp;
}
</code>```

EmplInfo.java

```<code>class EmplInfo{
    String ename;
    int eid;
}
</code>```

But in the when call the api with this json I get the arraylist initialized but contains nothings. What I am doing wrong ? I get other information like baseName,etc

答:
Following are the solutions:

Either add JsonProperty annotations as specified by Michael or update json keys i.e 'salary' to 'salaries' and 'info' to 'emp'

Body:
I am using jackson to map json which I get from my post rest api to map to a java object.

the json is represent by

{
  "baseName": "xyz",
  "salary": [
    {
      "id": 1,
      "info": {
        "ename": "john",
        "eid": 143
      }
    },
    {
      "id": 2,
      "info": {
        "ename": "bg",
        "eid": 123
      }
    }
  ]
}

The java class are represent by

BaseInfo.java

class BaseInfo {
     String baseName;
     ArrayList<salary> salaries = new ArrayList<salary>();
}

Salary.java

class Salary {
    int id;
    EmplInfo emp;
}

EmplInfo.java

class EmplInfo{
    String ename;
    int eid;
}

But in the when call the api with this json I get the arraylist initialized but contains nothings. What I am doing wrong ? I get other information like baseName,etc


问:
Modulo 7 on 64 bit integer using shift and add (32 bit works but 64 doesn't)
I have a working implementation to calculate modulo 7 of a 32 bit unsigned int but I'm having trouble with the 64 bit implementation. The 32 bit implementations were from this blog post (with a few bug fixes). I was able to get 64 bit versions working for modulo 3, 5, 15, and 6 but not 7. The math is a little over my head.

For reference, here is a gist with the full code.

Here's the working 32 bit:

```<code>static public uint Mersenne7(uint a)
{
    a = (a >> 24) + (a & 0xFFFFFF); // sum base 2**24 digits
    a = (a >> 12) + (a & 0xFFF);    // sum base 2**12 digits
    a = (a >> 6) + (a & 0x3F);      // sum base 2**6 digits
    a = (a >> 3) + (a & 0x7);       // sum base 2**2 digits
    a = (a >> 2) + (a & 0x7);       // sum base 2**2 digits
    if (a > 5) a = a - 6;
    return a;
}
</code>```

I made what seemed like the obvious extension, which worked for modulo 3, 5, and 15, but for mod 7 the results are all over the place with no obvious pattern (except the results all are under 7):

```<code>static public ulong Mersenne7(ulong a)
{
    a = (a >> 48) + (a & 0xFFFFFFFFFFFF); // sum base 2**48 digits
    a = (a >> 24) + (a & 0xFFFFFF); // sum base 2**24 digits
    a = (a >> 12) + (a & 0xFFF);    // sum base 2**12 digits
    a = (a >> 6) + (a & 0x3F);      // sum base 2**6 digits
    a = (a >> 3) + (a & 0x7);       // sum base 2**2 digits
    a = (a >> 2) + (a & 0x7);       // sum base 2**2 digits
    if (a > 5) a = a - 6;
    return a;
}
</code>```

The same technique for 64 bits obviously doesn't work for mod 7. I've been trying some variations but I don't get anything noticeably better and I'm not sure how to work through it systematically.

I have benchmarked and shown that calculating modulo using shift and add for Mersenne numbers is faster than the built in modulus operator in my environment, and this is running in a tight loop in a hot path (index to a static size circular buffer). These lower value divisors are also more common than larger buffer sizes.

答:
The maths behind this is actually pretty simple.

(Note for the maths part I'm using a^b to mean "a to the power b" not
"a xor b". These math parts are not supposed to be C# code)

The key trick is that you split a into two pieces so that

```<code>a = b * 2^3 + c
</code>```

where b = a / 2^3 = a >> 3 and c = a mod 2^3 = a & 0x7

Then

```<code>a mod 7 = ((b mod 7) * (2^3 mod 7) + c ) mod 7
</code>```

but 2^3 mod 7 = 1 so

```<code>a mod 7 = ( b mod 7 + c ) mod 7 = (b + c) mod 7
</code>```

We apply this trick several times using

```<code>1 = 2^3 mod 7 = 2^6 mod 7 = 2^12 mod 7 = 2^24 mod 7 = 2^48 mod 7
</code>```

With this in mind it looks like your "working" Mersene7 doesn't work.

I think this:

```<code>static public uint Mersenne7(uint a)
{
    a = (a >> 24) + (a & 0xFFFFFF); // sum base 2**24 digits
    a = (a >> 12) + (a & 0xFFF);    // sum base 2**12 digits
    a = (a >> 6) + (a & 0x3F);      // sum base 2**6 digits
    a = (a >> 3) + (a & 0x7);       // sum base 2**2 digits
    a = (a >> 2) + (a & 0x7);       // sum base 2**2 digits
    if (a > 5) a = a - 6;
    return a;
}
</code>```

should be

```<code>static public uint Mersenne7(uint a)
{
    a = (a >> 24) + (a & 0xFFFFFF); // sum base 2**24 digits
    a = (a >> 12) + (a & 0xFFF);    // sum base 2**12 digits
    a = (a >> 6) + (a & 0x3F);      // sum base 2**6 digits
    a = (a >> 3) + (a & 0x7);       // sum base 2**3 digits
    a = (a >> 3) + (a & 0x7);       // sum base 2**3 digits
    if (a >= 7) a = a - 7;
    return a;
}
</code>```

Note the change in the value in the final comparison, and the removal of the final sum line.

With these changes both the unit and ulong versions should produce correct results I think. (Haven't tested though)

I've duplicated the second contraction - I'm not sure if it is actually needed. (It is to handle overflow - but that may not occur you'll need to try some values to check)

In the ulong case you will need the a=(a>>48) + a & 0xFFFFFFFFFFFFL line like you have already implemented.

Body:
I have a working implementation to calculate modulo 7 of a 32 bit unsigned int but I'm having trouble with the 64 bit implementation. The 32 bit implementations were from this blog post (with a few bug fixes). I was able to get 64 bit versions working for modulo 3, 5, 15, and 6 but not 7. The math is a little over my head.

For reference, here is a gist with the full code.

Here's the working 32 bit:

static public uint Mersenne7(uint a)
{
    a = (a >> 24) + (a & 0xFFFFFF); // sum base 2**24 digits
    a = (a >> 12) + (a & 0xFFF);    // sum base 2**12 digits
    a = (a >> 6) + (a & 0x3F);      // sum base 2**6 digits
    a = (a >> 3) + (a & 0x7);       // sum base 2**2 digits
    a = (a >> 2) + (a & 0x7);       // sum base 2**2 digits
    if (a > 5) a = a - 6;
    return a;
}

I made what seemed like the obvious extension, which worked for modulo 3, 5, and 15, but for mod 7 the results are all over the place with no obvious pattern (except the results all are under 7):

static public ulong Mersenne7(ulong a)
{
    a = (a >> 48) + (a & 0xFFFFFFFFFFFF); // sum base 2**48 digits
    a = (a >> 24) + (a & 0xFFFFFF); // sum base 2**24 digits
    a = (a >> 12) + (a & 0xFFF);    // sum base 2**12 digits
    a = (a >> 6) + (a & 0x3F);      // sum base 2**6 digits
    a = (a >> 3) + (a & 0x7);       // sum base 2**2 digits
    a = (a >> 2) + (a & 0x7);       // sum base 2**2 digits
    if (a > 5) a = a - 6;
    return a;
}

The same technique for 64 bits obviously doesn't work for mod 7. I've been trying some variations but I don't get anything noticeably better and I'm not sure how to work through it systematically.

I have benchmarked and shown that calculating modulo using shift and add for Mersenne numbers is faster than the built in modulus operator in my environment, and this is running in a tight loop in a hot path (index to a static size circular buffer). These lower value divisors are also more common than larger buffer sizes.

Body:
The maths behind this is actually pretty simple.

(Note for the maths part I'm using a^b to mean "a to the power b" not
"a xor b". These math parts are not supposed to be C# code)

The key trick is that you split a into two pieces so that

a = b * 2^3 + c

where b = a / 2^3 = a >> 3 and c = a mod 2^3 = a & 0x7

Then

a mod 7 = ((b mod 7) * (2^3 mod 7) + c ) mod 7

but 2^3 mod 7 = 1 so

a mod 7 = ( b mod 7 + c ) mod 7 = (b + c) mod 7

We apply this trick several times using

1 = 2^3 mod 7 = 2^6 mod 7 = 2^12 mod 7 = 2^24 mod 7 = 2^48 mod 7

With this in mind it looks like your "working" Mersene7 doesn't work.

I think this:

static public uint Mersenne7(uint a)
{
    a = (a >> 24) + (a & 0xFFFFFF); // sum base 2**24 digits
    a = (a >> 12) + (a & 0xFFF);    // sum base 2**12 digits
    a = (a >> 6) + (a & 0x3F);      // sum base 2**6 digits
    a = (a >> 3) + (a & 0x7);       // sum base 2**2 digits
    a = (a >> 2) + (a & 0x7);       // sum base 2**2 digits
    if (a > 5) a = a - 6;
    return a;
}

should be

static public uint Mersenne7(uint a)
{
    a = (a >> 24) + (a & 0xFFFFFF); // sum base 2**24 digits
    a = (a >> 12) + (a & 0xFFF);    // sum base 2**12 digits
    a = (a >> 6) + (a & 0x3F);      // sum base 2**6 digits
    a = (a >> 3) + (a & 0x7);       // sum base 2**3 digits
    a = (a >> 3) + (a & 0x7);       // sum base 2**3 digits
    if (a >= 7) a = a - 7;
    return a;
}

Note the change in the value in the final comparison, and the removal of the final sum line.

With these changes both the unit and ulong versions should produce correct results I think. (Haven't tested though)

I've duplicated the second contraction - I'm not sure if it is actually needed. (It is to handle overflow - but that may not occur you'll need to try some values to check)

In the ulong case you will need the a=(a>>48) + a & 0xFFFFFFFFFFFFL line like you have already implemented.


答:
When you put:

```<code>y = x
</code>```

All x is doing is acting as a pointer to the list object in memory. When you do the above, you are saying I want y to point to the same list that x references in the memory. Any changes in place changes to y will also affect x.

If you wish to have the reference y point to a different object in memory (with the same values as x,) you need to make a copy of x.

```<code>y = x[:] #make a copy.  SEE EDIT
</code>```

Now y and x will be pointing to different list objects in memory, but both objects will have the same values.

Note that any mutable datatype in python shares this reference property, such as: sets, dictionaries, lists, byte arrays and also some classes.

Look into the differences between mutable and immutable datatypes in python as this distinction is critical and will lead to undiagnosible bugs without knowledge on how python accesses different data types.

EDIT!!

Sorry, I did not notice x is made of a series of lists. You need to use deepcopy to copy the nested lists!

```<code>from copy import deepcopy
y = deepcopy(x)
</code>```

Title: why did the value of "x" change?

Body:
When you put:

y = x

All x is doing is acting as a pointer to the list object in memory. When you do the above, you are saying I want y to point to the same list that x references in the memory. Any changes in place changes to y will also affect x.

If you wish to have the reference y point to a different object in memory (with the same values as x,) you need to make a copy of x.

y = x[:] #make a copy.  SEE EDIT

Now y and x will be pointing to different list objects in memory, but both objects will have the same values.

Note that any mutable datatype in python shares this reference property, such as: sets, dictionaries, lists, byte arrays and also some classes.

Look into the differences between mutable and immutable datatypes in python as this distinction is critical and will lead to undiagnosible bugs without knowledge on how python accesses different data types.

EDIT!!

Sorry, I did not notice x is made of a series of lists. You need to use deepcopy to copy the nested lists!

from copy import deepcopy
y = deepcopy(x)


问:
Is it possible to refresh/update the data in a treeview?
I'm new at GUI development and I've been working on a project with gtk+ 3 for some days, but I'm stuck at this point.

My app contains two treeviews, the data in the rows is obtained from an sql query, by right clicking on a row a popup-menu appears, giving the option to set the data as "known", updating the database table.

The previous data now should belong in the other treeview, and so it does when the app is restarted, but I'm looking to do it in real time.

Is it possible to update/refresh the data in a treeview?

The model is obtained with the function:

```<code>static GtkTreeStore* create_and_fill(char* known)
{
  GtkTreeStore* store;
  GtkTreeIter iter;
  GtkWidget* tree;
  store = gtk_tree_store_new(2,G_TYPE_STRING,G_TYPE_STRING);

  char source_mac[50] = {0};
  char source_ip[50] = {0};
  int num_fields;

  char query[300] = {0};
  sprintf(query, "select mac,ip from hosts where known=%s", known);
  if(mysql_query(conn, query))
  {
    fprintf(stderr,"%s\n", mysql_error(conn));
  }
  res = mysql_store_result(conn);
  num_fields = mysql_num_fields(res);

  while((row = mysql_fetch_row(res)))
  {
    sprintf(source_mac,"%s", row[0]);
    sprintf(source_ip,"%s", row[1]);
    gtk_tree_store_append(store, &iter, NULL);
    gtk_tree_store_set(store, &iter, MAC_ADDRESS, source_mac, IP_ADDRESS, source_ip,-1);
  }
  gtk_tree_store_append(store, &iter, NULL);
  mysql_free_result(res);
  return store;
}
</code>```

答:
I simply ended up doing an ugly patch.
I created a function that removes the treeviews, rebuilds the stores and packs them again.</p>

```<code>static void refresh()
{
gtk_container_remove(GTK_CONTAINER(box), tree_1);
gtk_container_remove(GTK_CONTAINER(box), tree_2);

tree_1 = create_view(create_and_fill("true")); // Rebuild the stores and views
tree_2 = create_view(create_and_fill("false"));

gtk_box_pack_start(GTK_BOX(box),tree_1,FALSE,FALSE,0);
gtk_box_pack_start(GTK_BOX(box),tree_2,FALSE,FALSE,0);

gtk_box_reorder_child(GTK_BOX(box), tree_1, x); // X being the relative position of your treeview
gtk_box_reorder_child(GTK_BOX(box), tree_2, x);
gtk_widget_show_all(box);
}
</code>```

Body:
I'm new at GUI development and I've been working on a project with gtk+ 3 for some days, but I'm stuck at this point.

My app contains two treeviews, the data in the rows is obtained from an sql query, by right clicking on a row a popup-menu appears, giving the option to set the data as "known", updating the database table.

The previous data now should belong in the other treeview, and so it does when the app is restarted, but I'm looking to do it in real time.

Is it possible to update/refresh the data in a treeview?

The model is obtained with the function:

static GtkTreeStore* create_and_fill(char* known)
{
  GtkTreeStore* store;
  GtkTreeIter iter;
  GtkWidget* tree;
  store = gtk_tree_store_new(2,G_TYPE_STRING,G_TYPE_STRING);

  char source_mac[50] = {0};
  char source_ip[50] = {0};
  int num_fields;

  char query[300] = {0};
  sprintf(query, "select mac,ip from hosts where known=%s", known);
  if(mysql_query(conn, query))
  {
    fprintf(stderr,"%s\n", mysql_error(conn));
  }
  res = mysql_store_result(conn);
  num_fields = mysql_num_fields(res);

  while((row = mysql_fetch_row(res)))
  {
    sprintf(source_mac,"%s", row[0]);
    sprintf(source_ip,"%s", row[1]);
    gtk_tree_store_append(store, &iter, NULL);
    gtk_tree_store_set(store, &iter, MAC_ADDRESS, source_mac, IP_ADDRESS, source_ip,-1);
  }
  gtk_tree_store_append(store, &iter, NULL);
  mysql_free_result(res);
  return store;
}

Body:
I simply ended up doing an ugly patch.
I created a function that removes the treeviews, rebuilds the stores and packs them again.

static void refresh()
{
gtk_container_remove(GTK_CONTAINER(box), tree_1);
gtk_container_remove(GTK_CONTAINER(box), tree_2);

tree_1 = create_view(create_and_fill("true")); // Rebuild the stores and views
tree_2 = create_view(create_and_fill("false"));

gtk_box_pack_start(GTK_BOX(box),tree_1,FALSE,FALSE,0);
gtk_box_pack_start(GTK_BOX(box),tree_2,FALSE,FALSE,0);

gtk_box_reorder_child(GTK_BOX(box), tree_1, x); // X being the relative position of your treeview
gtk_box_reorder_child(GTK_BOX(box), tree_2, x);
gtk_widget_show_all(box);
}


问:
In OfficeJS, can you retrieve the range of a binding object?
Targeted towards Word Online, but any pointers for Excel/PPT would be helpful as well.

Essentially, is it possible to treat the text within a binding object as a range?  Thus, being able to select it all as well as move the caret to the beginning/end.

I was envisioning the code to have something to the effect of:

```<code>Office.select(“myBindingID”, function error(){}).getAsRange().select(“End”);
</code>```

答:
There is a difference between the host-specific Office 2016+ wave of APIs and the "common" (2013) APIs.

In Excel, bindings (and everything from the common API set) is exposed to the new OM, and connect with other aspects of the OM (e.g., Ranges).  So there, you could absolutely do it:

```<code>    await Excel.run(async (context) => {
        let binding = context.workbook.bindings.getItem("TestBinding");
        let range = binding.getRange();
        range.load("address");
        range.select();

        await context.sync();

        OfficeHelpers.UI.notify("Binding range address is " + range.address);
    });
</code>```

It appears that Word does not offer binding support, however, in the Word-specific APIs.  If you want to be doubly-sure, you may want to ask a separate Stackoverflow question, something like "Does WordApi (Office 2016+) support Bindings?".

For Excel, you can try an expanded version of the above snippet live in literally five clicks via the recently-launched Script Lab tool (https://aka.ms/getscriptlab). Simply install the Script Lab add-in (free), then choose "Import" in the navigation menu, and use the following GIST URL: https://gist.github.com/Zlatkovsky/7701ceddae360ad3883ca867f3831a6f.  See more info about importing snippets to Script Lab.

UPDATE:

Regarding @codex's question about whether it's possible to combine an Office 2013 method (addFromPromptAsync) with the new Office 2016 wave of APIs:  yes it is.  You can nest the call into the 2013 callback, though I personally prefer to wrap it in a Promise instead, as follows (see top half of the code), followed by then using an Excel.run for the new APIs (identical to what I was using before):

```<code>    await new Promise((resolve, reject) => {
        Office.context.document.bindings.addFromPromptAsync(
            Office.BindingType.Matrix,
            { id: "TestBinding" },
            (result) => {
                if (result.status === Office.AsyncResultStatus.Succeeded) {
                    resolve();
                } else {
                    reject();
                }
            }
        )
    })

    await Excel.run(async (context) => {
        let binding = context.workbook.bindings.getItem("TestBinding");
        let range = binding.getRange();
        range.load("address");
        range.select();

        await context.sync();

        OfficeHelpers.UI.notify("Binding range address is " + range.address);
    });
</code>```

You can try it out with Script Lab, same instructions as above, at https://gist.github.com/Zlatkovsky/24f2297cecea181edcc165c6c0df6da0

PS: If you're new to wrapping callbacks with Promises, there is a chapter devoted to a JS/TS and Promises Primer -- including a section specifically about creating a new Promise -- in the book "Building Office Add-ins using Office.js" (https://leanpub.com/buildingofficeaddins).  Disclaimer, I am the author of said book; but I do think that readers will find a lot of value in it, both for getting started with JS/TS/Promise concepts, and for the "meat" of the book -- on the core concepts that make up the Office 2016 wave of APIs.

Body:
Targeted towards Word Online, but any pointers for Excel/PPT would be helpful as well.

Essentially, is it possible to treat the text within a binding object as a range?  Thus, being able to select it all as well as move the caret to the beginning/end.

I was envisioning the code to have something to the effect of:

Office.select(“myBindingID”, function error(){}).getAsRange().select(“End”);

Body:
There is a difference between the host-specific Office 2016+ wave of APIs and the "common" (2013) APIs.

In Excel, bindings (and everything from the common API set) is exposed to the new OM, and connect with other aspects of the OM (e.g., Ranges).  So there, you could absolutely do it:

    await Excel.run(async (context) => {
        let binding = context.workbook.bindings.getItem("TestBinding");
        let range = binding.getRange();
        range.load("address");
        range.select();

        await context.sync();

        OfficeHelpers.UI.notify("Binding range address is " + range.address);
    });

It appears that Word does not offer binding support, however, in the Word-specific APIs.  If you want to be doubly-sure, you may want to ask a separate Stackoverflow question, something like "Does WordApi (Office 2016+) support Bindings?".

For Excel, you can try an expanded version of the above snippet live in literally five clicks via the recently-launched Script Lab tool (https://aka.ms/getscriptlab). Simply install the Script Lab add-in (free), then choose "Import" in the navigation menu, and use the following GIST URL: https://gist.github.com/Zlatkovsky/7701ceddae360ad3883ca867f3831a6f.  See more info about importing snippets to Script Lab.

UPDATE:

Regarding @codex's question about whether it's possible to combine an Office 2013 method (addFromPromptAsync) with the new Office 2016 wave of APIs:  yes it is.  You can nest the call into the 2013 callback, though I personally prefer to wrap it in a Promise instead, as follows (see top half of the code), followed by then using an Excel.run for the new APIs (identical to what I was using before):

    await new Promise((resolve, reject) => {
        Office.context.document.bindings.addFromPromptAsync(
            Office.BindingType.Matrix,
            { id: "TestBinding" },
            (result) => {
                if (result.status === Office.AsyncResultStatus.Succeeded) {
                    resolve();
                } else {
                    reject();
                }
            }
        )
    })

    await Excel.run(async (context) => {
        let binding = context.workbook.bindings.getItem("TestBinding");
        let range = binding.getRange();
        range.load("address");
        range.select();

        await context.sync();

        OfficeHelpers.UI.notify("Binding range address is " + range.address);
    });

You can try it out with Script Lab, same instructions as above, at https://gist.github.com/Zlatkovsky/24f2297cecea181edcc165c6c0df6da0

PS: If you're new to wrapping callbacks with Promises, there is a chapter devoted to a JS/TS and Promises Primer -- including a section specifically about creating a new Promise -- in the book "Building Office Add-ins using Office.js" (https://leanpub.com/buildingofficeaddins).  Disclaimer, I am the author of said book; but I do think that readers will find a lot of value in it, both for getting started with JS/TS/Promise concepts, and for the "meat" of the book -- on the core concepts that make up the Office 2016 wave of APIs.


问:
Add/Read configuration from an encrypted file
I went down the path of creating my own ConfigurationProvider, which encrypts a file if it hasn't been already encrypted, and is also able to decrypt it.

I am now struggling coming up with a way of adding my decrypted appsettings.json content (decrypted string) to the configuration in a similar way that that .AddJsonFile() does.

Ultimately, I would like to be able to call .AddEncryptedJson("appsettings.json") in my Startup.cs, which would decrypt the file and add all the configuration necessary.

```<code>public class CustomConfigProvider : ConfigurationProvider, IConfigurationSource
{
    private readonly RSA _pubKey;
    private readonly RSA _privKey;
    private readonly string _filePath;

    public CustomConfigProvider(string filePath)
    {
        var cert = new X509Certificate2(Path.Combine(Directory.GetCurrentDirectory(), "certs", "IdentityServer4Auth.pfx"), "test");
        _pubKey = RSACertificateExtensions.GetRSAPublicKey(cert);
        _privKey = RSACertificateExtensions.GetRSAPrivateKey(cert);
        _filePath = filePath;
    }

    public override void Load()
    {
        Data = UnencryptMyConfiguration();
    }

    private IDictionary<string, string> UnencryptMyConfiguration()
    {
        EncryptIfNotEncrypted();

        var configFileBytes = File.ReadAllBytes(_filePath);

        var decryptedData = _privKey.Decrypt(configFileBytes, RSAEncryptionPadding.Pkcs1);
        var jsonString = Encoding.UTF8.GetString(decryptedData);

        jsonString = jsonString.Trim(new char[] { '\uFEFF', '\u200B' });
        dynamic result = JsonConvert.DeserializeObject(jsonString);
        Dictionary<string, string> dictObj = result.ToObject<Dictionary<string, string>>();
        return dictObj;
    }

    private void EncryptIfNotEncrypted()
    {
        var configFileBytes = File.ReadAllBytes(_filePath);

        // Check if encrypted
        try
        {
            _privKey.Decrypt(configFileBytes, RSAEncryptionPadding.Pkcs1);
        }
        catch
        {
            var encryptedData =
                _pubKey.Encrypt(configFileBytes, RSAEncryptionPadding.Pkcs1);

            using (var fs = new FileStream(_filePath, FileMode.Create, FileAccess.Write))
            {
                fs.Write(encryptedData, 0, encryptedData.Length);
            }
        }
    }
    public IConfigurationProvider Build(IConfigurationBuilder builder)
    {
        return new CustomConfigProvider(_filePath);
    }
}

public static class CustomConfigProviderExtensions
{
    public static IConfigurationBuilder AddEncryptedJson(this IConfigurationBuilder builder, string filePath)
    {
        return builder.Add(new CustomConfigProvider(filePath));
    }
}
</code>```

答:
You could solve this by taking a peek at the internal JsonConfigurationFileParser class here at the aspnet/Configuration repository.
By creating a similar class in your project, you'll be able to successfully parse the decrypted JSON string.

To use the parser, simply feed the jsonString as a Stream to its Parse()method. Your UnencryptMyConfiguration() method would then look like this:

```<code>private IDictionary<string, string> UnencryptMyConfiguration()
{
    EncryptIfNotEncrypted();

    var configFileBytes = File.ReadAllBytes(_filePath);

    var decryptedData = _privKey.Decrypt(configFileBytes, RSAEncryptionPadding.Pkcs1);
    var jsonString = Encoding.UTF8.GetString(decryptedData);

    //treat the decrypted string as a Stream to let JsonConfigurationFileParser handle it
    using (MemoryStream stream = new MemoryStream())
    {
        var parser = new JsonConfigurationFileParser();
        StreamWriter writer = new StreamWriter(stream);
        writer.Write(jsonString);
        writer.Flush();
        stream.Position = 0;
        return parser.Parse(stream);
    };
}
</code>```

Body:
I went down the path of creating my own ConfigurationProvider, which encrypts a file if it hasn't been already encrypted, and is also able to decrypt it.

I am now struggling coming up with a way of adding my decrypted appsettings.json content (decrypted string) to the configuration in a similar way that that .AddJsonFile() does.

Ultimately, I would like to be able to call .AddEncryptedJson("appsettings.json") in my Startup.cs, which would decrypt the file and add all the configuration necessary.

public class CustomConfigProvider : ConfigurationProvider, IConfigurationSource
{
    private readonly RSA _pubKey;
    private readonly RSA _privKey;
    private readonly string _filePath;

    public CustomConfigProvider(string filePath)
    {
        var cert = new X509Certificate2(Path.Combine(Directory.GetCurrentDirectory(), "certs", "IdentityServer4Auth.pfx"), "test");
        _pubKey = RSACertificateExtensions.GetRSAPublicKey(cert);
        _privKey = RSACertificateExtensions.GetRSAPrivateKey(cert);
        _filePath = filePath;
    }

    public override void Load()
    {
        Data = UnencryptMyConfiguration();
    }

    private IDictionary<string, string> UnencryptMyConfiguration()
    {
        EncryptIfNotEncrypted();

        var configFileBytes = File.ReadAllBytes(_filePath);

        var decryptedData = _privKey.Decrypt(configFileBytes, RSAEncryptionPadding.Pkcs1);
        var jsonString = Encoding.UTF8.GetString(decryptedData);

        jsonString = jsonString.Trim(new char[] { '\uFEFF', '\u200B' });
        dynamic result = JsonConvert.DeserializeObject(jsonString);
        Dictionary<string, string> dictObj = result.ToObject<Dictionary<string, string>>();
        return dictObj;
    }

    private void EncryptIfNotEncrypted()
    {
        var configFileBytes = File.ReadAllBytes(_filePath);

        // Check if encrypted
        try
        {
            _privKey.Decrypt(configFileBytes, RSAEncryptionPadding.Pkcs1);
        }
        catch
        {
            var encryptedData =
                _pubKey.Encrypt(configFileBytes, RSAEncryptionPadding.Pkcs1);

            using (var fs = new FileStream(_filePath, FileMode.Create, FileAccess.Write))
            {
                fs.Write(encryptedData, 0, encryptedData.Length);
            }
        }
    }
    public IConfigurationProvider Build(IConfigurationBuilder builder)
    {
        return new CustomConfigProvider(_filePath);
    }
}

public static class CustomConfigProviderExtensions
{
    public static IConfigurationBuilder AddEncryptedJson(this IConfigurationBuilder builder, string filePath)
    {
        return builder.Add(new CustomConfigProvider(filePath));
    }
}

Body:
You could solve this by taking a peek at the internal JsonConfigurationFileParser class here at the aspnet/Configuration repository.
By creating a similar class in your project, you'll be able to successfully parse the decrypted JSON string.

To use the parser, simply feed the jsonString as a Stream to its Parse()method. Your UnencryptMyConfiguration() method would then look like this:

private IDictionary<string, string> UnencryptMyConfiguration()
{
    EncryptIfNotEncrypted();

    var configFileBytes = File.ReadAllBytes(_filePath);

    var decryptedData = _privKey.Decrypt(configFileBytes, RSAEncryptionPadding.Pkcs1);
    var jsonString = Encoding.UTF8.GetString(decryptedData);

    //treat the decrypted string as a Stream to let JsonConfigurationFileParser handle it
    using (MemoryStream stream = new MemoryStream())
    {
        var parser = new JsonConfigurationFileParser();
        StreamWriter writer = new StreamWriter(stream);
        writer.Write(jsonString);
        writer.Flush();
        stream.Position = 0;
        return parser.Parse(stream);
    };
}


问:
Is it possible to use SysEx messages in WebMidi on Cordova Android?
I'm trying to port a web application to a native Android application using Cordova. It's fairly simple, primarily just sending Midi messages to a connected device. I know the WebMidi API is only supported on recent versions of Webkit on Android, and I have been testing on 5.1. I've managed to prove that the basics work by running the original web version on Chrome on the device, it works fine.

The problem when running in Cordova is the messages themselves are not sent for some reason, no error, just not getting there. I know the API is working, as a separate part of the application lists the connected devices and presents a dropdown list to choose from, this works fine, and recognises the connected Midi device. However, when I send messages they don't have the desired effect on the Midi device. They are SysEx messages, which I believe needs additional permissions, android.webkit.resource.MIDI_SYSEX, is it possible that this is enabled on Chrome but not on the Cordova application? I've tried adding this permission to the ./config.xml, and ./platform/android/AndroidManifest.xml but to no avail, it doesn't seem to have any effect, and doesn't even show as an additional permission when installed.

Based on various searches, I've also tried installing the Crosswalk plugin, but couldn't get that to work at all, not even the device listing.

Any thoughts welcome.

答:
The problem you're facing is that you won't even be prompted for midi sysex permission unless you meet certain criteria. You either have to be accessing your web midi code via a localhost, OR on an https URL. Sysex is potentially harmful, so they have used this as a minimum security requirement.

I had it working on android by opening a URL on my to my dev PC (using a self signed SSL cert on wamp). It gives the security prompt for sysex and then works as expected, so chrome on android works for sure. Crosswalk Cordova however, I'm not so sure.

I've tried running a little webserver in my cordova app (on Android), starting the webserver on 127.0.0.1:8080 and then connected to it using chrome (separately on the same device). Feels tantalizingly close, but I need it to run in my app!

My attempts to run an iFrame with the webserver's URL (http://127.0.0.1:8080) have failed. it's just not found. No security error, so doesn't seem to be to do with white-listing, although I need to look into that further to be sure.

It seems that the webserver plugin is running successfully, but is not visible from within the app.

You should have a play with this, and see if it gets you anywhere...

Or perhaps you'll find another one that is visible from within the app itself.
The alternative approach is to use a socket server to connect to your computer, and have the midi devices connected to it. Not exactly portable though!


问:
Pyspark - create new column from operations of DataFrame columns gives error "Column is not iterable"
I have a PySpark DataFrame and I have tried many examples showing how to create a new column based on operations with existing columns, but none of them seem to work.

So I have t̶w̶o̶ one questions:

1- Why doesn't this code work?

```<code>from pyspark import SparkContext, SparkConf
from pyspark.sql import SQLContext
import pyspark.sql.functions as F

sc = SparkContext()
sqlContext = SQLContext(sc)

a = sqlContext.createDataFrame([(5, 5, 3)], ['A', 'B', 'C'])
a.withColumn('my_sum', F.sum(a[col] for col in a.columns)).show()
</code>```

I get the error:
TypeError: Column is not iterable

EDIT: Answer 1

I found out how to make this work. I have to use the native Python sum function. a.withColumn('my_sum', F.sum(a[col] for col in a.columns)).show(). It works, but I have no idea why.

2- If there is a way to make this sum work, how can I write a udf function to do this (and add the result to a new column of a DataFrame)?

```<code>import numpy as np
def my_dif(row):
    d = np.diff(row) # creates an array of differences element by element
    return d.mean() # returns the mean of the array
</code>```

I am using Python 3.6.1 and Spark 2.1.1.

Thank you!

答:
Your problem is in this part for col in a.columns cuz you cannot iterate the result, so you must:

```<code>a = a.withColumn('my_sum', a.A + a.B + a.C)
</code>```

Body:
I have a PySpark DataFrame and I have tried many examples showing how to create a new column based on operations with existing columns, but none of them seem to work.

So I have t̶w̶o̶ one questions:

1- Why doesn't this code work?

from pyspark import SparkContext, SparkConf
from pyspark.sql import SQLContext
import pyspark.sql.functions as F

sc = SparkContext()
sqlContext = SQLContext(sc)

a = sqlContext.createDataFrame([(5, 5, 3)], ['A', 'B', 'C'])
a.withColumn('my_sum', F.sum(a[col] for col in a.columns)).show()

I get the error:
TypeError: Column is not iterable

EDIT: Answer 1

I found out how to make this work. I have to use the native Python sum function. a.withColumn('my_sum', F.sum(a[col] for col in a.columns)).show(). It works, but I have no idea why.

2- If there is a way to make this sum work, how can I write a udf function to do this (and add the result to a new column of a DataFrame)?

import numpy as np
def my_dif(row):
    d = np.diff(row) # creates an array of differences element by element
    return d.mean() # returns the mean of the array

I am using Python 3.6.1 and Spark 2.1.1.

Thank you!

Body:
Your problem is in this part for col in a.columns cuz you cannot iterate the result, so you must:

a = a.withColumn('my_sum', a.A + a.B + a.C)


问:
“You may need an appropriate loader to handle this file type” with Webpack and Babel
I'm upgrading from an arcane version of webpack to webpack 2 and I'm getting an error:

```<code>ERROR in ./scripts/app.js
Module parse failed: /Users/zackshapiro/dev/glimpse-electron/node_modules/eslint-loader/index.js!/Users/zackshapiro/dev/glimpse-electron/scripts/app.js Unexpected token (32:4)
You may need an appropriate loader to handle this file type.
|
| render((
|     <Provider store={store}>
|         <Home />
|     </Provider>
 @ multi (webpack)-dev-server/client?http://localhost:8081 webpack/hot/dev-server ./scripts/app.js
</code>```

My webpack.config.js looks like this:

```<code>const webpack = require('webpack');
const path = require('path');

console.log(path.resolve(__dirname, 'public/built'));
console.log("we here");

module.exports = {
  entry: {
    app: ['webpack/hot/dev-server', './scripts/app.js']
  },

  output: {
    // path: './public/built',
    path: path.resolve(__dirname, 'public/built'),
    filename: 'bundle.js',
    publicPath: 'http://localhost:8080/built/'
  },

  devServer: {
    contentBase: './public',
    publicPath: 'http://localhost:8080/built/'
  },

  module: {
    rules: [
        {
            test: /\.jsx?$/,
            enforce: "pre",
            loader: "eslint-loader",
            exclude: /node_modules/
        },
    ],
    loaders: [
      {
        test: /\.jsx?$/,
        loader: 'babel-loader',
        exclude: /node_modules/,
        query: {
          presets: ['react', 'es2015', 'stage-3']
        }
      },
      { test: /\.css$/, loader: 'style-loader!css-loader' },
      { test: /\.scss$/, loader: 'style-loader!css-loader!sass-loader'},
      { test: /\.(ttf|eot|otf|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: "file-loader" }
    ]
  },

  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new webpack.IgnorePlugin(new RegExp("^(fs|ipc)$")),
    new webpack.LoaderOptionsPlugin({
        options: {
            eslint: {
                failOnWarning: false,
                failOnError: true
            }
        }
    })
  ]
}
</code>```

And my app.js looks like this:

```<code>require('../styles/main.scss');
require('../styles/menubar.scss');
require('../styles/panel.scss');
require('../styles/sky.scss');
require('../styles/dock.scss');
require('../styles/sector.scss');
require('../styles/slot.scss');
require('../styles/element_builder.scss');

'use strict';

import 'babel-polyfill';
import React from 'react';
import {render} from 'react-dom';
import {Provider} from 'react-redux';
import {compose, createStore, applyMiddleware} from 'redux';
import createSagaMiddleware from 'redux-saga';

import reducer from './entities/reducers';
import sagas from './entities/sagas';

import Home from './containers/home';

const sagaMiddleware = createSagaMiddleware();

const composedCreateStore = compose(applyMiddleware(sagaMiddleware))(createStore);

const store = composedCreateStore(reducer, {});
sagaMiddleware.run(sagas);

render((
    <Provider store={store}>
        <Home />
    </Provider>
), document.getElementById('content'));
</code>```

I don't have a .babelrc file in my root directory because I have that object in my loaders in webpack.config.js

Any suggestions on how to fix this would be very welcome. Thanks!

答:
module.rules replaces module.loaders in Webpack 2, so it's possible that by providing both Webpack isn't using module.loaders (which is there for backwards-compatibility) at all - try moving the rules you currently have in module.loaders into module.rules instead.

Edit: peeking inside the current version of Webpack's NormalModuleFactory, this is what it's doing:

```<code>this.ruleSet = new RuleSet(options.rules || options.loaders);
</code>```

Body:
I'm upgrading from an arcane version of webpack to webpack 2 and I'm getting an error:

ERROR in ./scripts/app.js
Module parse failed: /Users/zackshapiro/dev/glimpse-electron/node_modules/eslint-loader/index.js!/Users/zackshapiro/dev/glimpse-electron/scripts/app.js Unexpected token (32:4)
You may need an appropriate loader to handle this file type.
|
| render((
|     <Provider store={store}>
|         <Home />
|     </Provider>
 @ multi (webpack)-dev-server/client?http://localhost:8081 webpack/hot/dev-server ./scripts/app.js

My webpack.config.js looks like this:

const webpack = require('webpack');
const path = require('path');

console.log(path.resolve(__dirname, 'public/built'));
console.log("we here");

module.exports = {
  entry: {
    app: ['webpack/hot/dev-server', './scripts/app.js']
  },

  output: {
    // path: './public/built',
    path: path.resolve(__dirname, 'public/built'),
    filename: 'bundle.js',
    publicPath: 'http://localhost:8080/built/'
  },

  devServer: {
    contentBase: './public',
    publicPath: 'http://localhost:8080/built/'
  },

  module: {
    rules: [
        {
            test: /\.jsx?$/,
            enforce: "pre",
            loader: "eslint-loader",
            exclude: /node_modules/
        },
    ],
    loaders: [
      {
        test: /\.jsx?$/,
        loader: 'babel-loader',
        exclude: /node_modules/,
        query: {
          presets: ['react', 'es2015', 'stage-3']
        }
      },
      { test: /\.css$/, loader: 'style-loader!css-loader' },
      { test: /\.scss$/, loader: 'style-loader!css-loader!sass-loader'},
      { test: /\.(ttf|eot|otf|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: "file-loader" }
    ]
  },

  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new webpack.IgnorePlugin(new RegExp("^(fs|ipc)$")),
    new webpack.LoaderOptionsPlugin({
        options: {
            eslint: {
                failOnWarning: false,
                failOnError: true
            }
        }
    })
  ]
}

And my app.js looks like this:

require('../styles/main.scss');
require('../styles/menubar.scss');
require('../styles/panel.scss');
require('../styles/sky.scss');
require('../styles/dock.scss');
require('../styles/sector.scss');
require('../styles/slot.scss');
require('../styles/element_builder.scss');

'use strict';

import 'babel-polyfill';
import React from 'react';
import {render} from 'react-dom';
import {Provider} from 'react-redux';
import {compose, createStore, applyMiddleware} from 'redux';
import createSagaMiddleware from 'redux-saga';

import reducer from './entities/reducers';
import sagas from './entities/sagas';

import Home from './containers/home';

const sagaMiddleware = createSagaMiddleware();

const composedCreateStore = compose(applyMiddleware(sagaMiddleware))(createStore);

const store = composedCreateStore(reducer, {});
sagaMiddleware.run(sagas);

render((
    <Provider store={store}>
        <Home />
    </Provider>
), document.getElementById('content'));

I don't have a .babelrc file in my root directory because I have that object in my loaders in webpack.config.js

Any suggestions on how to fix this would be very welcome. Thanks!

Body:
module.rules replaces module.loaders in Webpack 2, so it's possible that by providing both Webpack isn't using module.loaders (which is there for backwards-compatibility) at all - try moving the rules you currently have in module.loaders into module.rules instead.

Edit: peeking inside the current version of Webpack's NormalModuleFactory, this is what it's doing:

this.ruleSet = new RuleSet(options.rules || options.loaders);


问:
watchOS 2: haptic feedback in background
I think I know the answer to this question already, but I wanted to ask just to be thorough.

Consider the Apple Watch built-in Maps app. When you're using turn-by-turn directions, when it's time to turn left or right, the watch plays a custom haptic pattern - even though the screen is off and the app is backgrounded. Another example is while you're doing a workout - if you've set a goal, you'll get a light tap on your wrist when you get 50% there and 100% there, even if you're not looking at the watch at the time (screen off, app backgrounded).

In watchOS 2, is there any way for us 3rd party developers to have an app play a certain haptic pattern when the screen is off and the app is backgrounded? I know the playHaptic: method works while the app is active to let you play several different kinds of haptic patterns, and I know that while the app is inactive, you can have a notification come in - but the notification would only ever play the 'notification' haptic feeling, no choice in that.

答:
Just to post an update to my own question a couple years later - in watchOS 3 workout apps were granted background execution, but no haptics (I think).

In watchOS 4, workout apps, audio recording apps and navigation apps have background execution; navigation apps can send haptics in the background. Furthermore, the "frontmost app" (app last used which still appears if wrist is raised within 2 minutes, or 8 if extended frontmost time is enabled) has some privileges for sending haptics at the conclusion of a WatchConnectivity or NSURLSession data transfer, or when a notification comes in. See the docs for details.


问:
DebugActiveProcess crash
I'm trying to debug a child process while it's in a suspended state. The problem is that when I attempt to do that, the application doesn't start (it starts but exits instantly). That helps against reverse engineering, but however I can't manage doing it.

```<code>static void DebuggingTest(PROCESS_INFORMATION pi, int imageBase, int sizeOfHeaders)
{
    int oldProtection = 0;
    const uint STATUS_GUARD_PAGE_VIOLATION = 0x80000001;
    const int DBG_CONTINUE = 0x00010002;
    DEBUG_EVENT evt = new DEBUG_EVENT();
    if (!DebugActiveProcess(Convert.ToInt32(pi.dwProcessId)))
        throw new Win32Exception();
    else
        MessageBox.Show(pi.dwProcessId + " process is being debugged.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);

    while (true)
    {
        if (!WaitForDebugEvent(out evt, -1))
            throw new Win32Exception();
        else
            MessageBox.Show("WaitForDebugEvent executed.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);

        switch (evt.dwDebugEventCode)
        {
            case DebugEventType.CREATE_PROCESS_DEBUG_EVENT:
                //if (!VirtualProtectEx(pi.hProcess, imageBase, sizeOfHeaders, 320, ref oldProtection))
                //  throw new Exception();
                ResumeThread(pi.hThread);
                MessageBox.Show("CREATE_PROCESS_DEBUG_EVENT executed.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                break;
            case DebugEventType.EXCEPTION_DEBUG_EVENT:
                if (evt.Exception.ExceptionRecord.ExceptionCode == STATUS_GUARD_PAGE_VIOLATION)
                {
                    if (!VirtualProtectEx(pi.hProcess, imageBase, sizeOfHeaders, 320, ref oldProtection))
                        throw new Exception();
                }
                MessageBox.Show("EXCEPTION_DEBUG_EVENT executed.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                break;
            case DebugEventType.EXIT_PROCESS_DEBUG_EVENT:
                if (!DebugActiveProcessStop(Convert.ToInt32(pi.dwProcessId)))
                    throw new Win32Exception();
                if (!TerminateProcess(pi.hProcess, 0))
                    throw new Win32Exception();
                MessageBox.Show("EXIT_PROCESS_DEBUG_EVENT executed.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                break;
            case DebugEventType.LOAD_DLL_DEBUG_EVENT:
                if (CloseHandle(evt.LoadDll.hFile))
                    MessageBox.Show("CloseHandle executed.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                break;
        }

        if (ContinueDebugEvent(evt.dwProcessId, evt.dwThreadId, DBG_CONTINUE))
            MessageBox.Show("Last ContinueDebugEvent executed.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
}
</code>```

Edit: VirtualProtectEx calls are failing, they are the actual problem. If I comment their lines, the application executes. Also it is lagging, probably because of the debugging loop. Is there a solution for it?

Edit2: I edited the code as you suggested me, apart from DEBUG_PROCESS, because it stops the whole process, I can't even kill it through Task Manager, the only way to kill it, is to restart PC. Perhaps, I'm doing something wrong, but I don't know what. So the order the messageboxes appear: DebugActiveProcess executed -> WaitForDebugEvent executed -> CREATE_PROCESS_DEBUG_EVENT executed -> Last ContinueDebugEvent executed. Then Wait... -> CloseHandle -> ContinueDebug...

答:
1) when you want debug process created via CreateProcess set the DEBUG_PROCESS in dwCreationFlags

2) never call DebugActiveProcess in this case - this api internal create remote thread in process - DbgUiRemoteBreakIn - so process begin initialize not in it main thread but on this thread. say on xp this cause process initialization fail always. latter (begin form win7 ?) this fixed.

3) ContinueDebugEvent need call always, after every debug event. after EXIT_PROCESS_DEBUG_EVENT - also - need understand that this message send to you last thread in process when it exited. and he wait for your call ContinueDebugEvent - process still alive and not terminated when you got EXIT_PROCESS_DEBUG_EVENT - so you must have one common call to ContinueDebugEvent after swith

4) what you try todo with VirtualProtectEx must make infinite STATUS_GUARD_PAGE_VIOLATION exceptions. so even not look more - main logic of "protection" is invalid

5) handle LOAD_DLL_DEBUG_EVENT is mandatory - you must close handle  (hFile to the loaded DLL)

6) on CREATE_PROCESS_DEBUG_EVENT you also must close handle to file

7) when we call CreateProcess with DEBUG_PROCESS flag - use the CREATE_SUSPENDED - absolutely senseless - for what ?? usually this flag used for do some task with process, before it thread begin execute in user mode and after this call ResumeThread. but when we use DEBUG_PROCESS initial thread in process, when it begin execute (yet in kernel mode) send to us CREATE_PROCESS_DEBUG_EVENT and wait for reply (until debugger not call ContinueDebugEvent. as result all special task with process we can done in CREATE_PROCESS_DEBUG_EVENT handler. misunderstandings how windows work internal leads to gross errors

Title: DebugActiveProcess crash

Body:
I'm trying to debug a child process while it's in a suspended state. The problem is that when I attempt to do that, the application doesn't start (it starts but exits instantly). That helps against reverse engineering, but however I can't manage doing it.

static void DebuggingTest(PROCESS_INFORMATION pi, int imageBase, int sizeOfHeaders)
{
    int oldProtection = 0;
    const uint STATUS_GUARD_PAGE_VIOLATION = 0x80000001;
    const int DBG_CONTINUE = 0x00010002;
    DEBUG_EVENT evt = new DEBUG_EVENT();
    if (!DebugActiveProcess(Convert.ToInt32(pi.dwProcessId)))
        throw new Win32Exception();
    else
        MessageBox.Show(pi.dwProcessId + " process is being debugged.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);

    while (true)
    {
        if (!WaitForDebugEvent(out evt, -1))
            throw new Win32Exception();
        else
            MessageBox.Show("WaitForDebugEvent executed.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);

        switch (evt.dwDebugEventCode)
        {
            case DebugEventType.CREATE_PROCESS_DEBUG_EVENT:
                //if (!VirtualProtectEx(pi.hProcess, imageBase, sizeOfHeaders, 320, ref oldProtection))
                //  throw new Exception();
                ResumeThread(pi.hThread);
                MessageBox.Show("CREATE_PROCESS_DEBUG_EVENT executed.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                break;
            case DebugEventType.EXCEPTION_DEBUG_EVENT:
                if (evt.Exception.ExceptionRecord.ExceptionCode == STATUS_GUARD_PAGE_VIOLATION)
                {
                    if (!VirtualProtectEx(pi.hProcess, imageBase, sizeOfHeaders, 320, ref oldProtection))
                        throw new Exception();
                }
                MessageBox.Show("EXCEPTION_DEBUG_EVENT executed.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                break;
            case DebugEventType.EXIT_PROCESS_DEBUG_EVENT:
                if (!DebugActiveProcessStop(Convert.ToInt32(pi.dwProcessId)))
                    throw new Win32Exception();
                if (!TerminateProcess(pi.hProcess, 0))
                    throw new Win32Exception();
                MessageBox.Show("EXIT_PROCESS_DEBUG_EVENT executed.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                break;
            case DebugEventType.LOAD_DLL_DEBUG_EVENT:
                if (CloseHandle(evt.LoadDll.hFile))
                    MessageBox.Show("CloseHandle executed.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                break;
        }

        if (ContinueDebugEvent(evt.dwProcessId, evt.dwThreadId, DBG_CONTINUE))
            MessageBox.Show("Last ContinueDebugEvent executed.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
}

Edit: VirtualProtectEx calls are failing, they are the actual problem. If I comment their lines, the application executes. Also it is lagging, probably because of the debugging loop. Is there a solution for it?

Edit2: I edited the code as you suggested me, apart from DEBUG_PROCESS, because it stops the whole process, I can't even kill it through Task Manager, the only way to kill it, is to restart PC. Perhaps, I'm doing something wrong, but I don't know what. So the order the messageboxes appear: DebugActiveProcess executed -> WaitForDebugEvent executed -> CREATE_PROCESS_DEBUG_EVENT executed -> Last ContinueDebugEvent executed. Then Wait... -> CloseHandle -> ContinueDebug...


问:
Can undefined behaviour cause an exception in a function defined as never throwing an exception?
I was looking at a description of delete[] and it says:

Exception safety

  No-throw guarantee: this function never throws exceptions.

But it adds:

Notice that an invalid value of ptr causes undefined behavior.

I suspect that UB can include throwing an exception and the guarantee is only good for valid pointers, but I just thought I'd check.

答: "Undefined behavior" means that the language definition does not tell you what the code does. So, yes, anything can happen, including blowing past a noexcept specifier. After all, there are no rules... (well, your compiler may provide rules, but relying on that is not portable).


问:
Will using a parallel stream on a single-core processor be slower than using a sequential stream?
I am applying an operation to every element in a very large LinkedList<LinkedList<Double>>:

```<code>list.stream().map(l -> l.stream().filter(d ->
(Collections.max(l) - d) < 5)
.collect(Collectors.toCollection(LinkedList::new))).collect(Collectors.toCollection(LinkedList::new));
</code>```

On my computer (quad-core), parallel streams seem to be faster than using sequential streams:

```<code>list.parallelStream().map(l -> l.parallelStream().filter(d ->
(Collections.max(l) - d) < 5)
.collect(Collectors.toCollection(LinkedList::new))).collect(Collectors.toCollection(LinkedList::new));
</code>```

However, not every computer is going to be multi-core. My question is, will using parallel streams on a single-processor computer be noticeably slower than using sequential streams?

答:
Soon we won't be having single core CPU any more. But if you are curious how threading works on single non hyper threaded core then see this answer:
 Why is threading works on a single core CPU?

So to answer your question the run time most likely will be better for sequential processing since it won't be involving thread starting, scheduling and synchronization.

Body:
I am applying an operation to every element in a very large LinkedList<LinkedList<Double>>:

list.stream().map(l -> l.stream().filter(d ->
(Collections.max(l) - d) < 5)
.collect(Collectors.toCollection(LinkedList::new))).collect(Collectors.toCollection(LinkedList::new));

On my computer (quad-core), parallel streams seem to be faster than using sequential streams:

list.parallelStream().map(l -> l.parallelStream().filter(d ->
(Collections.max(l) - d) < 5)
.collect(Collectors.toCollection(LinkedList::new))).collect(Collectors.toCollection(LinkedList::new));

However, not every computer is going to be multi-core. My question is, will using parallel streams on a single-processor computer be noticeably slower than using sequential streams?


问:
FlatList does not re-render untill the list is scrolled
I have a FlatList which is sourced by an array defined in the view's state. The list is filtered by filtering the original array and setting the array in the state with the new filtered array. But the re-render is only called when the list is scrolled. Is there a way to force re-render flatlists ?</p>

```<code>import setsArr from '../../json/sets';
.
.
.
constructor (props) {
  super(props);
  this.state({
    arrToDisplay: setsArr,
  });
}
.
.
.
_filter = (filter,value) => {
  var newArr = setsArr.filter(function(){
                 return (el.filter === value)
               });
  this.setState({
    arrToDisplay: newArr,
  });
}

renderOption = (data) => {
  return (
    <Text>{data.item.name}</Text>
  );
}
render () {
   return (
      .
      .
      .
      <FlatList
        data={this.state.arrToDisplay}
        renderItem={(item) => this.renderOption(item)}}/>
      .
      .
   );
}
</code>```

答:
I found with ListView, FlatList, and SectionList, that changes to the datasource only rendered when the FlatList had a unique key.

I'll be happy if someone posts a proper answer but this is what I'm doing now:

```<code><FlatList
  key={"mylist" + hashOfDataSourceObj}
  ...
</code>```

see https://stackoverflow.com/a/31481960/7223

Body:
I have a FlatList which is sourced by an array defined in the view's state. The list is filtered by filtering the original array and setting the array in the state with the new filtered array. But the re-render is only called when the list is scrolled. Is there a way to force re-render flatlists ?

import setsArr from '../../json/sets';
.
.
.
constructor (props) {
  super(props);
  this.state({
    arrToDisplay: setsArr,
  });
}
.
.
.
_filter = (filter,value) => {
  var newArr = setsArr.filter(function(){
                 return (el.filter === value)
               });
  this.setState({
    arrToDisplay: newArr,
  });
}

renderOption = (data) => {
  return (
    <Text>{data.item.name}</Text>
  );
}
render () {
   return (
      .
      .
      .
      <FlatList
        data={this.state.arrToDisplay}
        renderItem={(item) => this.renderOption(item)}}/>
      .
      .
   );
}

Body:
I found with ListView, FlatList, and SectionList, that changes to the datasource only rendered when the FlatList had a unique key.

I'll be happy if someone posts a proper answer but this is what I'm doing now:

<FlatList
  key={"mylist" + hashOfDataSourceObj}
  ...

see https://stackoverflow.com/a/31481960/7223


问:
How to set code indentation in comment in Emacs?
I am working on different projects, and people in different projects have different indentation preference. I wonder if I can use Emacs' mode line to set the indentation for each file. Any idea?</p>

答:
Another cross IDE option would be editorconfig. For example:

```<code>root = true

[*]
end_of_line = crlf
insert_final_newline = true
charset = gb18030
indent_style = space
indent_size = 2
</code>```

Reference: http://editorconfig.org/

Body:
Another cross IDE option would be editorconfig. For example:

root = true

[*]
end_of_line = crlf
insert_final_newline = true
charset = gb18030
indent_style = space
indent_size = 2

Reference: http://editorconfig.org/