问:
Error TS2497: Module '...' resolves to a non-module entity and cannot be imported using this construct
Given this declaration file promise-retry/index.d.ts, which follows TypeScript's official module-function.d.ts format:

Edit: pasted the wrong code segment for this previously (which is still visible below):

```<code>export = promiseRetry;

declare function promiseRetry(options: Partial<PromiseRetry.NodeRetryOptions>, fn: (retry: PromiseRetry.RetryFn, attempt: number) => Promise<any>): Promise<any>;
declare function promiseRetry(fn: (retry: PromiseRetry.RetryFn, attempt: number) => Promise<any>, options ?: Partial<PromiseRetry.NodeRetryOptions>): Promise<any>;

declare namespace PromiseRetry {
    export interface NodeRetryOptions {
        forever: boolean;
        unref: boolean;
        retries: number;
        factor: number;
        minTimeout: number;
        maxTimeout: number;
        randomize: number | false;
    }

    export type RetryFn = (err: any) => never;
}
</code>```

I find I cannot import NodeRetryOptions nor RetryFn via this syntax:

```<code>import {NodeRetryOptions, RetryFn} from "promise-retry";

let options: NodeRetryOptions = { forever: false };
let retryFn: RetryFn = (err:any)=>{throw "Nobody responds on StackOverflow"};
</code>```

... as it throws the compile error: error TS2497: Module '"promise-retry"' resolves to a non-module entity and cannot be imported using this construct.

I also tried another syntax:

```<code>declare module "promise-retry" {
    export = promiseRetry;

    function promiseRetry(options: Partial<PromiseRetry.NodeRetryOptions>, fn: (retry: PromiseRetry.RetryFn, attempt: number) => Promise<any>): Promise<any>;
    function promiseRetry(fn: (retry: PromiseRetry.RetryFn, attempt: number) => Promise<any>, options ?: Partial<PromiseRetry.NodeRetryOptions>): Promise<any>;

    namespace PromiseRetry {
        export interface NodeRetryOptions {
            forever: boolean;
            unref: boolean;
            retries: number;
            factor: number;
            minTimeout: number;
            maxTimeout: number;
            randomize: number | false;
        }

        export type RetryFn = (err: any) => never;
    }
}
</code>```

But the imports (in a different style) failed too:

```<code>import * as PromiseRetry from "promise-retry";

let options: PromiseRetry.NodeRetryOptions = { forever: false };
let retryFn: PromiseRetry.RetryFn = (err:any)=>{throw "Nobody responds on StackOverflow"};
</code>```

... throwing the very same compiler error.

I've read everything I can find (including the related links here), and I can't get it working. In the words of Trump, "Nobody knew TypeScript imports could be so complicated."

答:
The example you linked to has an important note in its comments:

```<code>/*~ Note that ES6 modules cannot directly export callable functions.
 *~ This file should be imported using the CommonJS-style:
 *~   import x = require('someLibrary');
 *~
 *~ Refer to the documentation to understand common
 *~ workarounds for this limitation of ES6 modules.
 */
</code>```

What you probably want is the following:

```<code>export = PromiseRetry;

declare function PromiseRetry(options: Partial<PromiseRetry.NodeRetryOptions>, fn: (retry: PromiseRetry.RetryFn, attempt: number) => Promise<any>): Promise<any>;
declare function PromiseRetry(fn: (retry: PromiseRetry.RetryFn, attempt: number) => Promise<any>, options ?: Partial<PromiseRetry.NodeRetryOptions>): Promise<any>;

declare namespace PromiseRetry {
    export interface NodeRetryOptions {
        forever: boolean;
        unref?: boolean;
        retries?: number;
        factor?: number;
        minTimeout?: number; // milliseconds
        maxTimeout?: number; // milliseconds|(Number.)Infinity, which is itself of number type.
        randomize?: number | false;
    }

    export type RetryFn = (err: any) => never;
}
</code>```

Note the capitalized PromiseRetry function to match the namespace. Then, to import, use the following line:

```<code>import PromiseRetry = require('promise-retry');
</code>```

Usages must then be prefixed by the namespace as such:

```<code>let options: PromiseRetry.NodeRetryOptions = { forever: false };
let retryFn: PromiseRetry.RetryFn = (err:any) => {throw "Sometimes people respond on StackOverflow"};
</code>```

As a side note, it seems that most packages are leaning against using namespaces to attach types as namespace children of function declarations. Another alternative that would allow you to use a different name for the function and the namespace would be the following:

```<code>export declare function promiseRetry(options: Partial<PromiseRetry.NodeRetryOptions>, fn: (retry: PromiseRetry.RetryFn, attempt: number) => Promise<any>): Promise<any>;
export declare function promiseRetry(fn: (retry: PromiseRetry.RetryFn, attempt: number) => Promise<any>, options ?: Partial<PromiseRetry.NodeRetryOptions>): Promise<any>;

declare namespace PromiseRetry {
    export interface NodeRetryOptions {
        forever: boolean;
        unref?: boolean;
        retries?: number;
        factor?: number;
        minTimeout?: number; // milliseconds
        maxTimeout?: number; // milliseconds|(Number.)Infinity, which is itself of number type.
        randomize?: number | false;
    }

    export type RetryFn = (err: any) => never;
}
</code>```

Body:
Given this declaration file promise-retry/index.d.ts, which follows TypeScript's official module-function.d.ts format:

Edit: pasted the wrong code segment for this previously (which is still visible below):

export = promiseRetry;

declare function promiseRetry(options: Partial<PromiseRetry.NodeRetryOptions>, fn: (retry: PromiseRetry.RetryFn, attempt: number) => Promise<any>): Promise<any>;
declare function promiseRetry(fn: (retry: PromiseRetry.RetryFn, attempt: number) => Promise<any>, options ?: Partial<PromiseRetry.NodeRetryOptions>): Promise<any>;

declare namespace PromiseRetry {
    export interface NodeRetryOptions {
        forever: boolean;
        unref: boolean;
        retries: number;
        factor: number;
        minTimeout: number;
        maxTimeout: number;
        randomize: number | false;
    }

    export type RetryFn = (err: any) => never;
}

I find I cannot import NodeRetryOptions nor RetryFn via this syntax:

import {NodeRetryOptions, RetryFn} from "promise-retry";

let options: NodeRetryOptions = { forever: false };
let retryFn: RetryFn = (err:any)=>{throw "Nobody responds on StackOverflow"};

... as it throws the compile error: error TS2497: Module '"promise-retry"' resolves to a non-module entity and cannot be imported using this construct.

I also tried another syntax:

declare module "promise-retry" {
    export = promiseRetry;

    function promiseRetry(options: Partial<PromiseRetry.NodeRetryOptions>, fn: (retry: PromiseRetry.RetryFn, attempt: number) => Promise<any>): Promise<any>;
    function promiseRetry(fn: (retry: PromiseRetry.RetryFn, attempt: number) => Promise<any>, options ?: Partial<PromiseRetry.NodeRetryOptions>): Promise<any>;

    namespace PromiseRetry {
        export interface NodeRetryOptions {
            forever: boolean;
            unref: boolean;
            retries: number;
            factor: number;
            minTimeout: number;
            maxTimeout: number;
            randomize: number | false;
        }

        export type RetryFn = (err: any) => never;
    }
}

But the imports (in a different style) failed too:

import * as PromiseRetry from "promise-retry";

let options: PromiseRetry.NodeRetryOptions = { forever: false };
let retryFn: PromiseRetry.RetryFn = (err:any)=>{throw "Nobody responds on StackOverflow"};

... throwing the very same compiler error.

I've read everything I can find (including the related links here), and I can't get it working. In the words of Trump, "Nobody knew TypeScript imports could be so complicated."

Body:
The example you linked to has an important note in its comments:

/*~ Note that ES6 modules cannot directly export callable functions.
 *~ This file should be imported using the CommonJS-style:
 *~   import x = require('someLibrary');
 *~
 *~ Refer to the documentation to understand common
 *~ workarounds for this limitation of ES6 modules.
 */

What you probably want is the following:

export = PromiseRetry;

declare function PromiseRetry(options: Partial<PromiseRetry.NodeRetryOptions>, fn: (retry: PromiseRetry.RetryFn, attempt: number) => Promise<any>): Promise<any>;
declare function PromiseRetry(fn: (retry: PromiseRetry.RetryFn, attempt: number) => Promise<any>, options ?: Partial<PromiseRetry.NodeRetryOptions>): Promise<any>;

declare namespace PromiseRetry {
    export interface NodeRetryOptions {
        forever: boolean;
        unref?: boolean;
        retries?: number;
        factor?: number;
        minTimeout?: number; // milliseconds
        maxTimeout?: number; // milliseconds|(Number.)Infinity, which is itself of number type.
        randomize?: number | false;
    }

    export type RetryFn = (err: any) => never;
}

Note the capitalized PromiseRetry function to match the namespace. Then, to import, use the following line:

import PromiseRetry = require('promise-retry');

Usages must then be prefixed by the namespace as such:

let options: PromiseRetry.NodeRetryOptions = { forever: false };
let retryFn: PromiseRetry.RetryFn = (err:any) => {throw "Sometimes people respond on StackOverflow"};

As a side note, it seems that most packages are leaning against using namespaces to attach types as namespace children of function declarations. Another alternative that would allow you to use a different name for the function and the namespace would be the following:

export declare function promiseRetry(options: Partial<PromiseRetry.NodeRetryOptions>, fn: (retry: PromiseRetry.RetryFn, attempt: number) => Promise<any>): Promise<any>;
export declare function promiseRetry(fn: (retry: PromiseRetry.RetryFn, attempt: number) => Promise<any>, options ?: Partial<PromiseRetry.NodeRetryOptions>): Promise<any>;

declare namespace PromiseRetry {
    export interface NodeRetryOptions {
        forever: boolean;
        unref?: boolean;
        retries?: number;
        factor?: number;
        minTimeout?: number; // milliseconds
        maxTimeout?: number; // milliseconds|(Number.)Infinity, which is itself of number type.
        randomize?: number | false;
    }

    export type RetryFn = (err: any) => never;
}


来源: stackexchange

问:
time complexity of shortest job first algorithm when jobs are non preemptive
Shortest job first algorithm is implemented through min heap data structure.
Then what will be the time complexity of SJF algorithm?

I have read it somewhere that it is n*2*log n which is equal to n log n . Please explain how.
(Sorry if the question is too easy.I am new to it.)

Thanks in advance.

答:
Both the Insert and the Extract-Min operations have a running time of O(log n). There are n tasks and each task has to be inserted to the heap and later extracted from the heap, resulting in a running time of O(n log n).

The reason Insert has a running time of O(log n) is that when inserting we first add the new task to the heap final position. This does not necessarily maintain the heap property, as the priotiy of the new task might be better (having a smaller key) than the priority of its parent. This is why the Insert operation involves the Heapify-Up procedure whose purpose is to restore the heap order. The Heapify-Up procedure has a running time of O(log n).

The reason Extract-Min has a running time of O(log n) is that in the Extract-Min operation we first delete the root of the heap (the first task) and then move the last task to the first position (that is, replacing the root with the task residing in the last position). As this possibly violates the heap property, the Extract-Min involves the execution of the Heapify-Down procedure. The Heapify-Down procedure also has a running time of O(log n).

ContentLicense: CC BY-SA 3.0


问:
How do I multitarget frameworks in Xamarin Studio?
I'm trying to master the Xamarin's IDE and I want to know how I would multitarget frameworks for an asp.net project. In Visual Studio 2015, I would modify the project.json file to configure targeted frameworks. In Xamarin, it looks like targeting is determined by the package.config file. Is this the correct file? Can I just simply add a tag that specifies a package that targets the other framework?

I'm writing with NET45 currently and I'm trying to asp-add core support.

答:
I would recommend switching to Visual Studio as Xamarin Studio is no longer supported as shown below.

In Windows:

SOURCE: https://developer.xamarin.com/guides/cross-platform/xamarin-studio/

In macOS:

SOURCE: https://learn.microsoft.com/en-us/visualstudio/mac/benefits-vsmac-over-xs


问:
Batch Renaming PDFs using content from document on Mac
I have 7000 pdf docs in folder "ffl" they all have been through ocr program so contents can be copy and pasted.

Each document contains text "license -----*****"
The number is 15 digits long has dashes and the 10th item is a letter.

Need a batch to rename all files by the license number in the document.

Is there a script I can run to accomplish this? Have been searching for about a week. Everything is talking about the new way to rename from finder. Nothing on renaming from contents of doc.  Pretty new to terminal.

I have seen the basic command for renaming
mv "old location" "new location"

mv /home/user/my_static /home/user/static

Right now I copy the number and paste as file name. Need a faster way.

Please and thank you for any advise.

答:
I had a similar problem where I wanted to rename a bunch of pdf files with content extracted from the pdf file (in that case a date). I tried at first to do a bash only with pdfgrep, but the brew install exploded on me (seems like the formula is not updated).

What worked for me is Automator to extract the pdf content to text, and then a quick and dirty script to extract the  text and rename. See attached screenshot of the Automator action:

first part cleans up the temp directory (in my case copying the pdfs into "renaming_pdfs"

extract the text into rtf

script grabs the text that I want to rename the file to (in this case the content of the line follow "US4") and renames the files


问:
WebSocket connection to 'ws://localhost:3000/' failed: Connection closed before receiving a handshake response
I took a game that my friend made and wanted to make it playable across browsers by sending keypress data between peers with WebRTC and websockets. However, I get this error in the console:

WebSocket connection to 'ws://localhost:3000/' failed: Connection closed before receiving a handshake response

My server file has the following few lines:

```<code>'use strict';

const express = require('express');
const SocketServer = require('ws').Server;
const path = require('path');

const PORT = process.env.PORT || 3000;
const INDEX = path.join(__dirname, 'index.html');

const server = express();

server.use(express.static(path.join(__dirname, 'lib')));
server.use('/assets', express.static(path.join(__dirname, 'assets')));
server.listen(PORT, () => console.log(`Listening on ${ PORT }`));

const wss = new SocketServer({ server });
var users = {};
let usernames = [];

wss.on('connection', function(connection) {

   connection.on('message', function(message) {

      var data;
      try {
         data = JSON.parse(message);
      } catch (e) {
         console.log("Invalid JSON");
         data = {};
      }

      switch (data.type) {
         case "login":
            console.log("User logged", data.name);
            if(users[data.name]) {
               sendTo(connection, {
                  type: "login",
                  success: false
               });
            } else {
               users[data.name] = connection;
               connection.name = data.name;
               usernames.push(data.name);

               sendTo(connection, {
                  type: "login",
                  success: true,
                  users: usernames
               });
            }

            break;

         case "offer":
            console.log("Sending offer to: ", data.name);
            var conn = users[data.name];

            if(conn != null) {
               connection.otherName = data.name;

               sendTo(conn, {
                  type: "offer",
                  offer: data.offer,
                  name: connection.name
               });
            }

            break;

         case "answer":
            console.log("Sending answer to: ", data.name);
            var conn = users[data.name];

            if(conn != null) {
               connection.otherName = data.name;
               sendTo(conn, {
                  type: "answer",
                  answer: data.answer
               });
            }

            break;

         case "candidate":
            console.log("Sending candidate to:",data.name);
            var conn = users[data.name];

            if(conn != null) {
               sendTo(conn, {
                  type: "candidate",
                  candidate: data.candidate
               });
            }

            break;

         case "leave":
            console.log("Disconnecting from", data.name);
            var conn = users[data.name];
            conn.otherName = null;

            if(conn != null) {
               sendTo(conn, {
                  type: "leave"
               });
            }

            break;

         default:
            sendTo(connection, {
               type: "error",
               message: "Command not found: " + data.type
            });

            break;
      }
   });
</code>```

And the client side of the connection looks as follows:

```<code>const Game = require("./game");
const GameView = require("./game_view");
var HOST = location.origin.replace(/^http/, 'ws');
console.log('host: ', HOST);
console.log(process.env.PORT);

document.addEventListener("DOMContentLoaded", function() {
  const connection = new WebSocket(HOST);

.....
</code>```

This is the point that the error occurs and this is the caught error that I get:

```<code>bubbles
:
false
cancelBubble
:
false
cancelable
:
false
composed
:
false
currentTarget
:
WebSocket
defaultPrevented
:
false
eventPhase
:
0
isTrusted
:
true
path
:
Array(0)
returnValue
:
true
srcElement
:
WebSocket
target
:
WebSocket
timeStamp
:
213.01500000000001
type
:
"error"
__proto__
:
Event
</code>```

I am not too familiar with server side programming and was trying to understand. I tried looking up this issue, but it seems like a variety of different things can cause this. If you want to see the repository you can see and try it yourself (uses webpack): SlidingWarfare Repo

答:
The confusion starts here:

```<code>const server = express();
</code>```

The express function doesn't really return a server, it returns an application. Commonly, the variable used for this is app, but that's of course nothing more than convention (i.e. not a requirement).

However, it becomes an issue when you pass the app to the WS server:

```<code>const wss = new SocketServer({ server });
</code>```

That's because SocketServer requires an HTTP server instance, which server is not.

Here's a fix, without renaming your variables:

```<code>let httpServer = server.listen(PORT, () => console.log(`Listening on ${ PORT }`));
...
const wss = new SocketServer({ server : httpServer });
</code>```

(because when you call .listen() on the Express instance, it will return an HTTP server instance)

Using the variable naming convention it would be this:

```<code>const app = express();

app.use(express.static(path.join(__dirname, 'lib')));
app.use('/assets', express.static(path.join(__dirname, 'assets')));

let server = app.listen(PORT, () => console.log(`Listening on ${ PORT }`));

const wss = new SocketServer({ server });
</code>```

Body:
I took a game that my friend made and wanted to make it playable across browsers by sending keypress data between peers with WebRTC and websockets. However, I get this error in the console:

WebSocket connection to 'ws://localhost:3000/' failed: Connection closed before receiving a handshake response

My server file has the following few lines:

'use strict';

const express = require('express');
const SocketServer = require('ws').Server;
const path = require('path');

const PORT = process.env.PORT || 3000;
const INDEX = path.join(__dirname, 'index.html');

const server = express();

server.use(express.static(path.join(__dirname, 'lib')));
server.use('/assets', express.static(path.join(__dirname, 'assets')));
server.listen(PORT, () => console.log(`Listening on ${ PORT }`));

const wss = new SocketServer({ server });
var users = {};
let usernames = [];

wss.on('connection', function(connection) {

   connection.on('message', function(message) {

      var data;
      try {
         data = JSON.parse(message);
      } catch (e) {
         console.log("Invalid JSON");
         data = {};
      }

      switch (data.type) {
         case "login":
            console.log("User logged", data.name);
            if(users[data.name]) {
               sendTo(connection, {
                  type: "login",
                  success: false
               });
            } else {
               users[data.name] = connection;
               connection.name = data.name;
               usernames.push(data.name);

               sendTo(connection, {
                  type: "login",
                  success: true,
                  users: usernames
               });
            }

            break;

         case "offer":
            console.log("Sending offer to: ", data.name);
            var conn = users[data.name];

            if(conn != null) {
               connection.otherName = data.name;

               sendTo(conn, {
                  type: "offer",
                  offer: data.offer,
                  name: connection.name
               });
            }

            break;

         case "answer":
            console.log("Sending answer to: ", data.name);
            var conn = users[data.name];

            if(conn != null) {
               connection.otherName = data.name;
               sendTo(conn, {
                  type: "answer",
                  answer: data.answer
               });
            }

            break;

         case "candidate":
            console.log("Sending candidate to:",data.name);
            var conn = users[data.name];

            if(conn != null) {
               sendTo(conn, {
                  type: "candidate",
                  candidate: data.candidate
               });
            }

            break;

         case "leave":
            console.log("Disconnecting from", data.name);
            var conn = users[data.name];
            conn.otherName = null;

            if(conn != null) {
               sendTo(conn, {
                  type: "leave"
               });
            }

            break;

         default:
            sendTo(connection, {
               type: "error",
               message: "Command not found: " + data.type
            });

            break;
      }
   });

And the client side of the connection looks as follows:

const Game = require("./game");
const GameView = require("./game_view");
var HOST = location.origin.replace(/^http/, 'ws');
console.log('host: ', HOST);
console.log(process.env.PORT);

document.addEventListener("DOMContentLoaded", function() {
  const connection = new WebSocket(HOST);

.....

This is the point that the error occurs and this is the caught error that I get:

bubbles
:
false
cancelBubble
:
false
cancelable
:
false
composed
:
false
currentTarget
:
WebSocket
defaultPrevented
:
false
eventPhase
:
0
isTrusted
:
true
path
:
Array(0)
returnValue
:
true
srcElement
:
WebSocket
target
:
WebSocket
timeStamp
:
213.01500000000001
type
:
"error"
__proto__
:
Event

I am not too familiar with server side programming and was trying to understand. I tried looking up this issue, but it seems like a variety of different things can cause this. If you want to see the repository you can see and try it yourself (uses webpack): SlidingWarfare Repo

Body:
The confusion starts here:

const server = express();

The express function doesn't really return a server, it returns an application. Commonly, the variable used for this is app, but that's of course nothing more than convention (i.e. not a requirement).

However, it becomes an issue when you pass the app to the WS server:

const wss = new SocketServer({ server });

That's because SocketServer requires an HTTP server instance, which server is not.

Here's a fix, without renaming your variables:

let httpServer = server.listen(PORT, () => console.log(`Listening on ${ PORT }`));
...
const wss = new SocketServer({ server : httpServer });

(because when you call .listen() on the Express instance, it will return an HTTP server instance)

Using the variable naming convention it would be this:

const app = express();

app.use(express.static(path.join(__dirname, 'lib')));
app.use('/assets', express.static(path.join(__dirname, 'assets')));

let server = app.listen(PORT, () => console.log(`Listening on ${ PORT }`));

const wss = new SocketServer({ server });


问:
How to communicate two android applications?
i want to sent data from one applications to another android application, i am new to this android so please help me...</p>

答:
Look up intents. That's the preferred way to do it.

Apps can support any number of intents, and you can pass any data along with the intent.

ContentLicense: CC BY-SA 2.5


问:
Passing parameters to Unity Action
When I initiate my GameObject I loop through all if its dialogs. For each Dialog there is an action. Activate a quest or change NPC stage.

The method I pass to PopulateConversationList below gets called when I click the final button in a dialog-interaction, i.e "Okay". Below I pass an ActiveNpcQuest(questId) method, and pass the questId (get it from dialog data) like this:

```<code>//loop through all dialogs
for (int i = 0; i < dialogData.dialogs.Count; i++)
    {
        startsQ = dialogData.dialogs[i].dialogStartsQuest;
        questId = dialogData.dialogs[i].dialogBelongToQuestId;

            //if we have a quest, activate it (if already active, nothing happens)
            if (startsQ)
            {
                PopulateConversationList(dialogData.dialogs[i].dialogsInThisStage[j].pages, "Okay", npcObject.npcName, dialogData.dialogs[i].npcStage, () =>
                {
                    ActivateNPCQuest(questId); //This is the parameter I want to send
                });
            }
            //If this dialog ALWAYS changes the NPC stage, then change stage
            else if (autoChangeStage)
            {
                PopulateConversationList(dialogData.dialogs[i].dialogsInThisStage[j].pages, "Okay", npcObject.npcName, dialogData.dialogs[i].npcStage, ChangeNPCStage);
            }
        }
</code>```

I guess the value of questId doesnt actually get saved inside the ActivateNPCQuest-method. Which makes a lot of sense. But Is there any way I can do what I want here?

My PopulateConversationList declaration:

```<code>public void PopulateConversationList(List<string> fullConversation, string onLastPagePrompt, string npcName, int stage, UnityAction action)
</code>```

My ActiveNpcQuest-method:

```<code>public void ActivateNPCQuest(int id)
{
    for (int i = 0; i < npcQuests.Count; i++)
    {
        if (npcQuests[i].questId == id && !npcQuests[i].active && !npcQuests[i].objective.isComplete)
        {
            npcQuests[i].active = true;
            npcObject.hasActiveQuest = true;
        }
    }
}
</code>```

Had real problems knowing what to search for, not sure if Unity Actions are Lambda expressions or events.

答:
It is hard to understand you problem without having full code and knowing what you expect but it looks like you are having problems due to closures. Try to assign questId to a new variable each iteration of the loop and pass it to your ActivateNPCQuest method to see if you get the result you want:</p>

```<code>//loop through all dialogs
for (int i = 0; i < dialogData.dialogs.Count; i++)
    {
        startsQ = dialogData.dialogs[i].dialogStartsQuest;
        var questId = dialogData.dialogs[i].dialogBelongToQuestId; \\<----

            //if we have a quest, activate it (if already active, nothing happens)
            if (startsQ)
            {
                PopulateConversationList(dialogData.dialogs[i].dialogsInThisStage[j].pages, "Okay", npcObject.npcName, dialogData.dialogs[i].npcStage, () =>
                {
                    ActivateNPCQuest(questId); //This is the parameter I want to send
                });
            }
            //If this dialog ALWAYS changes the NPC stage, then change stage
            else if (autoChangeStage)
            {
                PopulateConversationList(dialogData.dialogs[i].dialogsInThisStage[j].pages, "Okay", npcObject.npcName, dialogData.dialogs[i].npcStage, ChangeNPCStage);
            }
        }
</code>```

Title: Passing parameters to Unity Action

Body:
When I initiate my GameObject I loop through all if its dialogs. For each Dialog there is an action. Activate a quest or change NPC stage.

The method I pass to PopulateConversationList below gets called when I click the final button in a dialog-interaction, i.e "Okay". Below I pass an ActiveNpcQuest(questId) method, and pass the questId (get it from dialog data) like this:

//loop through all dialogs
for (int i = 0; i < dialogData.dialogs.Count; i++)
    {
        startsQ = dialogData.dialogs[i].dialogStartsQuest;
        questId = dialogData.dialogs[i].dialogBelongToQuestId;

            //if we have a quest, activate it (if already active, nothing happens)
            if (startsQ)
            {
                PopulateConversationList(dialogData.dialogs[i].dialogsInThisStage[j].pages, "Okay", npcObject.npcName, dialogData.dialogs[i].npcStage, () =>
                {
                    ActivateNPCQuest(questId); //This is the parameter I want to send
                });
            }
            //If this dialog ALWAYS changes the NPC stage, then change stage
            else if (autoChangeStage)
            {
                PopulateConversationList(dialogData.dialogs[i].dialogsInThisStage[j].pages, "Okay", npcObject.npcName, dialogData.dialogs[i].npcStage, ChangeNPCStage);
            }
        }

I guess the value of questId doesnt actually get saved inside the ActivateNPCQuest-method. Which makes a lot of sense. But Is there any way I can do what I want here?

My PopulateConversationList declaration:

public void PopulateConversationList(List<string> fullConversation, string onLastPagePrompt, string npcName, int stage, UnityAction action)

My ActiveNpcQuest-method:

public void ActivateNPCQuest(int id)
{
    for (int i = 0; i < npcQuests.Count; i++)
    {
        if (npcQuests[i].questId == id && !npcQuests[i].active && !npcQuests[i].objective.isComplete)
        {
            npcQuests[i].active = true;
            npcObject.hasActiveQuest = true;
        }
    }
}

Had real problems knowing what to search for, not sure if Unity Actions are Lambda expressions or events.

Body:
It is hard to understand you problem without having full code and knowing what you expect but it looks like you are having problems due to closures. Try to assign questId to a new variable each iteration of the loop and pass it to your ActivateNPCQuest method to see if you get the result you want:

//loop through all dialogs
for (int i = 0; i < dialogData.dialogs.Count; i++)
    {
        startsQ = dialogData.dialogs[i].dialogStartsQuest;
        var questId = dialogData.dialogs[i].dialogBelongToQuestId; \\<----

            //if we have a quest, activate it (if already active, nothing happens)
            if (startsQ)
            {
                PopulateConversationList(dialogData.dialogs[i].dialogsInThisStage[j].pages, "Okay", npcObject.npcName, dialogData.dialogs[i].npcStage, () =>
                {
                    ActivateNPCQuest(questId); //This is the parameter I want to send
                });
            }
            //If this dialog ALWAYS changes the NPC stage, then change stage
            else if (autoChangeStage)
            {
                PopulateConversationList(dialogData.dialogs[i].dialogsInThisStage[j].pages, "Okay", npcObject.npcName, dialogData.dialogs[i].npcStage, ChangeNPCStage);
            }
        }


问:
Command "tinker" is not defined
After upgrade from 5.3 to 5.4, Follow the instructions:

In order to continue using the tinker Artisan command, you should also install the laravel/tinker package:

```<code>composer require laravel/tinker
</code>```

Once the package has been installed, you should add" Laravel\Tinker\TinkerServiceProvider::class to the providers array in your config/app.php configuration file.

After hours of search..got this question but is not working.

Any ideas?

config.json

```<code>{
"name": "laravel/laravel",
"description": "The Laravel Framework.",
"keywords": ["framework", "laravel"],
"license": "MIT",
"type": "project",
"require": {
    "php": ">=5.6.4",
    "laravel/framework": "5.4.*",
    "hisorange/browser-detect": "2.0.2",
    "guzzlehttp/guzzle": "^6.2",
    "maxmind-db/reader": "~1.0",
    "laravel/tinker": "^1.0"
},
"require-dev": {
    "fzaninotto/faker": "~1.4",
    "mockery/mockery": "0.9.*",
    "phpunit/phpunit": "~5.7",
    "symfony/css-selector": "3.1.*",
    "symfony/dom-crawler": "3.1.*"
},
"autoload": {
    "classmap": [
        "database"
    ],
    "psr-4": {
        "App\\": "app/"
    }
},
"autoload-dev": {
    "classmap": [
        "tests/TestCase.php"
    ]
},
"scripts": {
    "post-root-package-install": [
        "php -r \"file_exists('.env') || copy('.env.example', '.env');\""
    ],
    "post-create-project-cmd": [
        "php artisan key:generate"
    ],
    "post-install-cmd": [
        "Illuminate\\Foundation\\ComposerScripts::postInstall",
        "php artisan optimize"
    ],
    "post-update-cmd": [
        "Illuminate\\Foundation\\ComposerScripts::postUpdate",
        "php artisan optimize"
    ]
},
"config": {
    "preferred-install": "dist",
    "disable-tls": true,
    "secure-http": false
}
</code>```

}

config/app.php

return [

```<code>/*
|--------------------------------------------------------------------------
| Application Name
|--------------------------------------------------------------------------
|
| This value is the name of your application. This value is used when the
| framework needs to place the application's name in a notification or
| any other location as required by the application or its packages.
*/

'name' => 'App',

/*
|--------------------------------------------------------------------------
| Application Environment
|--------------------------------------------------------------------------
|
| This value determines the "environment" your application is currently
| running in. This may determine how you prefer to configure various
| services your application utilizes. Set this in your ".env" file.
|
*/

'env' => env('APP_ENV', 'development'),

/*
|--------------------------------------------------------------------------
| Application Debug Mode
|--------------------------------------------------------------------------
|
| When your application is in debug mode, detailed error messages with
| stack traces will be shown on every error that occurs within your
| application. If disabled, a simple generic error page is shown.
|
*/

'debug' => env('APP_DEBUG', true),

/*
|--------------------------------------------------------------------------
| Application URL
|--------------------------------------------------------------------------
|
| This URL is used by the console to properly generate URLs when using
| the Artisan command line tool. You should set this to the root of
| your application so that it is used when running Artisan tasks.
|
*/

'url' => env('APP_URL', 'http://localhost'),

/*
|--------------------------------------------------------------------------
| Application Timezone
|--------------------------------------------------------------------------
|
| Here you may specify the default timezone for your application, which
| will be used by the PHP date and date-time functions. We have gone
| ahead and set this to a sensible default for you out of the box.
|
*/

'timezone' => 'America/Tegucigalpa',

/*
|--------------------------------------------------------------------------
| Application Locale Configuration
|--------------------------------------------------------------------------
|
| The application locale determines the default locale that will be used
| by the translation service provider. You are free to set this value
| to any of the locales which will be supported by the application.
|
*/

'locale' => 'en',

/*
|--------------------------------------------------------------------------
| Application Fallback Locale
|--------------------------------------------------------------------------
|
| The fallback locale determines the locale to use when the current one
| is not available. You may change the value to correspond to any of
| the language folders that are provided through your application.
|
*/

'fallback_locale' => 'en',

/*
|--------------------------------------------------------------------------
| Encryption Key
|--------------------------------------------------------------------------
|
| This key is used by the Illuminate encrypter service and should be set
| to a random, 32 character string, otherwise these encrypted strings
| will not be safe. Please do this before deploying an application!
|
*/

'key' => env('APP_KEY'),

'cipher' => 'AES-256-CBC',

/*
|--------------------------------------------------------------------------
| Logging Configuration
|--------------------------------------------------------------------------
|
| Here you may configure the log settings for your application. Out of
| the box, Laravel uses the Monolog PHP logging library. This gives
| you a variety of powerful log handlers / formatters to utilize.
|
| Available Settings: "single", "daily", "syslog", "errorlog"
|
*/

'log' => env('APP_LOG', 'single'),

'log_level' => env('APP_LOG_LEVEL', 'debug'),

/*
|--------------------------------------------------------------------------
| Autoloaded Service Providers
|--------------------------------------------------------------------------
|
| The service providers listed here will be automatically loaded on the
| request to your application. Feel free to add your own services to
| this array to grant expanded functionality to your applications.
|
*/

'providers' => [

    /*
     * Laravel Framework Service Providers...
     */
    Illuminate\Auth\AuthServiceProvider::class,
    Illuminate\Broadcasting\BroadcastServiceProvider::class,
    Illuminate\Bus\BusServiceProvider::class,
    Illuminate\Cache\CacheServiceProvider::class,
    Illuminate\Foundation\Providers\ConsoleSupportServiceProvider::class,
    Illuminate\Cookie\CookieServiceProvider::class,
    Illuminate\Database\DatabaseServiceProvider::class,
    Illuminate\Encryption\EncryptionServiceProvider::class,
    Illuminate\Filesystem\FilesystemServiceProvider::class,
    Illuminate\Foundation\Providers\FoundationServiceProvider::class,
    Illuminate\Hashing\HashServiceProvider::class,
    Illuminate\Mail\MailServiceProvider::class,
    Illuminate\Notifications\NotificationServiceProvider::class,
    Illuminate\Pagination\PaginationServiceProvider::class,
    Illuminate\Pipeline\PipelineServiceProvider::class,
    Illuminate\Queue\QueueServiceProvider::class,
    Illuminate\Redis\RedisServiceProvider::class,
    Illuminate\Auth\Passwords\PasswordResetServiceProvider::class,
    Illuminate\Session\SessionServiceProvider::class,
    Illuminate\Translation\TranslationServiceProvider::class,
    Illuminate\Validation\ValidationServiceProvider::class,
    Illuminate\View\ViewServiceProvider::class,
    \hisorange\BrowserDetect\Provider\BrowserDetectService::class,
    Laravel\Tinker\TinkerServiceProvider::class,

    /*
     * Package Service Providers...
     */

    //

    /*
     * Application Service Providers...
     */
],

/*
|--------------------------------------------------------------------------
| Class Aliases
|--------------------------------------------------------------------------
|
| This array of class aliases will be registered when this application
| is started. However, feel free to register as many as you wish as
| the aliases are "lazy" loaded so they don't hinder performance.
|
*/

'aliases' => [

    'App' => Illuminate\Support\Facades\App::class,
    'Artisan' => Illuminate\Support\Facades\Artisan::class,
    'Auth' => Illuminate\Support\Facades\Auth::class,
    'Blade' => Illuminate\Support\Facades\Blade::class,
    'Bus' => Illuminate\Support\Facades\Bus::class,
    'Cache' => Illuminate\Support\Facades\Cache::class,
    'Config' => Illuminate\Support\Facades\Config::class,
    'Cookie' => Illuminate\Support\Facades\Cookie::class,
    'Crypt' => Illuminate\Support\Facades\Crypt::class,
    'DB' => Illuminate\Support\Facades\DB::class,
    'Eloquent' => Illuminate\Database\Eloquent\Model::class,
    'Event' => Illuminate\Support\Facades\Event::class,
    'File' => Illuminate\Support\Facades\File::class,
    'Gate' => Illuminate\Support\Facades\Gate::class,
    'Hash' => Illuminate\Support\Facades\Hash::class,
    'Lang' => Illuminate\Support\Facades\Lang::class,
    'Log' => Illuminate\Support\Facades\Log::class,
    'Mail' => Illuminate\Support\Facades\Mail::class,
    'Notification' => Illuminate\Support\Facades\Notification::class,
    'Password' => Illuminate\Support\Facades\Password::class,
    'Queue' => Illuminate\Support\Facades\Queue::class,
    'Redirect' => Illuminate\Support\Facades\Redirect::class,
    'Redis' => Illuminate\Support\Facades\Redis::class,
    'Request' => Illuminate\Support\Facades\Request::class,
    'Response' => Illuminate\Support\Facades\Response::class,
    'Route' => Illuminate\Support\Facades\Route::class,
    'Schema' => Illuminate\Support\Facades\Schema::class,
    'Session' => Illuminate\Support\Facades\Session::class,
    'Storage' => Illuminate\Support\Facades\Storage::class,
    'URL' => Illuminate\Support\Facades\URL::class,
    'Validator' => Illuminate\Support\Facades\Validator::class,
    'View' => Illuminate\Support\Facades\View::class,
    'BrowserDetect' => \hisorange\BrowserDetect\Facade\Parser::class,
],
</code>```

];

EDIT
Well, Looks like we need to register the command in our /Console/Kernel.php

Modify the $commands property. With this:

```<code>    protected $commands = [
    //
    \Laravel\Tinker\Console\TinkerCommand::class,
];
</code>```

After that, make a composer dump-autoload

答: I ran into this on a production server, but not with the very same code in my development environment. Turns out that I had my configuration (and routes) cached on the server and that regenerating the configuration cache made the tinker command suddenly show up again.

Title: Command "tinker" is not defined

Body:
After upgrade from 5.3 to 5.4, Follow the instructions:

In order to continue using the tinker Artisan command, you should also install the laravel/tinker package:

composer require laravel/tinker

Once the package has been installed, you should add" Laravel\Tinker\TinkerServiceProvider::class to the providers array in your config/app.php configuration file.

After hours of search..got this question but is not working.

Any ideas?

config.json

{
"name": "laravel/laravel",
"description": "The Laravel Framework.",
"keywords": ["framework", "laravel"],
"license": "MIT",
"type": "project",
"require": {
    "php": ">=5.6.4",
    "laravel/framework": "5.4.*",
    "hisorange/browser-detect": "2.0.2",
    "guzzlehttp/guzzle": "^6.2",
    "maxmind-db/reader": "~1.0",
    "laravel/tinker": "^1.0"
},
"require-dev": {
    "fzaninotto/faker": "~1.4",
    "mockery/mockery": "0.9.*",
    "phpunit/phpunit": "~5.7",
    "symfony/css-selector": "3.1.*",
    "symfony/dom-crawler": "3.1.*"
},
"autoload": {
    "classmap": [
        "database"
    ],
    "psr-4": {
        "App\\": "app/"
    }
},
"autoload-dev": {
    "classmap": [
        "tests/TestCase.php"
    ]
},
"scripts": {
    "post-root-package-install": [
        "php -r \"file_exists('.env') || copy('.env.example', '.env');\""
    ],
    "post-create-project-cmd": [
        "php artisan key:generate"
    ],
    "post-install-cmd": [
        "Illuminate\\Foundation\\ComposerScripts::postInstall",
        "php artisan optimize"
    ],
    "post-update-cmd": [
        "Illuminate\\Foundation\\ComposerScripts::postUpdate",
        "php artisan optimize"
    ]
},
"config": {
    "preferred-install": "dist",
    "disable-tls": true,
    "secure-http": false
}

}

config/app.php

return [

/*
|--------------------------------------------------------------------------
| Application Name
|--------------------------------------------------------------------------
|
| This value is the name of your application. This value is used when the
| framework needs to place the application's name in a notification or
| any other location as required by the application or its packages.
*/

'name' => 'App',

/*
|--------------------------------------------------------------------------
| Application Environment
|--------------------------------------------------------------------------
|
| This value determines the "environment" your application is currently
| running in. This may determine how you prefer to configure various
| services your application utilizes. Set this in your ".env" file.
|
*/

'env' => env('APP_ENV', 'development'),

/*
|--------------------------------------------------------------------------
| Application Debug Mode
|--------------------------------------------------------------------------
|
| When your application is in debug mode, detailed error messages with
| stack traces will be shown on every error that occurs within your
| application. If disabled, a simple generic error page is shown.
|
*/

'debug' => env('APP_DEBUG', true),

/*
|--------------------------------------------------------------------------
| Application URL
|--------------------------------------------------------------------------
|
| This URL is used by the console to properly generate URLs when using
| the Artisan command line tool. You should set this to the root of
| your application so that it is used when running Artisan tasks.
|
*/

'url' => env('APP_URL', 'http://localhost'),

/*
|--------------------------------------------------------------------------
| Application Timezone
|--------------------------------------------------------------------------
|
| Here you may specify the default timezone for your application, which
| will be used by the PHP date and date-time functions. We have gone
| ahead and set this to a sensible default for you out of the box.
|
*/

'timezone' => 'America/Tegucigalpa',

/*
|--------------------------------------------------------------------------
| Application Locale Configuration
|--------------------------------------------------------------------------
|
| The application locale determines the default locale that will be used
| by the translation service provider. You are free to set this value
| to any of the locales which will be supported by the application.
|
*/

'locale' => 'en',

/*
|--------------------------------------------------------------------------
| Application Fallback Locale
|--------------------------------------------------------------------------
|
| The fallback locale determines the locale to use when the current one
| is not available. You may change the value to correspond to any of
| the language folders that are provided through your application.
|
*/

'fallback_locale' => 'en',

/*
|--------------------------------------------------------------------------
| Encryption Key
|--------------------------------------------------------------------------
|
| This key is used by the Illuminate encrypter service and should be set
| to a random, 32 character string, otherwise these encrypted strings
| will not be safe. Please do this before deploying an application!
|
*/

'key' => env('APP_KEY'),

'cipher' => 'AES-256-CBC',

/*
|--------------------------------------------------------------------------
| Logging Configuration
|--------------------------------------------------------------------------
|
| Here you may configure the log settings for your application. Out of
| the box, Laravel uses the Monolog PHP logging library. This gives
| you a variety of powerful log handlers / formatters to utilize.
|
| Available Settings: "single", "daily", "syslog", "errorlog"
|
*/

'log' => env('APP_LOG', 'single'),

'log_level' => env('APP_LOG_LEVEL', 'debug'),

/*
|--------------------------------------------------------------------------
| Autoloaded Service Providers
|--------------------------------------------------------------------------
|
| The service providers listed here will be automatically loaded on the
| request to your application. Feel free to add your own services to
| this array to grant expanded functionality to your applications.
|
*/

'providers' => [

    /*
     * Laravel Framework Service Providers...
     */
    Illuminate\Auth\AuthServiceProvider::class,
    Illuminate\Broadcasting\BroadcastServiceProvider::class,
    Illuminate\Bus\BusServiceProvider::class,
    Illuminate\Cache\CacheServiceProvider::class,
    Illuminate\Foundation\Providers\ConsoleSupportServiceProvider::class,
    Illuminate\Cookie\CookieServiceProvider::class,
    Illuminate\Database\DatabaseServiceProvider::class,
    Illuminate\Encryption\EncryptionServiceProvider::class,
    Illuminate\Filesystem\FilesystemServiceProvider::class,
    Illuminate\Foundation\Providers\FoundationServiceProvider::class,
    Illuminate\Hashing\HashServiceProvider::class,
    Illuminate\Mail\MailServiceProvider::class,
    Illuminate\Notifications\NotificationServiceProvider::class,
    Illuminate\Pagination\PaginationServiceProvider::class,
    Illuminate\Pipeline\PipelineServiceProvider::class,
    Illuminate\Queue\QueueServiceProvider::class,
    Illuminate\Redis\RedisServiceProvider::class,
    Illuminate\Auth\Passwords\PasswordResetServiceProvider::class,
    Illuminate\Session\SessionServiceProvider::class,
    Illuminate\Translation\TranslationServiceProvider::class,
    Illuminate\Validation\ValidationServiceProvider::class,
    Illuminate\View\ViewServiceProvider::class,
    \hisorange\BrowserDetect\Provider\BrowserDetectService::class,
    Laravel\Tinker\TinkerServiceProvider::class,

    /*
     * Package Service Providers...
     */

    //

    /*
     * Application Service Providers...
     */
],

/*
|--------------------------------------------------------------------------
| Class Aliases
|--------------------------------------------------------------------------
|
| This array of class aliases will be registered when this application
| is started. However, feel free to register as many as you wish as
| the aliases are "lazy" loaded so they don't hinder performance.
|
*/

'aliases' => [

    'App' => Illuminate\Support\Facades\App::class,
    'Artisan' => Illuminate\Support\Facades\Artisan::class,
    'Auth' => Illuminate\Support\Facades\Auth::class,
    'Blade' => Illuminate\Support\Facades\Blade::class,
    'Bus' => Illuminate\Support\Facades\Bus::class,
    'Cache' => Illuminate\Support\Facades\Cache::class,
    'Config' => Illuminate\Support\Facades\Config::class,
    'Cookie' => Illuminate\Support\Facades\Cookie::class,
    'Crypt' => Illuminate\Support\Facades\Crypt::class,
    'DB' => Illuminate\Support\Facades\DB::class,
    'Eloquent' => Illuminate\Database\Eloquent\Model::class,
    'Event' => Illuminate\Support\Facades\Event::class,
    'File' => Illuminate\Support\Facades\File::class,
    'Gate' => Illuminate\Support\Facades\Gate::class,
    'Hash' => Illuminate\Support\Facades\Hash::class,
    'Lang' => Illuminate\Support\Facades\Lang::class,
    'Log' => Illuminate\Support\Facades\Log::class,
    'Mail' => Illuminate\Support\Facades\Mail::class,
    'Notification' => Illuminate\Support\Facades\Notification::class,
    'Password' => Illuminate\Support\Facades\Password::class,
    'Queue' => Illuminate\Support\Facades\Queue::class,
    'Redirect' => Illuminate\Support\Facades\Redirect::class,
    'Redis' => Illuminate\Support\Facades\Redis::class,
    'Request' => Illuminate\Support\Facades\Request::class,
    'Response' => Illuminate\Support\Facades\Response::class,
    'Route' => Illuminate\Support\Facades\Route::class,
    'Schema' => Illuminate\Support\Facades\Schema::class,
    'Session' => Illuminate\Support\Facades\Session::class,
    'Storage' => Illuminate\Support\Facades\Storage::class,
    'URL' => Illuminate\Support\Facades\URL::class,
    'Validator' => Illuminate\Support\Facades\Validator::class,
    'View' => Illuminate\Support\Facades\View::class,
    'BrowserDetect' => \hisorange\BrowserDetect\Facade\Parser::class,
],

];

EDIT
Well, Looks like we need to register the command in our /Console/Kernel.php

Modify the $commands property. With this:

    protected $commands = [
    //
    \Laravel\Tinker\Console\TinkerCommand::class,
];

After that, make a composer dump-autoload


问:
Adding react-lds import in react component resulting in failed compilation
Please refer import that is causing error.It compiles without any issue if I comment this line.

```<code>import React, {Component} from 'react';
import {returnCurrencies} from '../reducers/reducer_currency';
import {DropdownMenu, DropdownMenuList, DropdownMenuListItem} from 'react-lds';

export default class CurrencyDropDown extends Component
{
   constructor(props)
   {
      super(props);
      //console.log("props",props);
   }
   renderCurrencies(curr)
   {
      //console.log("Curr ", curr);
      return (<option key={curr} value={curr}>{curr}</option>);
   }
   render()
   {
      if(!this.props.currencies)
      {
        return (<div></div>);
      }
      let currencyList = returnCurrencies(this.props.currencies);
       return (<div>
          <select value={this.props.initValue} onChange=
              {this.props.selectCurrency}>
            {currencyList.map(this.renderCurrencies)}
          </select>
        </div>);
 }
}
</code>```

Package.json

```<code>{
  "name": "redux-simple-starter",
  "version": "1.0.0",
  "description": "Simple starter package for Redux with React and Babel support",
   "main": "index.js",
   "repository": "",
   "scripts": {
       "start": "node ./node_modules/webpack-dev-server/bin/webpack-dev-server.js",
       "test": "mocha --compilers js:babel-core/register --require ./test/test_helper.js --recursive ./test",
       "test:watch": "npm run test -- --watch"
 },
 "author": "",
 "license": "ISC",
 "devDependencies": {
 "babel-core": "^6.2.1",
 "babel-loader": "^6.2.0",
 "babel-preset-es2015": "^6.1.18",
 "babel-preset-react": "^6.1.18",
 "chai": "^3.5.0",
 "chai-jquery": "^2.0.0",
 "jquery": "^2.2.1",
 "jsdom": "^8.1.0",
 "mocha": "^2.4.5",
 "react-addons-test-utils": "^0.14.7",
 "webpack": "^1.12.9",
 "webpack-dev-server": "^1.14.0"
},
"dependencies": {
"axios": "^0.16.2",
"babel-preset-stage-1": "^6.1.18",
"lodash": "^3.10.1",
"prop-types": "^15.5.10",
"react": "^0.14.9",
"react-dom": "^0.14.9",
"react-lds": "^1.1.11",
"react-redux": "4.3.0",
"react-router": "^2.0.1",
"redux": "^3.0.4",
"redux-promise": "^0.5.3"
}
</code>```

}

Failed to compile with below error.

ERROR in ./~/moment-timezone/data/packed/latest.json
Module parse failed: C:..\XXXX\node_modules\moment-timezone\data\packed\latest.json Unexpected token (2:10)
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected token (2:10)
    at Parser.pp$4.raise (C:..\XXXX\node_modules\webpack\node_modules\acorn\dist\acorn.js:2221:15)
    at Parser.pp.unexpected (C:..\XXXX\node_modules\webpack\node_modules\acorn\dist\acorn.js:603:10)
    at Parser.pp.semicolon (C:..\XXXX\node_modules\webpack\node_modules\acorn\dist\acorn.js:581:61)
    at Parser.pp$1.parseExpressionStatement (C:..\XXXX\node_modules\webpack\node_modules\acorn\dist\acorn.js:966:10)
    at Parser.pp$1.parseStatement (C:..\XXXX\node_modules\webpack\node_modules\acorn\dist\acorn.js:730:24)
    at Parser.pp$1.parseBlock (C:..\XXXX\node_modules\webpack\node_modules\acorn\dist\acorn.js:981:25)
    at Parser.pp$1.parseStatement (C:..\XXXX\node_modules\webpack\node_modules\acorn\dist\acorn.js:709:33)
    at Parser.pp$1.parseTopLevel (C:..\XXXX\node_modules\webpack\node_modules\acorn\dist\acorn.js:638:25)
    at Parser.parse (C:..\XXXX\node_modules\webpack\node_modules\acorn\dist\acorn.js:516:17)
    at Object.parse (C:..\XXXX\node_modules\webpack\node_modules\acorn\dist\acorn.js:3098:39)
 @ ./~/moment-timezone/index.js 2:15-51

答:
It fails because it can not load the JSON file. You need to configure webpack to load the JSON files:

Install the json-loader:

```<code>npm install --save-dev json-loader
</code>```

And adjust your webpack config loaders section to use something like this:

```<code>rules: [
  ...
  {
    test: /\.json$/,
    use: 'json-loader'
  }
  ...
]
</code>```

Given that you are using the webpack v1 config may look a bit different to you.

Body:
Please refer import that is causing error.It compiles without any issue if I comment this line.

import React, {Component} from 'react';
import {returnCurrencies} from '../reducers/reducer_currency';
import {DropdownMenu, DropdownMenuList, DropdownMenuListItem} from 'react-lds';

export default class CurrencyDropDown extends Component
{
   constructor(props)
   {
      super(props);
      //console.log("props",props);
   }
   renderCurrencies(curr)
   {
      //console.log("Curr ", curr);
      return (<option key={curr} value={curr}>{curr}</option>);
   }
   render()
   {
      if(!this.props.currencies)
      {
        return (

);
      }
      let currencyList = returnCurrencies(this.props.currencies);
       return (

          <select value={this.props.initValue} onChange=
              {this.props.selectCurrency}>
            {currencyList.map(this.renderCurrencies)}
          </select>

);
 }
}

Package.json

{
  "name": "redux-simple-starter",
  "version": "1.0.0",
  "description": "Simple starter package for Redux with React and Babel support",
   "main": "index.js",
   "repository": "",
   "scripts": {
       "start": "node ./node_modules/webpack-dev-server/bin/webpack-dev-server.js",
       "test": "mocha --compilers js:babel-core/register --require ./test/test_helper.js --recursive ./test",
       "test:watch": "npm run test -- --watch"
 },
 "author": "",
 "license": "ISC",
 "devDependencies": {
 "babel-core": "^6.2.1",
 "babel-loader": "^6.2.0",
 "babel-preset-es2015": "^6.1.18",
 "babel-preset-react": "^6.1.18",
 "chai": "^3.5.0",
 "chai-jquery": "^2.0.0",
 "jquery": "^2.2.1",
 "jsdom": "^8.1.0",
 "mocha": "^2.4.5",
 "react-addons-test-utils": "^0.14.7",
 "webpack": "^1.12.9",
 "webpack-dev-server": "^1.14.0"
},
"dependencies": {
"axios": "^0.16.2",
"babel-preset-stage-1": "^6.1.18",
"lodash": "^3.10.1",
"prop-types": "^15.5.10",
"react": "^0.14.9",
"react-dom": "^0.14.9",
"react-lds": "^1.1.11",
"react-redux": "4.3.0",
"react-router": "^2.0.1",
"redux": "^3.0.4",
"redux-promise": "^0.5.3"
}

}

Failed to compile with below error.

ERROR in ./~/moment-timezone/data/packed/latest.json
Module parse failed: C:..\XXXX\node_modules\moment-timezone\data\packed\latest.json Unexpected token (2:10)
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected token (2:10)
    at Parser.pp$4.raise (C:..\XXXX\node_modules\webpack\node_modules\acorn\dist\acorn.js:2221:15)
    at Parser.pp.unexpected (C:..\XXXX\node_modules\webpack\node_modules\acorn\dist\acorn.js:603:10)
    at Parser.pp.semicolon (C:..\XXXX\node_modules\webpack\node_modules\acorn\dist\acorn.js:581:61)
    at Parser.pp$1.parseExpressionStatement (C:..\XXXX\node_modules\webpack\node_modules\acorn\dist\acorn.js:966:10)
    at Parser.pp$1.parseStatement (C:..\XXXX\node_modules\webpack\node_modules\acorn\dist\acorn.js:730:24)
    at Parser.pp$1.parseBlock (C:..\XXXX\node_modules\webpack\node_modules\acorn\dist\acorn.js:981:25)
    at Parser.pp$1.parseStatement (C:..\XXXX\node_modules\webpack\node_modules\acorn\dist\acorn.js:709:33)
    at Parser.pp$1.parseTopLevel (C:..\XXXX\node_modules\webpack\node_modules\acorn\dist\acorn.js:638:25)
    at Parser.parse (C:..\XXXX\node_modules\webpack\node_modules\acorn\dist\acorn.js:516:17)
    at Object.parse (C:..\XXXX\node_modules\webpack\node_modules\acorn\dist\acorn.js:3098:39)
 @ ./~/moment-timezone/index.js 2:15-51

Body:
It fails because it can not load the JSON file. You need to configure webpack to load the JSON files:

Install the json-loader:

npm install --save-dev json-loader

And adjust your webpack config loaders section to use something like this:

rules: [
  ...
  {
    test: /\.json$/,
    use: 'json-loader'
  }
  ...
]

Given that you are using the webpack v1 config may look a bit different to you.


问:
How to import external javascript (which requires jquery) in reactjs
First of all I'm still a newbie in web development. Okay, now to the question.
I have these imports:

```<code>import $ from 'jquery';
window.jQuery = $;
window.$ = $;
global.jQuery = $;
import './assets/js/waves';
</code>```

How do I properly import an external javascript to reactjs if my external javascript requires jquery?

Because based on what these guys have said:

reactjs, bootstrap and npm import - jQuery is not defined

Are ES6 module imports hoisted?

my imports will be hoisted, which results in my external "./assets/js/waves" js causing an error.

```<code>Uncaught ReferenceError: $ is not defined?
</code>```

Thanks in advance!

答:
```<code>import * as jQuery from 'jquery';
</code>```

Then you have a reference of jQuery and you may do with it what you like, for instance:

```<code>window.$ = jQuery;
</code>```

Body:
First of all I'm still a newbie in web development. Okay, now to the question.
I have these imports:

import $ from 'jquery';
window.jQuery = $;
window.$ = $;
global.jQuery = $;
import './assets/js/waves';

How do I properly import an external javascript to reactjs if my external javascript requires jquery?

Because based on what these guys have said:

reactjs, bootstrap and npm import - jQuery is not defined

Are ES6 module imports hoisted?

my imports will be hoisted, which results in my external "./assets/js/waves" js causing an error.

Uncaught ReferenceError: $ is not defined?

Thanks in advance!

Body:
import * as jQuery from 'jquery';

Then you have a reference of jQuery and you may do with it what you like, for instance:

window.$ = jQuery;


问:
How to select periods of time with empty data?
I want to find out all periods with empty data, given the following table my_table:

```<code>id         day
29         2017-06-05
26         2017-06-05
30         2017-06-06
30         2017-06-06
21         2017-06-06
21         2017-07-01
29         2017-07-01
30         2017-07-20
</code>```

The answer would be:

```<code>Empty_start    Empty_end
2017-06-07     2017-06-30
2017-07-02     2017-07-19
</code>```

It's important that the number of months is considered. For example, in the first row the answer 2017-06-31 would be incorrect.

How can I write this query in Hive?

答:
You can use lag() or lead():

```<code>select date_add(day, 1) as empty_start, date_add(next_day, -1) as empty_end
from (select day,
             lead(day) over (order by day) as next_day
      from t
      group by day
     ) t
where next_day <> date_add(day, 1);
</code>```

Body:
I want to find out all periods with empty data, given the following table my_table:

id         day
29         2017-06-05
26         2017-06-05
30         2017-06-06
30         2017-06-06
21         2017-06-06
21         2017-07-01
29         2017-07-01
30         2017-07-20

The answer would be:

Empty_start    Empty_end
2017-06-07     2017-06-30
2017-07-02     2017-07-19

It's important that the number of months is considered. For example, in the first row the answer 2017-06-31 would be incorrect.

How can I write this query in Hive?

Body:
You can use lag() or lead():

select date_add(day, 1) as empty_start, date_add(next_day, -1) as empty_end
from (select day,
             lead(day) over (order by day) as next_day
      from t
      group by day
     ) t
where next_day <> date_add(day, 1);


问:
Why isn’t my object collected by an autorelease pool?
I wrote an simple demo

```<code>@implementation A

- (void)a{
    NSLog(@"%@",url);
}

-(id)init{
    self = [super init];
    url = [NSURL URLWithString:@"http://xxx.com"];
    return self;
}
@end

A *a = [A new];
while (YES) {
    [NSThread sleepForTimeInterval:0.5];
    [a a];
}
</code>```

but seems it will keep running and never crash.
so when will an autorelease object be releaed?

答:
No run-loop processing is done while the thread sleeps, so that the main run loop never runs during your endless while-loop and autoreleased objects are not collected by the default pool. If you spin the run loop, your code should crash just fine:

```<code>[[NSRunLoop mainRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.1]];
</code>```

But it might be the case that the simple NSLog will work even though the object was released. Enabling zombies should do the trick for sure (provided that you spin the run loop).

Body:
I wrote an simple demo

@implementation A

- (void)a{
    NSLog(@"%@",url);
}

-(id)init{
    self = [super init];
    url = [NSURL URLWithString:@"http://xxx.com"];
    return self;
}
@end

A *a = [A new];
while (YES) {
    [NSThread sleepForTimeInterval:0.5];
    [a a];
}

but seems it will keep running and never crash.
so when will an autorelease object be releaed?

Body:
No run-loop processing is done while the thread sleeps, so that the main run loop never runs during your endless while-loop and autoreleased objects are not collected by the default pool. If you spin the run loop, your code should crash just fine:

[[NSRunLoop mainRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.1]];

But it might be the case that the simple NSLog will work even though the object was released. Enabling zombies should do the trick for sure (provided that you spin the run loop).


问:
How do I make a function return a value to be used immediately as part of the calling script?
I want to make a function that I can wrap around certain things and change the output based on the current user.

Assume there is a master user called "av". If the person currently using the DB is "av", then I need to alter the VBA code to allow him better priveleges.

```<code>Public Function masteruser(input_parm)

   If GetUser = "av" Then

       masteruser = ""

   Else

       masteruser = input_parm

End Function
</code>```

I plan on using the function above like this:

```<code>Public Sub blah_FormTimer()

   'rest of code

    masteruser(Application.Quit)

    'rest of code

End Sub
</code>```

In the sub above, if the current user is "av", then the Application.Quit will effectively be removed. If not, then the code reads Application.Quit like normal.

How do I handle the input parameter in such a way as to return it to work with the rest of the VBA script like normal?

答:
You can first create a wrapper sub/function, because Application.Quit is a method call and not a function call:

```<code>Public Sub QuitApplication()
    Application.Quit
End Sub
</code>```

And then use the following code:

```<code>Public Function masteruser(input_parm As String)
   If GetUser = "av" Then
       masteruser = ""
   Else
       Application.Run input_parm
   End If
End Function
</code>```

And of course

```<code>Public Sub blah_FormTimer()

   'rest of code

    masteruser "QuitApplication"

    'rest of code

End Sub
</code>```

You can of course create a function that creates a module, creates a wrapper sub/function, then pastes the code that you pass it in that function and executes it, and then deletes that module, but I wouldn't suggest it.

You can also make one especially for method calls, which would prevent the need for making wrapper functions for them:

```<code>Public Function masterusermethod(objObject as object, strMethod As String)
   If GetUser = "av" Then
       masteruser = ""
   Else
       CallByName objObject, strMethod, VbMethod
   End If
End Function
</code>```

(If anyone knows a more efficient way to do this, I'd like to know)

Body:
I want to make a function that I can wrap around certain things and change the output based on the current user.

Assume there is a master user called "av". If the person currently using the DB is "av", then I need to alter the VBA code to allow him better priveleges.

Public Function masteruser(input_parm)

   If GetUser = "av" Then

       masteruser = ""

   Else

       masteruser = input_parm

End Function

I plan on using the function above like this:

Public Sub blah_FormTimer()

   'rest of code

    masteruser(Application.Quit)

    'rest of code

End Sub

In the sub above, if the current user is "av", then the Application.Quit will effectively be removed. If not, then the code reads Application.Quit like normal.

How do I handle the input parameter in such a way as to return it to work with the rest of the VBA script like normal?

Body:
You can first create a wrapper sub/function, because Application.Quit is a method call and not a function call:

Public Sub QuitApplication()
    Application.Quit
End Sub

And then use the following code:

Public Function masteruser(input_parm As String)
   If GetUser = "av" Then
       masteruser = ""
   Else
       Application.Run input_parm
   End If
End Function

And of course

Public Sub blah_FormTimer()

   'rest of code

    masteruser "QuitApplication"

    'rest of code

End Sub

You can of course create a function that creates a module, creates a wrapper sub/function, then pastes the code that you pass it in that function and executes it, and then deletes that module, but I wouldn't suggest it.

You can also make one especially for method calls, which would prevent the need for making wrapper functions for them:

Public Function masterusermethod(objObject as object, strMethod As String)
   If GetUser = "av" Then
       masteruser = ""
   Else
       CallByName objObject, strMethod, VbMethod
   End If
End Function

(If anyone knows a more efficient way to do this, I'd like to know)


问:
Simple XCTest for UITest is failing all the time?
I start a new project from File -> New -> project

I add a button to ViewController.

I open UITest folder which created by xcode by default. Run the test code.

It fails:

```<code>2016-03-16 12:57:09.191 XCTRunner[3511:150419] Continuing to run tests in the background with task ID 1
    t =    10.18s         Assertion Failure: UI Testing Failure - Failed to background test runner.
/Users/Bernard/Desktop/ExampleTestApplication/ExampleTestApplicationUITests/test2.m:27: error: -[test2 testExample] : UI Testing Failure - Failed to background test runner.
2016-03-16 12:57:12.789 XCTRunner[3511:150419] *** Terminating app due to uncaught exception '_XCTestCaseInterruptionException', reason: 'Interrupting test'
</code>```

Now I add a break point as follow:

Now test is successful! Anyone can explain the reason?

答:
I was also facing same issues and none of the available solutions worked for me. Issue was not letting app to attach to the simulator itself.
I checked the log and saw that i did a mistake in code while locating the element. for Predicate instead of BEGINSWITH i wrote STARTSWITH and this was stopping the app to get attached.
So check your logs in the test report to get the issue.</p>

Body:
I start a new project from File -> New -> project

I add a button to ViewController.

I open UITest folder which created by xcode by default. Run the test code.

It fails:

2016-03-16 12:57:09.191 XCTRunner[3511:150419] Continuing to run tests in the background with task ID 1
    t =    10.18s         Assertion Failure: UI Testing Failure - Failed to background test runner.
/Users/Bernard/Desktop/ExampleTestApplication/ExampleTestApplicationUITests/test2.m:27: error: -[test2 testExample] : UI Testing Failure - Failed to background test runner.
2016-03-16 12:57:12.789 XCTRunner[3511:150419] *** Terminating app due to uncaught exception '_XCTestCaseInterruptionException', reason: 'Interrupting test'

Now I add a break point as follow:

Now test is successful! Anyone can explain the reason?


问:
Moving the screen scroll position after page jumps to anchor point?
I have a menu on a single webpage whose links move the page to the section with the corresponding ID. However, there is a sticky header that is covering the top part of each section, so I want to scroll slightly to compensate.

I'm trying to determine a way to scroll the page by 50px after the page moves to a section. I tried doing a .click() event listener on each link, but it appears that the page is moved after the callback is issued, negating my attempt to scroll.

My code looks like the following:

HTML:

```<code><ul id="menu">
    <li id="menu-item-1"><a href="#1">1</a></li>
    <li id="menu-item-2"><a href="#2">2</a></li>
    <li id="menu-item-3"><a href="#3">3</a></li>
    <li id="menu-item-4"><a href="#4">4</a></li>
</ul>
</code>```

JS: (the two interior lines work in the console but not in the page code itself)

```<code>$('#menu-item-1 a').click(function(){
    var y = $(window).scrollTop();
    $(window).scrollTop(y-50);
});
</code>```

Is there a way to listen for a link action to be completed, then run my scroll code?

答:
did you try setting a timeout, it will have a flicker effect though (unnoticeable)

also you can change your click event to handle all the a tags within li item like this

```<code>$('li > a').click(function(){
  setTimeout(function(){
        var y = $(window).scrollTop();
        $(window).scrollTop(y-50); }, 1);
});
</code>```

here is a sample fiddle for you https://jsfiddle.net/fxabnk4o/16/

Body:
I have a menu on a single webpage whose links move the page to the section with the corresponding ID. However, there is a sticky header that is covering the top part of each section, so I want to scroll slightly to compensate.

I'm trying to determine a way to scroll the page by 50px after the page moves to a section. I tried doing a .click() event listener on each link, but it appears that the page is moved after the callback is issued, negating my attempt to scroll.

My code looks like the following:

HTML:

1

2

3

4

JS: (the two interior lines work in the console but not in the page code itself)

$('#menu-item-1 a').click(function(){
    var y = $(window).scrollTop();
    $(window).scrollTop(y-50);
});

Is there a way to listen for a link action to be completed, then run my scroll code?

Body:
did you try setting a timeout, it will have a flicker effect though (unnoticeable)

also you can change your click event to handle all the a tags within li item like this

$('li > a').click(function(){
  setTimeout(function(){
        var y = $(window).scrollTop();
        $(window).scrollTop(y-50); }, 1);
});

here is a sample fiddle for you https://jsfiddle.net/fxabnk4o/16/


问:
How can I monkey-patch an instance method in Perl?
I'm trying to monkey-patch (duck-punch :-) a LWP::UserAgent instance, like so:

```<code>sub _user_agent_get_basic_credentials_patch {
  return ($username, $password);
}

my $agent = LWP::UserAgent->new();
$agent->get_basic_credentials = _user_agent_get_basic_credentials_patch;
</code>```

This isn't the right syntax -- it yields:

Can't modify non-lvalue subroutine
  call at [module] line [lineno].

As I recall (from Programming Perl), dispatch lookup is performed dynamically based on the blessed package (ref($agent), I believe), so I'm not sure how instance monkey patching would even work without affecting the blessed package.

I know that I can subclass the UserAgent, but I would prefer the more concise monkey-patched approach. Consenting adults and what have you. ;-)

答:
As answered by Fayland Lam, the correct syntax is:

```<code>    local *LWP::UserAgent::get_basic_credentials = sub {
        return ( $username, $password );
    };
</code>```

But this is patching (dynamically scoped) the whole class and not just the instance. You can probably get away with this in your case.

If you really want to affect just the instance, use the subclassing you described. This can be done 'on the fly' like this:

```<code>{
   package My::LWP::UserAgent;
   our @ISA = qw/LWP::UserAgent/;
   sub get_basic_credentials {
      return ( $username, $password );
   };

   # ... and rebless $agent into current package
   $agent = bless $agent;
}
</code>```

OwnerDisplayName: cdleary

Body:
I'm trying to monkey-patch (duck-punch :-) a LWP::UserAgent instance, like so:

sub _user_agent_get_basic_credentials_patch {
  return ($username, $password);
}

my $agent = LWP::UserAgent->new();
$agent->get_basic_credentials = _user_agent_get_basic_credentials_patch;

This isn't the right syntax -- it yields:

Can't modify non-lvalue subroutine
  call at [module] line [lineno].

As I recall (from Programming Perl), dispatch lookup is performed dynamically based on the blessed package (ref($agent), I believe), so I'm not sure how instance monkey patching would even work without affecting the blessed package.

I know that I can subclass the UserAgent, but I would prefer the more concise monkey-patched approach. Consenting adults and what have you. ;-)

LastEditorDisplayName: cdleary

Body:
As answered by Fayland Lam, the correct syntax is:

    local *LWP::UserAgent::get_basic_credentials = sub {
        return ( $username, $password );
    };

But this is patching (dynamically scoped) the whole class and not just the instance. You can probably get away with this in your case.

If you really want to affect just the instance, use the subclassing you described. This can be done 'on the fly' like this:

{
   package My::LWP::UserAgent;
   our @ISA = qw/LWP::UserAgent/;
   sub get_basic_credentials {
      return ( $username, $password );
   };

   # ... and rebless $agent into current package
   $agent = bless $agent;
}


问:
Get country from latitude longitude
I would like to know how I can get the country name from latitude & longitude using JavaScript. I am open to use of Google Maps’ JavaScript API. Can I also get city and zip?

Edit: My aim is to fill up the address field automatically, not to display it on a map.

答:
Yes, you can use google maps to find the country for given latitudes and longitudes. Use the reverse geocoding service.

You can get the country, city, zip code and the complete address from the response you get from the server. Check the example from the link for details ;)

ContentLicense: CC BY-SA 4.0

Title: Get country from latitude longitude


问:
How do I filter my log file based on categories with .NET Core logging?
I've configured my logger factory like so,

```<code>loggerFactory
    .AddConsole()
    .AddDebug()
    .AddFile("Logs/trace-{Date}.txt");
</code>```

and in my constructors I take dependencies on e.g. ILogger<MyServiceClass>. It is my understanding that the framework will then create a logger instance for my service class, with a category name based on the full name of the type.

In my log file, I see messages like this:

2017-07-07T09:10:46.5678506+02:00 0HL650T1MS1RU [WRN] Socket registration failed for participant b943174e-8022-4e33-ef0d-08d4c4bc4879 in negotiation 42d9720f-32a2-46f9-9042-08d4c4bc4881. (799c4f21)

I seem to remember reading somewhere that the category is hashed to save on file size, so I suspect the mouthful between the timestamp and the log level (0HL...1RU) represents the category, but that's not really searchable or discoverable.

How do I configure my logger to not obfuscate the category names in the log file?

答:
According to the code, you use Serilog.Extensions.Logging.File (the concrete logger implementation is important). That funny string 0HL...1RU actually is a unique Request Id. I guess this logger doesn't support log categories for the plain text logs.

Workaround #1: use JSON logs:

```<code>loggerFactory.AddFile("filename", isJson: true);
</code>```

SourceContext property will appear in the log output having your log category:

```<code>"SourceContext":"MyNamespace.MyServiceClass"
</code>```

Workaround #2: just use another third-party file logger like NLog or full standalone Serilog API.

Body:
I've configured my logger factory like so,

loggerFactory
    .AddConsole()
    .AddDebug()
    .AddFile("Logs/trace-{Date}.txt");

and in my constructors I take dependencies on e.g. ILogger<MyServiceClass>. It is my understanding that the framework will then create a logger instance for my service class, with a category name based on the full name of the type.

In my log file, I see messages like this:

2017-07-07T09:10:46.5678506+02:00 0HL650T1MS1RU [WRN] Socket registration failed for participant b943174e-8022-4e33-ef0d-08d4c4bc4879 in negotiation 42d9720f-32a2-46f9-9042-08d4c4bc4881. (799c4f21)

I seem to remember reading somewhere that the category is hashed to save on file size, so I suspect the mouthful between the timestamp and the log level (0HL...1RU) represents the category, but that's not really searchable or discoverable.

How do I configure my logger to not obfuscate the category names in the log file?

Body:
According to the code, you use Serilog.Extensions.Logging.File (the concrete logger implementation is important). That funny string 0HL...1RU actually is a unique Request Id. I guess this logger doesn't support log categories for the plain text logs.

Workaround #1: use JSON logs:

loggerFactory.AddFile("filename", isJson: true);

SourceContext property will appear in the log output having your log category:

"SourceContext":"MyNamespace.MyServiceClass"

Workaround #2: just use another third-party file logger like NLog or full standalone Serilog API.


问:
How to write a regular expression that matches and indefinite number of groups?
I have a configuration file where rules are defined in the format

```<code>RULENAME : STRING > STRING | STRING > STRING | ... (as many STRING > STRING as necessary)
</code>```

Bellow is an example:

```<code>Rule1 : Type1.Output > Type2.Input;

Rule2 : Type1.Output > Type2.Input |
        Type3.Output > Type4.Input;

Rule3 : Type1.Output > Type2.Input |
        Type1.Output > Type2.Input |
        Type1.Output > Type2.Input |
        Type1.Output > Type2.Input;
</code>```

Just to be clear ANY whitespace (or amount of spaces) is valid between the :, > and the |. The rule ends with the ;

The file will contain other information but none of it has this format. So I would like to write a regular expression that will match each of these rules. The match groups should return the rule name each rule (these are separated by the |) and, if possible (I don't know if it is), subgroups for each string on each side of the > for each rule.

So for Rule2 the match would look something like this:

```<code>Group 1: Rule2
Group 2.1 Type1.Output
Group 2.2 Type2.Input
Group 3.1 Type3.Output
Group 3.2 Type4.Input
</code>```

If the subgroups are not possible, I'm ok with a result .ike

```<code>Group 1: Rule2
Group 2: Type1.Output > Type2.Input
Group 3: Type3.Output > Type4.Input
</code>```

In case it matters, I will be using this in QRegularExpressions in a Qt/C++ program

答:
PCRE (and most regex implementations') repeated capture groups do not capture all matching groups, only the last match. For example:

```<code>"abcd" s|(\w)*|\1|
</code>```

returns

```<code>d
</code>```

not

```<code>a
b
c
d
</code>```

Thus you cannot have a regex match and return all matching capture groups when you repeat capture groups.

You can take a code based approach using regex as one of your tools though, using a regex to capture the entirety of a Rule, then splitting that rule string on | and trimming whitespace from the returned substrings.

Body:
I have a configuration file where rules are defined in the format

RULENAME : STRING > STRING | STRING > STRING | ... (as many STRING > STRING as necessary)

Bellow is an example:

Rule1 : Type1.Output > Type2.Input;

Rule2 : Type1.Output > Type2.Input |
        Type3.Output > Type4.Input;

Rule3 : Type1.Output > Type2.Input |
        Type1.Output > Type2.Input |
        Type1.Output > Type2.Input |
        Type1.Output > Type2.Input;

Just to be clear ANY whitespace (or amount of spaces) is valid between the :, > and the |. The rule ends with the ;

The file will contain other information but none of it has this format. So I would like to write a regular expression that will match each of these rules. The match groups should return the rule name each rule (these are separated by the |) and, if possible (I don't know if it is), subgroups for each string on each side of the > for each rule.

So for Rule2 the match would look something like this:

Group 1: Rule2
Group 2.1 Type1.Output
Group 2.2 Type2.Input
Group 3.1 Type3.Output
Group 3.2 Type4.Input

If the subgroups are not possible, I'm ok with a result .ike

Group 1: Rule2
Group 2: Type1.Output > Type2.Input
Group 3: Type3.Output > Type4.Input

In case it matters, I will be using this in QRegularExpressions in a Qt/C++ program

Body:
PCRE (and most regex implementations') repeated capture groups do not capture all matching groups, only the last match. For example:

"abcd" s|(\w)*|\1|

returns

d

not

a
b
c
d

Thus you cannot have a regex match and return all matching capture groups when you repeat capture groups.

You can take a code based approach using regex as one of your tools though, using a regex to capture the entirety of a Rule, then splitting that rule string on | and trimming whitespace from the returned substrings.


问:
Regular expressions: search (instead of match) with DFA
I have been wondering about theory behind search mode of regex matcher. So, say I have a regex that matches aab, what if instead of match at the beginning of the string I wanna be able to perform this match starting from any position of the string. What I mean - in match mode I can only verify that string aab is consistent with a regex, on the other hand with search this should work with say aaab producing corresponding span result.
So super specifically - is there any way to build DFA searcher, or this is fundamentally impossible since it would require additional memory which you cant have in DFSM. It is obvious though that you can in fact build searcher from matcher by reapplying matcher to input string in a for loop, but complexity of such approach is something like O(len_of_pattern * len_of_input).

答: A regex searcher is basically the same thing as a regex matcher with .* tacked onto the front of the expression.


问:
Understanding foldLeft in Scala
Please help me understand the below statement.  I couldn't understand how foldLeft works here:</p>

```<code>scala> l1
res71: List[Double] = List(1.0, 1.0, 1.0)

scala> l2
res72: List[Double] = List(1.5, 0.0)

scala> l1.foldLeft(l2) { (a,b) => (b + a.head) :: a}
res73: List[Double] = List(4.5, 3.5, 2.5, 1.5, 0.0)
</code>```

答:
foldLeft on List[A] looks like this:

```<code>def foldLeft[B](z: B)(f: (B, A) => B): B
</code>```

It takes in a seed of type B, in your case it's the list l2, which usually acts as an accumulator, and a function which receives the accumulator and a value from the list you're folding over, and returns the type of the accumulator.

In your example:

```<code>(a,b) => (b + a.head) :: a
</code>```

a is a List[Double], and b is a value from the l1 list. It adds the head of the accumulator with the value from l1 and concatenates it with a the accumulator.

I suggest adding a println inside the fold function so you can see the values created in each iteration.

Title: Understanding foldLeft in Scala

Body:
Please help me understand the below statement.  I couldn't understand how foldLeft works here:

scala> l1
res71: List[Double] = List(1.0, 1.0, 1.0)

scala> l2
res72: List[Double] = List(1.5, 0.0)

scala> l1.foldLeft(l2) { (a,b) => (b + a.head) :: a}
res73: List[Double] = List(4.5, 3.5, 2.5, 1.5, 0.0)

Body:
foldLeft on List[A] looks like this:

def foldLeft[B](z: B)(f: (B, A) => B): B

It takes in a seed of type B, in your case it's the list l2, which usually acts as an accumulator, and a function which receives the accumulator and a value from the list you're folding over, and returns the type of the accumulator.

In your example:

(a,b) => (b + a.head) :: a

a is a List[Double], and b is a value from the l1 list. It adds the head of the accumulator with the value from l1 and concatenates it with a the accumulator.

I suggest adding a println inside the fold function so you can see the values created in each iteration.


问:
Lodash update element values from another array Chain / Map
How I can update an array element values with another array elements data values, using Lodash

```<code>var Master_Array [
{ Name: "Jon", Region: "North America & Caribbean" },
{ Name: "Ruan", Region: "Asia Pacific" }
]

var Regions_Map = [
{ Region: 'Europe', NewRegion: 'EMEA' },
{ Region: 'North America & Caribbean', NewRegion: 'NAC' },
{ Region: 'Asia Pacific', NewRegion: 'APAC' }
]
</code>```

I think that can be did with:

```<code>_.chain()
.mapValues( ...blá blá... )
.values()
.value();
</code>```

Expected result:

```<code>var Master_Array [
{ Name: "Jon", Region: "NAC" },
{ Name: "Ruan", Region: "APAC" }
]
</code>```

答:
you don't need to execute mapValues as you are iterating a collection and not an object, mapKeys and mapValues is preferable iterating objects and mapped to another

Now, approach 1, if you want to run something that will return a new array of your expected items then try with map like this

```<code>var EXPECTED_RESULT = _.map(Master_Array, function(item){
    var newItem = {};
    newItem.Name = item.Name;
    newItem.Region = _.find(Regions_Map, {Region: item.Region}).NewRegion
    return newItem;
});
</code>```

and if you want to modify the existing array, then just loop over it either by loadash or normal javascript loop, and perform the operation

```<code>_.each(Master_Array,function(item){
    item.Region = _.find(Regions_Map, {Region: item.Region}).NewRegion
} )
</code>```

Body:
How I can update an array element values with another array elements data values, using Lodash

var Master_Array [
{ Name: "Jon", Region: "North America & Caribbean" },
{ Name: "Ruan", Region: "Asia Pacific" }
]

var Regions_Map = [
{ Region: 'Europe', NewRegion: 'EMEA' },
{ Region: 'North America & Caribbean', NewRegion: 'NAC' },
{ Region: 'Asia Pacific', NewRegion: 'APAC' }
]

I think that can be did with:

_.chain()
.mapValues( ...blá blá... )
.values()
.value();

Expected result:

var Master_Array [
{ Name: "Jon", Region: "NAC" },
{ Name: "Ruan", Region: "APAC" }
]

Body:
you don't need to execute mapValues as you are iterating a collection and not an object, mapKeys and mapValues is preferable iterating objects and mapped to another

Now, approach 1, if you want to run something that will return a new array of your expected items then try with map like this

var EXPECTED_RESULT = _.map(Master_Array, function(item){
    var newItem = {};
    newItem.Name = item.Name;
    newItem.Region = _.find(Regions_Map, {Region: item.Region}).NewRegion
    return newItem;
});

and if you want to modify the existing array, then just loop over it either by loadash or normal javascript loop, and perform the operation

_.each(Master_Array,function(item){
    item.Region = _.find(Regions_Map, {Region: item.Region}).NewRegion
} )


问:
what is the diffence between WAS and IIS?
Is WAS distinct from IIS?
How is WAS better than IIS?</p>

答:
Windows Process Activation Service, also referred to as WPAS, is a new component in IIS 7.0 that manages application pool configuration and worker processes instead of the WWW process. This enables the same configuration for both HTTP and non-HTTP sites to be used.

http://searchwindowsserver.techtarget.com/tip/Windows-Process-Activation-Service-in-IIS-70


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

Controller

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

json

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

POJO

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

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

答: Make properties public and annotate each property with @JsonProperty() (i.e. @JsonProperty("grouping") ), for example. It's likely your getters and setters don't follow standard naming convention. </p>

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

Controller

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

json

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

POJO

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

       //setter/getter
    }


问:
Ruby on Rails omniauth and carrierwave
I'm using omniauth ( omniauth-facebook) in my ruby on rails application. I would like to know whether I can retrieve user's city, country and gender information. And how can I take user profile photo with carrierwave,

Thanks.

答:
Usually omniauth will return a standard answer that is only concerned with authentication, basically a hash with a combination of email, name/first/last, profile_picture url, username, etc. Some providers give you email, others don't, others only provide some fields if you ask specifically for them through scopes.

For facebook I'm using the following on my omniauth.rb (inside config/initializers/*)

```<code>provider :facebook, ENV['FB_ID'], ENV['FB_SECRET'], scope: 'public_profile, email, manage_pages, user_friends', info_fields: 'id, first_name, last_name, link, email', image_size: 'large'
</code>```

This means that facebook will provide me an email, some basic info such as ID, first name and last name on the response hash (that omniauth takes care of arranging) after a successful oauth authorization. The token it will provide will also be scoped for managing pages although I don't ask for any field related to it initially.

So in your case you would ask for city, country and whatever in info_fields (double checking through their graph explorer that you don't need any extra scope for those fields).

After you get the response through omniauth (which is basically a piece of code written as middleware, that does the oauth2 flow for you - you could do it by yourself as well) you'll have a profile pic url.
You'll want to download that picture.
Using carrierwave you do that either on your controller or module/class by instantiating the column where you have the uploader set and then executing the method .download! passing it the url from where to download:

```<code>user.avatar = AvatarUploader.new
user.avatar.download! omniauth_hash['blabla_fields']['blabla_picture_url']
</code>```

This will download a remote picture url and save it as a regular carrierwave attachment, that you can then access through your model normally.

Title: Ruby on Rails omniauth and carrierwave

Body:
Usually omniauth will return a standard answer that is only concerned with authentication, basically a hash with a combination of email, name/first/last, profile_picture url, username, etc. Some providers give you email, others don't, others only provide some fields if you ask specifically for them through scopes.

For facebook I'm using the following on my omniauth.rb (inside config/initializers/*)

provider :facebook, ENV['FB_ID'], ENV['FB_SECRET'], scope: 'public_profile, email, manage_pages, user_friends', info_fields: 'id, first_name, last_name, link, email', image_size: 'large'

This means that facebook will provide me an email, some basic info such as ID, first name and last name on the response hash (that omniauth takes care of arranging) after a successful oauth authorization. The token it will provide will also be scoped for managing pages although I don't ask for any field related to it initially.

So in your case you would ask for city, country and whatever in info_fields (double checking through their graph explorer that you don't need any extra scope for those fields).

After you get the response through omniauth (which is basically a piece of code written as middleware, that does the oauth2 flow for you - you could do it by yourself as well) you'll have a profile pic url.
You'll want to download that picture.
Using carrierwave you do that either on your controller or module/class by instantiating the column where you have the uploader set and then executing the method .download! passing it the url from where to download:

user.avatar = AvatarUploader.new
user.avatar.download! omniauth_hash['blabla_fields']['blabla_picture_url']

This will download a remote picture url and save it as a regular carrierwave attachment, that you can then access through your model normally.