问:
Trail of nodes along a path as in hello world
hi I have a node traveling back and forth along a path. I am trying to integrate the moving shapeNode as in the hello world example to trail my moving node. I'm using a trigger from frame update to trigger the copying of the shape node. And using the position of the travelling node.

The problem is that the trail has some sort of offset and i don't know where its coming from. I have tried to compensate but to no avail. I'm wondering if it might have anything to do with the actions. Thanks for reading.

I have tried looking at this link  but i cannot translate

Here is my code so far

spriteKit xcode 9 swift 4 iPad Air

```<code>//  GameScene.swift

import SpriteKit

    class GameScene: SKScene, SKPhysicsContactDelegate {
    var borderBody = SKPhysicsBody()
    var myMovingNode = SKSpriteNode()
    var trailNode : SKShapeNode?

override func didMove(to view: SKView) {
    //Define Border
    borderBody = SKPhysicsBody(edgeLoopFrom: self.frame)
    borderBody.friction = 0
    self.physicsBody = borderBody
    physicsWorld.gravity = CGVector(dx: 0.0, dy: 0.0)
    physicsWorld.contactDelegate = self

    //Define myMovingNode
    myMovingNode = SKSpriteNode(imageNamed: "greenball")
    myMovingNode.size.width = 50
    myMovingNode.size.height = 50
    let myMovingNodeBody:CGSize = CGSize(width: 50, height: 50)
    myMovingNode.physicsBody = SKPhysicsBody.init(rectangleOf: myMovingNodeBody)
    myMovingNode.zPosition = 2
    addChild(myMovingNode)

    //Make Path for myMovingNode to travel
    let myPath = CGMutablePath()
    myPath.move(to: CGPoint(x: 30, y: 30))

    myPath.addLine(to: CGPoint(x: 500, y: 500))

    /*This is another path to try*/
     // myPath.addCurve(to: CGPoint(x: 800, y: 700), control1: CGPoint(x: 500, y: 30), control2: CGPoint(x: 50, y: 500))

    /*This draws a line along myPath*/
    let myLine = SKShapeNode(path: myPath)
    myLine.lineWidth = 10
    myLine.strokeColor = .green
    myLine.glowWidth = 0.5
    myLine.zPosition = 2
    addChild(myLine)

    /*This sets myMovingNode running along myPath*/
    let actionForward = SKAction.follow(myPath, asOffset: false, orientToPath: true, duration: 10)
    let actionReverse = actionForward.reversed()
    let wait = SKAction.wait(forDuration: 1)
    let actionSequence = SKAction.sequence([actionForward, wait, actionReverse, wait])
    myMovingNode.run(SKAction.repeatForever(actionSequence))

    /*This defines TrailNode and its actions*/
    trailNode = SKShapeNode.init(rectOf: CGSize.init(width: 20, height: 20), cornerRadius: 10)
    if let trailNode = trailNode {
    trailNode.lineWidth = 1
    trailNode.fillColor = .cyan
    trailNode.run(SKAction.sequence([SKAction.wait(forDuration: 5),
                  SKAction.fadeOut(withDuration: 3),
                  SKAction.removeFromParent()]))
    }//Eo if Let

}//eo overdrive

func timeFunction (){/*This is controlled by func update*/
    let n = trailNode?.copy() as! SKShapeNode?

    /*this is where i'm trying to compensate*/
    let movingNodeX = myMovingNode.position.x
    let movingNodeY = myMovingNode.position.y
    let movingNodeOffSet = CGPoint(x: movingNodeX - 0, y: movingNodeY - 0)

    n?.position = movingNodeOffSet
    myMovingNode.addChild(n!)
}

var frameCounter = 0
override func update(_ currentTime: TimeInterval) {
    // print( "Called before each frame is rendered")
    if frameCounter == 10{frameCounter = 0; timeFunction()}
    frameCounter = frameCounter + 1
}

}//class GameScene
</code>```

答:
hi in answer to my own question. It was the simplest. On the last line change from

myMovingNode.addChild(n!) to addChild(n!)

Body:
hi I have a node traveling back and forth along a path. I am trying to integrate the moving shapeNode as in the hello world example to trail my moving node. I'm using a trigger from frame update to trigger the copying of the shape node. And using the position of the travelling node.

The problem is that the trail has some sort of offset and i don't know where its coming from. I have tried to compensate but to no avail. I'm wondering if it might have anything to do with the actions. Thanks for reading.

I have tried looking at this link  but i cannot translate

Here is my code so far

spriteKit xcode 9 swift 4 iPad Air

//  GameScene.swift

import SpriteKit

    class GameScene: SKScene, SKPhysicsContactDelegate {
    var borderBody = SKPhysicsBody()
    var myMovingNode = SKSpriteNode()
    var trailNode : SKShapeNode?

override func didMove(to view: SKView) {
    //Define Border
    borderBody = SKPhysicsBody(edgeLoopFrom: self.frame)
    borderBody.friction = 0
    self.physicsBody = borderBody
    physicsWorld.gravity = CGVector(dx: 0.0, dy: 0.0)
    physicsWorld.contactDelegate = self

    //Define myMovingNode
    myMovingNode = SKSpriteNode(imageNamed: "greenball")
    myMovingNode.size.width = 50
    myMovingNode.size.height = 50
    let myMovingNodeBody:CGSize = CGSize(width: 50, height: 50)
    myMovingNode.physicsBody = SKPhysicsBody.init(rectangleOf: myMovingNodeBody)
    myMovingNode.zPosition = 2
    addChild(myMovingNode)

    //Make Path for myMovingNode to travel
    let myPath = CGMutablePath()
    myPath.move(to: CGPoint(x: 30, y: 30))

    myPath.addLine(to: CGPoint(x: 500, y: 500))

    /*This is another path to try*/
     // myPath.addCurve(to: CGPoint(x: 800, y: 700), control1: CGPoint(x: 500, y: 30), control2: CGPoint(x: 50, y: 500))

    /*This draws a line along myPath*/
    let myLine = SKShapeNode(path: myPath)
    myLine.lineWidth = 10
    myLine.strokeColor = .green
    myLine.glowWidth = 0.5
    myLine.zPosition = 2
    addChild(myLine)

    /*This sets myMovingNode running along myPath*/
    let actionForward = SKAction.follow(myPath, asOffset: false, orientToPath: true, duration: 10)
    let actionReverse = actionForward.reversed()
    let wait = SKAction.wait(forDuration: 1)
    let actionSequence = SKAction.sequence([actionForward, wait, actionReverse, wait])
    myMovingNode.run(SKAction.repeatForever(actionSequence))

    /*This defines TrailNode and its actions*/
    trailNode = SKShapeNode.init(rectOf: CGSize.init(width: 20, height: 20), cornerRadius: 10)
    if let trailNode = trailNode {
    trailNode.lineWidth = 1
    trailNode.fillColor = .cyan
    trailNode.run(SKAction.sequence([SKAction.wait(forDuration: 5),
                  SKAction.fadeOut(withDuration: 3),
                  SKAction.removeFromParent()]))
    }//Eo if Let

}//eo overdrive

func timeFunction (){/*This is controlled by func update*/
    let n = trailNode?.copy() as! SKShapeNode?

    /*this is where i'm trying to compensate*/
    let movingNodeX = myMovingNode.position.x
    let movingNodeY = myMovingNode.position.y
    let movingNodeOffSet = CGPoint(x: movingNodeX - 0, y: movingNodeY - 0)

    n?.position = movingNodeOffSet
    myMovingNode.addChild(n!)
}

var frameCounter = 0
override func update(_ currentTime: TimeInterval) {
    // print( "Called before each frame is rendered")
    if frameCounter == 10{frameCounter = 0; timeFunction()}
    frameCounter = frameCounter + 1
}

}//class GameScene


来源: stackexchange

问:
Clojure 1.2 is released! How to get swank-clojure to use this?
I just set up a new emacs installation, installed ELPA and installed swank-clojure with using ELPA. Although Clojure 1.2 is released, when I hit "M-x slime", it still downloaded Clojure 1.1 for me instead of 1.2

How do I get it to use 1.2 now that it's available? Do I have to do it manually? Do I have to wait for slime/swank to be updated to use 1.2?

Update: Thanks for the recommendations for using leiningen, but what I'm after is for emacs to just launch a REPL itself. Is this problem happening because the swank-clojure package in ELPA is not being updated?

答:
You just need to set  the swank-clojure-classpath variable before you hit M-x slime

Say if you have the clojure.jar, clojure-contrib.jar and swank-clojure.jar under c:\jars

In the scratch buffer paste this

```<code>(setq swank-clojure-classpath '("c:/jars/clojure.jar" "c:/jars/cloure-contrib.jar"
"c:/jars/swank-clojure.jar"))
</code>```

Hit C-x C-e and the M-x slime , that should do it.

For details checkout

https://github.com/jochu/swank-clojure/blob/master/swank-clojure.el#L32-34

http://en.wikibooks.org/wiki/Clojure_Programming/FAQ#Where_does_swank-clojure_.28SLIME.29_look_for_Clojure.27s_jars.3F

ContentLicense: CC BY-SA 2.5

Body:
You just need to set  the swank-clojure-classpath variable before you hit M-x slime

Say if you have the clojure.jar, clojure-contrib.jar and swank-clojure.jar under c:\jars

In the scratch buffer paste this

(setq swank-clojure-classpath '("c:/jars/clojure.jar" "c:/jars/cloure-contrib.jar"
"c:/jars/swank-clojure.jar"))

Hit C-x C-e and the M-x slime , that should do it.

For details checkout

https://github.com/jochu/swank-clojure/blob/master/swank-clojure.el#L32-34

http://en.wikibooks.org/wiki/Clojure_Programming/FAQ#Where_does_swank-clojure_.28SLIME.29_look_for_Clojure.27s_jars.3F


问:
How do I change the timezone to UTC in postgres permanently?
I have set the timezone in postgresql.conf as follows :-

```<code>- Locale and Formatting -

datestyle = 'iso, mdy'
#intervalstyle = 'postgres'
timezone = 'UTC'
#timezone_abbreviations = 'Default'
</code>```

But When I do see the timezone in postgres server it defaults to 'Asia/Kolkata'.
I have installed the postgres using brew package in MacOs.

答:
There are many ways to set configuration variables. But most of these setting can be overruled by the client inside its transaction. (Some settings require a server restart or have other restrictions, but not timezone.)

To make absolutely sure, some operations happen with timezone = 'UTC', you could encapsulate that in a server-side function with its own setting, overriding any user-setting. Find a code example in this related answer:

How does the search_path influence identifier resolution and the "current schema"

But while that fits the wording of your question, I don't think that's what you are looking for. You probably just need to reload after changing postgresql.conf to set the default for new sessions.

ContentLicense: CC BY-SA 3.0

Body:
I have set the timezone in postgresql.conf as follows :-

- Locale and Formatting -

datestyle = 'iso, mdy'
#intervalstyle = 'postgres'
timezone = 'UTC'
#timezone_abbreviations = 'Default'

But When I do see the timezone in postgres server it defaults to 'Asia/Kolkata'.
I have installed the postgres using brew package in MacOs.


问:
Cannot disable submit button by $invalid while page load
I am trying to invalidate and disable the submit button on the load of the page, as not entering text into textbox is invalid, but my code is not working, can someone please provide the solution.

```<code><div id="reg_bground">
    <div id="formdiv" ng-app="myApp" ng-controller="valCtrl">
        <form name="myForm" novalidate>
            <div style="font-family:calibri; font-size:30px; font-weight:bolder;">
                <span>Register:</span>
            </div>
            <div>
                <span>Name:</span><br>
                <input type="text" name="user" ng-model="user" required><br>
                <p ng-show="myForm.user.$dirty && myForm.user.$invalid">*Please insert the name</p>
            </div>
            <input type="number">
            <input type="submit" ng-disabled="myForm.user.$dirty && myForm.user.$invalid">
        </form>
    </div>
</div>
</code>```

答:
You essentially check for $dirty state in the submit button for disabled status.

```<code><input type="submit" ng-disabled="myForm.user.$dirty && myForm.user.$invalid">
</code>```

$dirty is only set to true when user has meddled with the myForm.user input, which is not the case on page load. Instead, try checking the $pristine state (or !$dirty)

```<code><input type="submit" ng-disabled="myForm.user.$pristine || myForm.user.$invalid">
</code>```

Body:
I am trying to invalidate and disable the submit button on the load of the page, as not entering text into textbox is invalid, but my code is not working, can someone please provide the solution.

        <form name="myForm" novalidate>

                Register:

                Name:

                <input type="text" name="user" ng-model="user" required>

*Please insert the name

            <input type="number">
            <input type="submit" ng-disabled="myForm.user.$dirty && myForm.user.$invalid">
        </form>

Body:
You essentially check for $dirty state in the submit button for disabled status.

<input type="submit" ng-disabled="myForm.user.$dirty && myForm.user.$invalid">

$dirty is only set to true when user has meddled with the myForm.user input, which is not the case on page load. Instead, try checking the $pristine state (or !$dirty)

<input type="submit" ng-disabled="myForm.user.$pristine || myForm.user.$invalid">


问:
Fatal error compiling: tools.jar not found - maven-compiler-plugin
Issue: The following problem occurs when I compile my project w/ maven (note: I'm working on windows):

Failed to execute goal
  org.apache.maven.plugins:maven-compiler-plugin:2.5.1:compile
  (default-compile) on project XYZ:  Fatal error compiling: tools.jar
  not found: C:\java\jdk1.8.0_40..\lib\tools.jar -> [Help 1]

Error occurs from both command line and eclipse (Eclipse STS) - mvn clean; mvn install

Notes:

System env variable, JAVA_HOME, was set to C:\java\jdk1.8.0_40

C:\java\jdk1.8.0_40\lib\tools.jar is there

Tried clearing local maven repo (.m2) - error still occurred

configured maven compiler plugin to point to C:/java/jdk1.7.0_75/bin/javac.exe executable with source=target=1.7 - same error

Tried installing java 1.7.0_75 in eclipse and using that (but maven is still used for the compile -- right-click on project, run as, maven install): same error (even with maven compiler's plugin configuration's executable set to C:/java/jdk1.7.0_75/bin/javac.exe)

答: When I added the JDK to the Libraries the problem was solved. The issue is like tools.jar is not found as part of the jre distribution</p>


问:
Two rest api response diff using rest assured
I am trying to compare the rest API response of two environments. I am using rest assured to get the response back. The problem I am facing is that I get a hashmap back which has a couple of hashmaps.

I have tried flattening the map into one map but keep on missing a hierarchy when the response differs slightly

here is a sample of the rest response

```<code>{
   programmes:[
      {
         episodenumber:21,
         seasonnumber:5,
         seasontitle:"program Season 5",
         seasonuuid:"7aabb30e-39a1-48bb-8dca-38f732c9c982",
         seriestitle:"programm",
         seriesuuid:"f95caa09-8cd7-4e23-a88a-444f7932714d",
         sy:"blah blah blah. (S5, ep 21)",
         t:"blah blah Fathers",
         trailer:false,
         type:"programme",
         uuid:"69b91264-37c9-4b2f-a515-b45805a58867",
         uuidtype:"programme",
         waystowatch:{
            svod:[
               {
                  ad:false,
                  added:1495800164,
                  at:"DD",
                  availendtime:1497729599,
                  broadcasttime:1495137600,
                  cgid:10053,
                  cgname:"blah",
                  channelname:"blah1 HD",
                  d:2880,
                  downloadlink:"oig://FFC27E94",
                  hardofhearing:false,
                  is3d:false,
                  providerid:"ab_st_hd",
                  providername:"blah HD",
                  s:true,
                  sid:4061,
                  size:2352611,
                  sy:"blah blah. (S5, ep 21)",
                  videotype:"HD"
               }
            }
         ]         ps:255,
         tc:3
      }
</code>```

I am using the guava diff lib and for that, i need a simple map. I know this might not be the best of doing this comparison but this is for a short duration and this is what I can come up with. My question is how do I either flatten this response to make one map which i can pass to

```<code> MapDifference<String, ?> diff = Maps.difference(test, test2);
</code>```

or is there a better way to compare two responses in rest assured. I have to get both the response at runtime.

答:
If you are open to evaluating other tools take a look at Karate because it has been designed to:

allow you to specify expected payloads in (simplified) JSON itself

enable you to perform a "deep equals" comparison of two JSON payloads

be flexible so that you do a contains if you only want to check a sub-set of fields

handle dynamic values by letting you mark those fields as to be ignored or use a fuzzy match

even let you handle arrays where the elements are JSON (not just primitives), and ignore the order if needed

Disclaimer: am dev.

Body:
I am trying to compare the rest API response of two environments. I am using rest assured to get the response back. The problem I am facing is that I get a hashmap back which has a couple of hashmaps.

I have tried flattening the map into one map but keep on missing a hierarchy when the response differs slightly

here is a sample of the rest response

{
   programmes:[
      {
         episodenumber:21,
         seasonnumber:5,
         seasontitle:"program Season 5",
         seasonuuid:"7aabb30e-39a1-48bb-8dca-38f732c9c982",
         seriestitle:"programm",
         seriesuuid:"f95caa09-8cd7-4e23-a88a-444f7932714d",
         sy:"blah blah blah. (S5, ep 21)",
         t:"blah blah Fathers",
         trailer:false,
         type:"programme",
         uuid:"69b91264-37c9-4b2f-a515-b45805a58867",
         uuidtype:"programme",
         waystowatch:{
            svod:[
               {
                  ad:false,
                  added:1495800164,
                  at:"DD",
                  availendtime:1497729599,
                  broadcasttime:1495137600,
                  cgid:10053,
                  cgname:"blah",
                  channelname:"blah1 HD",
                  d:2880,
                  downloadlink:"oig://FFC27E94",
                  hardofhearing:false,
                  is3d:false,
                  providerid:"ab_st_hd",
                  providername:"blah HD",
                  s:true,
                  sid:4061,
                  size:2352611,
                  sy:"blah blah. (S5, ep 21)",
                  videotype:"HD"
               }
            }
         ]         ps:255,
         tc:3
      }

I am using the guava diff lib and for that, i need a simple map. I know this might not be the best of doing this comparison but this is for a short duration and this is what I can come up with. My question is how do I either flatten this response to make one map which i can pass to

 MapDifference<String, ?> diff = Maps.difference(test, test2);

or is there a better way to compare two responses in rest assured. I have to get both the response at runtime.


问:
How to get docker 'objects' completion on mintty-bash from git for windows
I have read (and tried) this:
https://docs.docker.com/machine/completion/

But it seems this is not the right way to get it on.

Anybody know how to get docker completion commands in Mintty (from Git for windows) bash command line?

答:
Not sure if this is the best way to do this or if it work properly at all, but it seems to work!
Let me know if you find any strange behavior...

Minimum requirements:

Git for Windows (git bash / mintty terminal)

7-Zip or similar to extract files

Installation:

First of all, you will need the bash-completion package.

I discovered that the package built for cygwin works.

Choose a cygwin mirror: https://cygwin.com/mirrors.html

Navigate to: /cygwin/noarch/release/bash-completion/

Download: bash-completion-2.7-1.tar.xz

Extract it elsewhere

Copy the etc and usr folder to C:\Program Files\Git (see the note below)

Done, now you should have command completion enabled.

Testing:

You can test it by opening a git bash terminal and typing:

curl --ver (hit tab twice)

It will suggests something like this:

```<code>$ curl --ver
--verbose  --version
</code>```

Docker commands:

Now, about that docker commands...

I have found my files here:

docker command:
https://github.com/docker/docker-ce/blob/v17.09.0-ce/components/cli/contrib/completion/bash/docker

docker-compose command:
https://github.com/docker/compose/blob/1.16.1/contrib/completion/bash/docker-compose

docker-machine command:
https://github.com/docker/machine/blob/v0.12.2/contrib/completion/bash/docker-machine.bash

Just download and copy them to:
C:\Program Files\Git\usr\share\bash-completion\completions\

Make sure they are correctly named (remove the filename extension if any).

It should be named like this:

docker

docker-compose

docker-machine

No extra .txt or whatever...

Some notes:

I'm not sure if the package bash-completion-2.7.1 is the best version to work with git bash, I just got the latest one. (You can compare them and find it out)

You don't need to copy all the files from /usr/share/bash-completion/completions/, just the ones you want. (I didn't copy any of them).

It's a good idea to run a docker version, docker-compose version, docker-machine version and check the versions you are running, then download the correct files from the repository. (Choose the correct release tag for you).

Body:
Not sure if this is the best way to do this or if it work properly at all, but it seems to work!
Let me know if you find any strange behavior...

Minimum requirements:

Git for Windows (git bash / mintty terminal)

7-Zip or similar to extract files

Installation:

First of all, you will need the bash-completion package.

I discovered that the package built for cygwin works.

Choose a cygwin mirror: https://cygwin.com/mirrors.html

Navigate to: /cygwin/noarch/release/bash-completion/

Download: bash-completion-2.7-1.tar.xz

Extract it elsewhere

Copy the etc and usr folder to C:\Program Files\Git (see the note below)

Done, now you should have command completion enabled.

Testing:

You can test it by opening a git bash terminal and typing:

curl --ver (hit tab twice)

It will suggests something like this:

$ curl --ver
--verbose  --version

Docker commands:

Now, about that docker commands...

I have found my files here:

docker command:
https://github.com/docker/docker-ce/blob/v17.09.0-ce/components/cli/contrib/completion/bash/docker

docker-compose command:
https://github.com/docker/compose/blob/1.16.1/contrib/completion/bash/docker-compose

docker-machine command:
https://github.com/docker/machine/blob/v0.12.2/contrib/completion/bash/docker-machine.bash

Just download and copy them to:
C:\Program Files\Git\usr\share\bash-completion\completions\

Make sure they are correctly named (remove the filename extension if any).

It should be named like this:

docker

docker-compose

docker-machine

No extra .txt or whatever...

Some notes:

I'm not sure if the package bash-completion-2.7.1 is the best version to work with git bash, I just got the latest one. (You can compare them and find it out)

You don't need to copy all the files from /usr/share/bash-completion/completions/, just the ones you want. (I didn't copy any of them).

It's a good idea to run a docker version, docker-compose version, docker-machine version and check the versions you are running, then download the correct files from the repository. (Choose the correct release tag for you).


问:
Swift Parse - This query has an outstanding network connection error
I am stuck using parse when making several queries on the same viewcontroller, I know they need to be asynchronous and this is the problem but I am not sure how to go about solving this. I have 3 buttons on this page, one to show the user's pods, one to show his followers, and one who he is following. The code is as follows :

```<code>   // Query for user's pods

    let podQuery = Pod.query()
    podQuery?.whereKey("createdBy", equalTo: currentUser as Any)
    podQuery?.includeKey("audio")
    podQuery?.findObjectsInBackground(block: { (objects, error) in
        if error != nil {
            print("Error")
        } else if let pods = objects {
            self.pods.removeAll()
            for pod in pods {
                if let pod = pod as? Pod {
                    self.pods.insert(pod, at: 0)
                }
            }
            self.tableview.reloadData()
        }
    })

    //Query for the user's subscribers

    let subscribersQuery = Following.query()
    subscribersQuery?.whereKey("following", equalTo: PFUser.current()?.objectId as Any)
    subscribersQuery?.includeKey("following")
    subscribersQuery?.findObjectsInBackground(block: {(objects, error) in
        if let objects = objects {
            for object in objects {
                self.subscribers.insert(object as! PFUser, at: 0)
            }
        }
    })

    //Query for the users that the user is subscribed to

    let subscribedQuery = Following.query()
    subscribedQuery?.whereKey("follower", equalTo: PFUser.current()?.objectId as Any)
    subscribersQuery?.includeKey("follower")
    subscribedQuery?.findObjectsInBackground(block: { (objects, error) in
        if let objects = objects {
            for object in objects {
                self.subscribed.insert(object as! PFUser, at: 0)
            }
        }
    })
</code>```

I am getting the error on the 2nd and 3rd queries.

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'This query has an outstanding network connection. You have to wait until it's done.'

Let me know if the question needs more context/code. Thank you

答:
I think going by the description, you probably meant:

```<code>let subscribersQuery = Followers.query()  //Not Following.query()??
</code>```

In that case, making this change will make the error go away. If you did mean "Following",  then this might be the problem:

I encountered this problem and the reason was that I was using the same query object in consequitive parse accesses. Whether or not this is the case for you depends on how PFObject.query() behaves. I did not find the documentation to be clear enough. If it returns a previously cashed query, then:

```<code>let subscribersQuery = Following.query()
//....
subscribersQuery?.findObjectsInBackground(block: {(objects, error) in{(
//..
let subscribedQuery = Following.query()
//....
subscribedQuery?.findObjectsInBackground(block: {(objects, error) in{(
//..
</code>```

Here, you are performing findObjectsInBackground on the same query which will lead to the error.
Try this where you explicitly create a new query. This has worked for me:

```<code>subscribersQuery = PFQuery(className: Following) //Again, did you mean Followers here?
subscribedQuery = PFQuery(className: Following)
</code>```

Body:
I am stuck using parse when making several queries on the same viewcontroller, I know they need to be asynchronous and this is the problem but I am not sure how to go about solving this. I have 3 buttons on this page, one to show the user's pods, one to show his followers, and one who he is following. The code is as follows :

   // Query for user's pods

    let podQuery = Pod.query()
    podQuery?.whereKey("createdBy", equalTo: currentUser as Any)
    podQuery?.includeKey("audio")
    podQuery?.findObjectsInBackground(block: { (objects, error) in
        if error != nil {
            print("Error")
        } else if let pods = objects {
            self.pods.removeAll()
            for pod in pods {
                if let pod = pod as? Pod {
                    self.pods.insert(pod, at: 0)
                }
            }
            self.tableview.reloadData()
        }
    })

    //Query for the user's subscribers

    let subscribersQuery = Following.query()
    subscribersQuery?.whereKey("following", equalTo: PFUser.current()?.objectId as Any)
    subscribersQuery?.includeKey("following")
    subscribersQuery?.findObjectsInBackground(block: {(objects, error) in
        if let objects = objects {
            for object in objects {
                self.subscribers.insert(object as! PFUser, at: 0)
            }
        }
    })

    //Query for the users that the user is subscribed to

    let subscribedQuery = Following.query()
    subscribedQuery?.whereKey("follower", equalTo: PFUser.current()?.objectId as Any)
    subscribersQuery?.includeKey("follower")
    subscribedQuery?.findObjectsInBackground(block: { (objects, error) in
        if let objects = objects {
            for object in objects {
                self.subscribed.insert(object as! PFUser, at: 0)
            }
        }
    })

I am getting the error on the 2nd and 3rd queries.

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'This query has an outstanding network connection. You have to wait until it's done.'

Let me know if the question needs more context/code. Thank you

Body:
I think going by the description, you probably meant:

let subscribersQuery = Followers.query()  //Not Following.query()??

In that case, making this change will make the error go away. If you did mean "Following",  then this might be the problem:

I encountered this problem and the reason was that I was using the same query object in consequitive parse accesses. Whether or not this is the case for you depends on how PFObject.query() behaves. I did not find the documentation to be clear enough. If it returns a previously cashed query, then:

let subscribersQuery = Following.query()
//....
subscribersQuery?.findObjectsInBackground(block: {(objects, error) in{(
//..
let subscribedQuery = Following.query()
//....
subscribedQuery?.findObjectsInBackground(block: {(objects, error) in{(
//..

Here, you are performing findObjectsInBackground on the same query which will lead to the error.
Try this where you explicitly create a new query. This has worked for me:

subscribersQuery = PFQuery(className: Following) //Again, did you mean Followers here?
subscribedQuery = PFQuery(className: Following)


问:
How to replace one characters with two possible characters in a string
I want to know how to replace a string like "10?01?1" at '?' with 1 or 0. E.g., from string "1?0" -> "110" && "100". How to approach this problem? Recursive? Thanks.

EDIT with OP comment

"1?0?1 ... it should have four different combinations. "11011", "11001", "10011","10001". How to print all four combinations?"

答:
try this code it gives for "1???" all combinations which are: 1000, 1001, 1010, 1011, 1100, 1101, 1110, 1111
as possible by 2^3= 8 combinations. </p>

```<code>import java.util.*;

import java.lang.*;

import java.io.*;

 class testRecursion {

    public static void main(String[] args) {
        combinations("1???");
    }

    public static void combinations(String s) {
        if(s.contains("?")){
            combinations(replace(s, '0'));
            combinations(replace(s, '1'));
        } else {
            System.out.println(s);
        }
    }

    public static String replace(String s, char replacement){
        char[] charSeq = s.toCharArray();
        int i;
        for(i=0; charSeq[i]!='?'; i++);
        charSeq[i]=replacement;
        return new String(charSeq);
    }
}
</code>```

Body:
try this code it gives for "1???" all combinations which are: 1000, 1001, 1010, 1011, 1100, 1101, 1110, 1111
as possible by 2^3= 8 combinations.

import java.util.*;

import java.lang.*;

import java.io.*;

 class testRecursion {

    public static void main(String[] args) {
        combinations("1???");
    }

    public static void combinations(String s) {
        if(s.contains("?")){
            combinations(replace(s, '0'));
            combinations(replace(s, '1'));
        } else {
            System.out.println(s);
        }
    }

    public static String replace(String s, char replacement){
        char[] charSeq = s.toCharArray();
        int i;
        for(i=0; charSeq[i]!='?'; i++);
        charSeq[i]=replacement;
        return new String(charSeq);
    }
}


问:
How can I delete a file or directory in API Level >= 23?
I have an android app that delete a specific files or directories .this app work on android with API less than 23 but doesn't work on API 23 and above .
i wrote manifest permissions and wrote run time permission for read and write data on external sdcard .but didn't work .i wrote run time permissions with dexter library but again didn't work.
at last i delete part of code that delete files and directories on external sdcard and only want to delete directories on internal sd card but again have same result (again API>23 not work )

```<code>public double deleteFileOrDirectory(String fileOrDirectory) {
    File FOD = new File(fileOrDirectory);
    if (FOD.exists() && FOD.isFile() && FOD.canWrite()) {
        FOD.delete();
    } else if (FOD.exists() && FOD.isDirectory() && FOD.canRead()) {
        String fileList[] = FOD.list();
        if (fileList != null && fileList.length == 0) {
            FOD.delete();
            // return 0;
        } else if (fileList != null && fileList.length > 0) {
            for (int i = 0; i < fileList.length; i++) {
                File temp_f = new File(FOD.getAbsolutePath() + "/" + fileList[i]);
                if (temp_f.isDirectory())
                    deleteFileOrDirectory(temp_f.getAbsolutePath());
                else if (temp_f.isFile())
                    temp_f.delete();
            }

        }
        if (FOD.exists())
            if (FOD.delete()) {
                //return 0;
            }
    }
    // return -1;
    double[] v = volumCalcultor();
    return v[2];

}
</code>```

i want to delete file for all android device -At least I want to delete the directories from the internal memory with any specific permission.

答: API23+ considers the External SD card to be a 'semi-permanent' device and as such will not grant write access anything outside of the App private directory</p>

Body:
I have an android app that delete a specific files or directories .this app work on android with API less than 23 but doesn't work on API 23 and above .
i wrote manifest permissions and wrote run time permission for read and write data on external sdcard .but didn't work .i wrote run time permissions with dexter library but again didn't work.
at last i delete part of code that delete files and directories on external sdcard and only want to delete directories on internal sd card but again have same result (again API>23 not work )

public double deleteFileOrDirectory(String fileOrDirectory) {
    File FOD = new File(fileOrDirectory);
    if (FOD.exists() && FOD.isFile() && FOD.canWrite()) {
        FOD.delete();
    } else if (FOD.exists() && FOD.isDirectory() && FOD.canRead()) {
        String fileList[] = FOD.list();
        if (fileList != null && fileList.length == 0) {
            FOD.delete();
            // return 0;
        } else if (fileList != null && fileList.length > 0) {
            for (int i = 0; i < fileList.length; i++) {
                File temp_f = new File(FOD.getAbsolutePath() + "/" + fileList[i]);
                if (temp_f.isDirectory())
                    deleteFileOrDirectory(temp_f.getAbsolutePath());
                else if (temp_f.isFile())
                    temp_f.delete();
            }

        }
        if (FOD.exists())
            if (FOD.delete()) {
                //return 0;
            }
    }
    // return -1;
    double[] v = volumCalcultor();
    return v[2];

}

i want to delete file for all android device -At least I want to delete the directories from the internal memory with any specific permission.


问:
How do I install WindowsAzure.Storage in Visual Studio 2013?
Note: this answer didn't help me because I don't have the same dll: System.Collections.Immutable 1.1.37

I'm using Visual Studio 2013 and .net 4.5 and following this tutorial: Get started with Azure Blob storage using .NET
I am trying to install WindowsAzure.Storage but get this error:

Attempting to resolve dependency 'Microsoft.Data.OData (≥ 5.8.2)'.
  Attempting to resolve dependency 'System.Spatial (= 5.8.2)'.
  Attempting to resolve dependency 'Microsoft.Data.Edm (= 5.8.2)'.
  Attempting to resolve dependency 'Newtonsoft.Json (≥ 6.0.8)'.
  Attempting to resolve dependency 'Microsoft.Data.Services.Client (≥ 5.8.2)'.
  Attempting to resolve dependency 'System.Net.Requests (≥ 4.0.11)'.
  Attempting to resolve dependency 'System.ComponentModel.EventBasedAsync (≥ > 4.0.11)'.
  Attempting to resolve dependency 'System.Dynamic.Runtime (≥ 4.0.0)'.
  Attempting to resolve dependency 'System.Linq.Queryable (≥ 4.0.0)'.
  The 'System.Linq.Queryable 4.0.0' package requires NuGet client version '3.0' or above, but the current NuGet version is '2.12.0.817'.

when I upgrade Nuget per the red error in the image, it takes me to Extensions and Updates asking to update this:

I don't know the relation between what I am looking for and this, but I went ahead and followed that update anyway, but get the error:

Where should I proceed from here!?

based on comment form Simsons, I already checked that my processor supports Virtualization:

答:
Open your Visual Studio 2013. Go to Tools > NuGet Package Manager > Package Manager Console

In the packet manager console type:

```<code>Install-Package NuGet.Client -Version 3.2.0
</code>```

I tried this using NuGet Client version 3.2.0. The current latest version is 4.3 (beta) or 4.2. So I'm not sure if it will work for versions 4.2 and 4.3, but it surely works for NuGet 3.2.0. NuGet >3 was all I needed for SendGrid and other packages.

Body:
Open your Visual Studio 2013. Go to Tools > NuGet Package Manager > Package Manager Console

In the packet manager console type:

Install-Package NuGet.Client -Version 3.2.0

I tried this using NuGet Client version 3.2.0. The current latest version is 4.3 (beta) or 4.2. So I'm not sure if it will work for versions 4.2 and 4.3, but it surely works for NuGet 3.2.0. NuGet >3 was all I needed for SendGrid and other packages.


问:
How to display sum of columns (where all values are decimal values) in DataTables in PHP-jQuery?
In my PHP-jQuery DataTable, all values of the column in all rows are decimal values and also contains a "₹" sign before the decimal value like below:

```<code>+---------+
| Column  |
+---------+
| ₹ 1.20  |
+---------+
| ₹ 3.42  |
+---------+
| ₹ 9.07  |
+---------+
</code>```

I want to display sum of the decimal values of all the columns on the table footer like below:

```<code>+----------------+
|     Column     |
+----------------+
|     ₹ 1.20     |
+----------------+
|     ₹ 3.42     |
+----------------+
|     ₹ 9.07     |
+----------------+
| ₹ 13.69 (Total)|
+----------------+
</code>```

I've tried to output like above using the "footerCallback" function, but failed:

```<code>"footerCallback": function ( row, data, start, end, display ) {
    var api = this.api(), data;

    // Remove the formatting to get integer data for summation
    var intVal = function ( i ) {
        return typeof i === 'string' ?
        i.replace(/[\$,₹]/g, '')*1 :
        typeof i === 'string' ?
        i : 0.00;
    };

    // Total over this page
    pageTotal = api
    .column( 4, { page: 'current'} )
    .data()
    .reduce( function (a, b) {
         return intVal(a) + intVal(b);
     }, 0 );

     // Update footer
     $( api.column( 4 ).footer() ).html(
         '₹ '+pageTotal +' (Total)'
     );
 },
</code>```

It results like below on the table footer:

```<code>₹ NaN (Total)
</code>```

Please help!

答:
Your intVal function checks if the value is a string and if it is converts it to a number, but if it's already a number then it returns 0.

Yu aren't working with integers though, decimal numbers are floats so this isn't suitable for currency addition as it will only ever return whole numbers.

Delete your whole intVal function and replace with something like this, all it does is strip anything which isn't a number or a decimal point:

```<code>var floatVal = function ( i ) {
    return i.replace( /[^\d\.]/g, '');
};
</code>```

Then change this line of your pageTotal function return intVal(a) + intVal(b);
to this, which will add your numbers together as floating numbers instead of appending them to one another:

```<code>return parseFloat(floatVal(a)) + parseFloat(floatVal(b));
</code>```

Body:
In my PHP-jQuery DataTable, all values of the column in all rows are decimal values and also contains a "₹" sign before the decimal value like below:

+---------+
| Column  |
+---------+
| ₹ 1.20  |
+---------+
| ₹ 3.42  |
+---------+
| ₹ 9.07  |
+---------+

I want to display sum of the decimal values of all the columns on the table footer like below:

+----------------+
|     Column     |
+----------------+
|     ₹ 1.20     |
+----------------+
|     ₹ 3.42     |
+----------------+
|     ₹ 9.07     |
+----------------+
| ₹ 13.69 (Total)|
+----------------+

I've tried to output like above using the "footerCallback" function, but failed:

"footerCallback": function ( row, data, start, end, display ) {
    var api = this.api(), data;

    // Remove the formatting to get integer data for summation
    var intVal = function ( i ) {
        return typeof i === 'string' ?
        i.replace(/[\$,₹]/g, '')*1 :
        typeof i === 'string' ?
        i : 0.00;
    };

    // Total over this page
    pageTotal = api
    .column( 4, { page: 'current'} )
    .data()
    .reduce( function (a, b) {
         return intVal(a) + intVal(b);
     }, 0 );

     // Update footer
     $( api.column( 4 ).footer() ).html(
         '₹ '+pageTotal +' (Total)'
     );
 },

It results like below on the table footer:

₹ NaN (Total)

Please help!

Body:
Your intVal function checks if the value is a string and if it is converts it to a number, but if it's already a number then it returns 0.

Yu aren't working with integers though, decimal numbers are floats so this isn't suitable for currency addition as it will only ever return whole numbers.

Delete your whole intVal function and replace with something like this, all it does is strip anything which isn't a number or a decimal point:

var floatVal = function ( i ) {
    return i.replace( /[^\d\.]/g, '');
};

Then change this line of your pageTotal function return intVal(a) + intVal(b);
to this, which will add your numbers together as floating numbers instead of appending them to one another:

return parseFloat(floatVal(a)) + parseFloat(floatVal(b));


问:
Java word appearence in a text file
For the given text file (text.txt) compute how many times each word appears in the file. The output of the program should be another text file containing on each line a word and then the number of times it appears in the original file. After you finish change the program so that the words in the output file are sorted alphabetically. Do not use maps, use only basic arrays. The thing is displaying me only one word that I enter from keyboard in that text file, but how can I display for all words, not only for one? Thanks</p>

```<code>package worddata;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

 class WordData {
     public FileReader fr = null;
     public BufferedReader br =null;

     public String [] stringArray;
     public int counLine = 0;
     public int arrayLength ;
      public String s="";
    public String stringLine="";
     public String filename ="";
     public String wordname ="";

public WordData(){

    try{
        Scanner scan = new Scanner(System.in);
        System.out.println("Please enter the filename: ");
        filename = scan.nextLine();
        Scanner scan2 = new Scanner(System.in);
        System.out.println("Please enter a word: ");
        wordname = scan.nextLine();
        fr = new FileReader(filename);
        br = new BufferedReader(fr);
        while((s = br.readLine()) != null){
            stringLine = stringLine + s;
            //System.out.println(s);
            stringLine = stringLine + " ";
            counLine ++;
        }

        stringArray = stringLine.split(" ");
        arrayLength = stringArray.length;
        for (int i = 0; i < arrayLength; i++) {
            int c = 1 ;
            for (int j = i+1; j < arrayLength; j++) {
                if(stringArray[i].equalsIgnoreCase(stringArray[j])){
                    c++;
                    for (int j2 = j; j2 < arrayLength; j2++) {
                        stringArray[j2] = stringArray[j2+1];
                        arrayLength = arrayLength - 1;
                    }

                       if (stringArray[i].equalsIgnoreCase(wordname)){
           System.out.println("The word "+wordname+" is present "+c+" times in the specified file.");
           }
                }
        }
    }
        System.out.println("Total number of lines: "+counLine);
        fr.close();
        br.close();
    }catch (Exception e) {
        e.printStackTrace();
    }
}
public static void main(String[] args) throws IOException {
    Scanner scan = new Scanner(System.in);
    OutputStream out = new FileOutputStream("output.txt");
    System.out.println("Please enter the filename: ");
    String filename = scan.nextLine();
    System.out.println("Please enter a word: ");
    String wordname = scan.nextLine();
    int count = 0;
    try (LineNumberReader r = new LineNumberReader(new FileReader(filename))) {
        String line;
        while ((line = r.readLine()) != null) {
            for (String element : line.split(" ")) {
                if (element.equalsIgnoreCase(wordname)) {
                    count++;
                    System.out.println("Word found at line " + r.getLineNumber());
                }
            }
        }
    }
                        FileReader fileReader = new FileReader(filename);
            BufferedReader bufferedReader = new BufferedReader(fileReader);
            StringBuffer stringBuffer = new StringBuffer();
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                stringBuffer.append(line);
                stringBuffer.append("\n");
            }
            fileReader.close();
    System.out.println("The word " + stringBuffer.toString() + " appears " + count + " times.");
    int i;
    List<String> ls = new ArrayList<String>();
    for (i = 1; i <= 1000; i++) {
        String str = null;
        str = +i + ":-  The word "+wordname+" was found " + count +"  times";
        ls.add(str);
    }
    String listString = "";
    for (String s : ls) {
        listString += s + "\n";
    }
    FileWriter writer = null;
    try {
        writer = new FileWriter("final.txt");
        writer.write(listString);
        writer.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
}
</code>```

答:
The code below does something like you want I think.

it does the following:

read the contents from the input.txt file

Remove punctuation marks from the text

make it one string of words by removing line breaks

Split the text up in words by using space as delimiter

The lambda maps all the words to lowercase then removes whitespace and all empty entries then it...

loops over all words and computes there word count in het HashMap

then we sort the Map based on the count value in reverse order to get the highest counted words first

then write them to a StringBuilder to format it like this "word : count\n" and then write it to a text file

```<code>final String content = new String(Files.readAllBytes(Paths.get("<PATH TO YOUR PLACE>/input.txt")));
final List<String> words = Arrays.asList(content.replaceAll("[\\p{InCombiningDiacriticalMarks}]", "").replace("\n", " ").split(" "));

final Map<String, Integer> wordlist = new HashMap<>();
words.stream()
        .map(String::toLowerCase)
        .map(String::trim)
        .filter(s -> !s.isEmpty())
        .forEach(s -> {
            wordlist.computeIfPresent(s, (s1, integer) -> ++integer);
            wordlist.putIfAbsent(s, 1);
        });

final StringBuilder sb = new StringBuilder();
wordlist.entrySet()
        .stream()
        .sorted(Map.Entry.comparingByValue(Collections.reverseOrder()))
        .collect(Collectors.toMap(
                Map.Entry::getKey,
                Map.Entry::getValue,
                (e1, e2) -> e1,
                LinkedHashMap::new
        )).forEach((s, integer) -> sb.append(s).append(" : ").append(integer).append("\n"));

Files.write(Paths.get("<PATH TO YOUR PLACE>/output.txt"), sb.toString().getBytes());
</code>```

Hope it helps :-)

Note: the <PATH TO YOUR PLACE> needs to be replaced by the fully qualified path to your text file with words.

Title: Java word appearence in a text file

Body:
For the given text file (text.txt) compute how many times each word appears in the file. The output of the program should be another text file containing on each line a word and then the number of times it appears in the original file. After you finish change the program so that the words in the output file are sorted alphabetically. Do not use maps, use only basic arrays. The thing is displaying me only one word that I enter from keyboard in that text file, but how can I display for all words, not only for one? Thanks

package worddata;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

 class WordData {
     public FileReader fr = null;
     public BufferedReader br =null;

     public String [] stringArray;
     public int counLine = 0;
     public int arrayLength ;
      public String s="";
    public String stringLine="";
     public String filename ="";
     public String wordname ="";

public WordData(){

    try{
        Scanner scan = new Scanner(System.in);
        System.out.println("Please enter the filename: ");
        filename = scan.nextLine();
        Scanner scan2 = new Scanner(System.in);
        System.out.println("Please enter a word: ");
        wordname = scan.nextLine();
        fr = new FileReader(filename);
        br = new BufferedReader(fr);
        while((s = br.readLine()) != null){
            stringLine = stringLine + s;
            //System.out.println(s);
            stringLine = stringLine + " ";
            counLine ++;
        }

        stringArray = stringLine.split(" ");
        arrayLength = stringArray.length;
        for (int i = 0; i < arrayLength; i++) {
            int c = 1 ;
            for (int j = i+1; j < arrayLength; j++) {
                if(stringArray[i].equalsIgnoreCase(stringArray[j])){
                    c++;
                    for (int j2 = j; j2 < arrayLength; j2++) {
                        stringArray[j2] = stringArray[j2+1];
                        arrayLength = arrayLength - 1;
                    }

                       if (stringArray[i].equalsIgnoreCase(wordname)){
           System.out.println("The word "+wordname+" is present "+c+" times in the specified file.");
           }
                }
        }
    }
        System.out.println("Total number of lines: "+counLine);
        fr.close();
        br.close();
    }catch (Exception e) {
        e.printStackTrace();
    }
}
public static void main(String[] args) throws IOException {
    Scanner scan = new Scanner(System.in);
    OutputStream out = new FileOutputStream("output.txt");
    System.out.println("Please enter the filename: ");
    String filename = scan.nextLine();
    System.out.println("Please enter a word: ");
    String wordname = scan.nextLine();
    int count = 0;
    try (LineNumberReader r = new LineNumberReader(new FileReader(filename))) {
        String line;
        while ((line = r.readLine()) != null) {
            for (String element : line.split(" ")) {
                if (element.equalsIgnoreCase(wordname)) {
                    count++;
                    System.out.println("Word found at line " + r.getLineNumber());
                }
            }
        }
    }
                        FileReader fileReader = new FileReader(filename);
            BufferedReader bufferedReader = new BufferedReader(fileReader);
            StringBuffer stringBuffer = new StringBuffer();
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                stringBuffer.append(line);
                stringBuffer.append("\n");
            }
            fileReader.close();
    System.out.println("The word " + stringBuffer.toString() + " appears " + count + " times.");
    int i;
    List<String> ls = new ArrayList<String>();
    for (i = 1; i <= 1000; i++) {
        String str = null;
        str = +i + ":-  The word "+wordname+" was found " + count +"  times";
        ls.add(str);
    }
    String listString = "";
    for (String s : ls) {
        listString += s + "\n";
    }
    FileWriter writer = null;
    try {
        writer = new FileWriter("final.txt");
        writer.write(listString);
        writer.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
}

Body:
The code below does something like you want I think.

it does the following:

read the contents from the input.txt file

Remove punctuation marks from the text

make it one string of words by removing line breaks

Split the text up in words by using space as delimiter

The lambda maps all the words to lowercase then removes whitespace and all empty entries then it...

loops over all words and computes there word count in het HashMap

then we sort the Map based on the count value in reverse order to get the highest counted words first

then write them to a StringBuilder to format it like this "word : count\n" and then write it to a text file

final String content = new String(Files.readAllBytes(Paths.get("<PATH TO YOUR PLACE>/input.txt")));
final List<String> words = Arrays.asList(content.replaceAll("[\\p{InCombiningDiacriticalMarks}]", "").replace("\n", " ").split(" "));

final Map<String, Integer> wordlist = new HashMap<>();
words.stream()
        .map(String::toLowerCase)
        .map(String::trim)
        .filter(s -> !s.isEmpty())
        .forEach(s -> {
            wordlist.computeIfPresent(s, (s1, integer) -> ++integer);
            wordlist.putIfAbsent(s, 1);
        });

final StringBuilder sb = new StringBuilder();
wordlist.entrySet()
        .stream()
        .sorted(Map.Entry.comparingByValue(Collections.reverseOrder()))
        .collect(Collectors.toMap(
                Map.Entry::getKey,
                Map.Entry::getValue,
                (e1, e2) -> e1,
                LinkedHashMap::new
        )).forEach((s, integer) -> sb.append(s).append(" : ").append(integer).append("\n"));

Files.write(Paths.get("<PATH TO YOUR PLACE>/output.txt"), sb.toString().getBytes());

Hope it helps :-)

Note: the <PATH TO YOUR PLACE> needs to be replaced by the fully qualified path to your text file with words.


问:
C# check if variable only contains given string
I am trying to use a variable called game.PlayMode which contains a semicolon-separated list of Play Modes input by the user. The variable can literally contain anything.

An example value:

```<code>Single Player; 2-Player; 3-Player; Co-Op; Versus; Alternate
</code>```

I want to check if game.PlayMode ONLY contains Single Player but I am not sure how to do that.

So far:

```<code>if (game.Playmode.Contains("Single Player"))
        {
           Players = "1";
        }
</code>```

But I know this will also return true with the example value above. How can I make sure my code returns true only if the string is an exact match?

答:
In C#, you can simply use the == operator:

```<code>if (game.Playmode == "Single Player")
{
   Players = "1";
}
</code>```

It might be a better idea to remove any ; and any white spaces and only then do the comparison:

```<code>if (Playmode.Replace(";","").Trim()=="Single Player")
{
    Players = "1";
}
</code>```

Body:
I am trying to use a variable called game.PlayMode which contains a semicolon-separated list of Play Modes input by the user. The variable can literally contain anything.

An example value:

Single Player; 2-Player; 3-Player; Co-Op; Versus; Alternate

I want to check if game.PlayMode ONLY contains Single Player but I am not sure how to do that.

So far:

if (game.Playmode.Contains("Single Player"))
        {
           Players = "1";
        }

But I know this will also return true with the example value above. How can I make sure my code returns true only if the string is an exact match?

Body:
In C#, you can simply use the == operator:

if (game.Playmode == "Single Player")
{
   Players = "1";
}

It might be a better idea to remove any ; and any white spaces and only then do the comparison:

if (Playmode.Replace(";","").Trim()=="Single Player")
{
    Players = "1";
}


问:
Implementing callback function within a class in C++
I would like to implement a workaround to use a non-static class as a call-back function. I am working with Eclipse Paho MQTT code. The following type is implemented and used as callback:

```<code>typedef void MQTTAsync_onSuccess(void* context, MQTTAsync_successData* response);

MQTTAsync_onSuccess* onSuccess;

onSuccess = myStaticCallback;

void myStaticCallback (void* context, MQTTAsync_successData* response)
{
   //...callback actions...
}
</code>```

I want to wrap this C API (without modifying the existing MQTT C API) and implement non-static / non-centralized callback function that belongs to an object/class.

```<code>typedef void MQTTAsync_onSuccess(void* context, MQTTAsync_successData* response);

class myMQTTClass
{
   private:
      void myCallback (void* context, MQTTAsync_successData* response);
      MQTTAsync_onSuccess* onSuccess;

   public:
      void foo (void)
      {
          this->onSuccess = this->myCallback;
      }
}
</code>```

As you might guess, the code above causes the error:
cannot convert myCallback from type 'void (myMQTTClass::) (void*, MQTTAsync_successData*)' to type 'void (*)(void*, MQTTAsync_successData*)'.

Any guidance as to how to address this issue or any workaround is greately appreciated. I would be willing to provide any possible missing information. Thanks in advance.

EDIT: Actual code with some omissions

```<code>   namespace rover
    {
       typedef struct
       {
        char * clientID;
        char * topic;
        char * payload;
        int         qos;        // 1
        long int    timeout;    // Such as 10000L usec
       } RoverMQTT_Configure_t;

       class RoverPahoMQTT
       {
           public:
              RoverPahoMQTT (char * host_name, int port, RoverMQTT_Configure_t MQTT_Configure);

           private:

             /**
             * @brief Host name used for connecting to the Eclipse Paho MQTT server
             */
            char * HOST_NAME;

            /**
             * @brief Port used for connecting to the Eclipse Paho MQTT server
             */
            int PORT;

            RoverMQTT_Configure_t rover_MQTT_configure;

            /* Internal attributes */
            MQTTAsync client;

            /**
             * @brief Connect options
             */
            MQTTAsync_connectOptions conn_opts;

            /**
             * @brief Disconnect options
             */
            MQTTAsync_disconnectOptions disc_opts;

             //...
             static void onPublisherConnect (void* context, MQTTAsync_successData* response);
             void onPublisherConnect_ (MQTTAsync_successData* response);

           //...

       }
    }

    int rover::RoverPahoMQTT::publish (void)
    {
        this->flushFlags ();

        this->conn_opts = MQTTAsync_connectOptions_initializer;
        this->client = new MQTTAsync;
        int rc;

        char my_addr[20];
        this->constructAddress (my_addr);
        printf ("address: %s", my_addr);
        MQTTAsync_create (  &(this->client),
                            my_addr,
                            this->rover_MQTT_configure.clientID,
                            MQTTCLIENT_PERSISTENCE_NONE,
                            NULL);

        MQTTAsync_setCallbacks(this->client, NULL, onConnectionLost, NULL, NULL);

        conn_opts.keepAliveInterval = 20;
        conn_opts.cleansession = 1;
        conn_opts.onSuccess = rover::RoverPahoMQTT::onPublisherConnect;
        conn_opts.onFailure = onConnectFailure;
        conn_opts.context = this->client;

        if ((rc = MQTTAsync_connect(this->client, &(this->conn_opts))) != MQTTASYNC_SUCCESS)
        {
            printf("Failed to start connect, return code %d\n", rc);
            return rc;
        }

        /*printf("Waiting for publication of %s\n"
             "on topic %s for client with ClientID: %s\n",
             PAYLOAD, TOPIC, CLIENTID);*/
        while (!mqtt_finished)
            usleep(this->rover_MQTT_configure.timeout);

        MQTTAsync_destroy(&client);
        return rc;
    }

    void rover::RoverPahoMQTT::onPublisherConnect_(MQTTAsync_successData* response)
    {
        MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer;
        MQTTAsync_message pubmsg = MQTTAsync_message_initializer;
        int rc;

        printf("Successful connection\n");

        opts.onSuccess = onPublisherSend;
        opts.context = client;

        pubmsg.payload = &default_MQTT_configure.payload;
        pubmsg.payloadlen = strlen(default_MQTT_configure.payload);
        pubmsg.qos = default_MQTT_configure.qos;
        pubmsg.retained = 0;
        deliveredtoken = 0;

        if ((rc = MQTTAsync_sendMessage(client, default_MQTT_configure.topic, &pubmsg, &opts)) != MQTTASYNC_SUCCESS)
        {
            printf("Failed to start sendMessage, return code %d\n", rc);
            exit(EXIT_FAILURE);
        }
    }

    void rover::RoverPahoMQTT::onPublisherConnect (void* context, MQTTAsync_successData* response)
    {
        rover::RoverPahoMQTT* m = (rover::RoverPahoMQTT*) context;
        m->onPublisherConnect_(response);
        //((rover::RoverPahoMQTT*)context)->onPublisherConnect_(response);
        // ^^^HERE IS THE SEGMENTATION FAULT

    }
</code>```

答:
As clearly stated here, the callback has to be

registered with the client library by passing it as an argument in
  MQTTAsync_responseOptions

and the context argument is a

pointer to the context value originally passed to
  MQTTAsync_responseOptions, which contains any application-specific
  context.

I suggest a common interface for your classes, which provides a static method that matches the callback prototype:

```<code>class myMQTTClass
{
public:
  static void callback(void* context, MQTTAsync_successData* response)
  {
    myMQTTClass * m = (myMQTTClass*)context;
    m->myCallback(response);
  }
protected:
  virtual void myCallback(MQTTAsync_successData* response) = 0;
};
</code>```

You can now implement different behaviours in subclasses:

```<code>class myMQTTClassImpl : public myMQTTClass
{
protected:
  void myCallback(MQTTAsync_successData *response)
  {
    std::cout << "success!!!" << std::endl;
  }
};
</code>```

Let's see how to use it:

```<code>int main()
{
  myMQTTClass * m = new myMQTTClassImpl();

  MQTTAsync_responseOptions options;
  options.onSuccess = myMQTTClass::callback;
  options.context = m;
}
</code>```

Edit (refers to actual code posted):

In your publish method, this is right:

```<code>conn_opts.onSuccess = rover::RoverPahoMQTT::onPublisherConnect;
</code>```

this is wrong:

```<code>conn_opts.context = this->client;
</code>```

it should be:

```<code>conn_opts.context = this;
</code>```

Body:
I would like to implement a workaround to use a non-static class as a call-back function. I am working with Eclipse Paho MQTT code. The following type is implemented and used as callback:

typedef void MQTTAsync_onSuccess(void* context, MQTTAsync_successData* response);

MQTTAsync_onSuccess* onSuccess;

onSuccess = myStaticCallback;

void myStaticCallback (void* context, MQTTAsync_successData* response)
{
   //...callback actions...
}

I want to wrap this C API (without modifying the existing MQTT C API) and implement non-static / non-centralized callback function that belongs to an object/class.

typedef void MQTTAsync_onSuccess(void* context, MQTTAsync_successData* response);

class myMQTTClass
{
   private:
      void myCallback (void* context, MQTTAsync_successData* response);
      MQTTAsync_onSuccess* onSuccess;

   public:
      void foo (void)
      {
          this->onSuccess = this->myCallback;
      }
}

As you might guess, the code above causes the error:
cannot convert myCallback from type 'void (myMQTTClass::) (void*, MQTTAsync_successData*)' to type 'void (*)(void*, MQTTAsync_successData*)'.

Any guidance as to how to address this issue or any workaround is greately appreciated. I would be willing to provide any possible missing information. Thanks in advance.

EDIT: Actual code with some omissions

   namespace rover
    {
       typedef struct
       {
        char * clientID;
        char * topic;
        char * payload;
        int         qos;        // 1
        long int    timeout;    // Such as 10000L usec
       } RoverMQTT_Configure_t;

       class RoverPahoMQTT
       {
           public:
              RoverPahoMQTT (char * host_name, int port, RoverMQTT_Configure_t MQTT_Configure);

           private:

             /**
             * @brief Host name used for connecting to the Eclipse Paho MQTT server
             */
            char * HOST_NAME;

            /**
             * @brief Port used for connecting to the Eclipse Paho MQTT server
             */
            int PORT;

            RoverMQTT_Configure_t rover_MQTT_configure;

            /* Internal attributes */
            MQTTAsync client;

            /**
             * @brief Connect options
             */
            MQTTAsync_connectOptions conn_opts;

            /**
             * @brief Disconnect options
             */
            MQTTAsync_disconnectOptions disc_opts;

             //...
             static void onPublisherConnect (void* context, MQTTAsync_successData* response);
             void onPublisherConnect_ (MQTTAsync_successData* response);

           //...

       }
    }

    int rover::RoverPahoMQTT::publish (void)
    {
        this->flushFlags ();

        this->conn_opts = MQTTAsync_connectOptions_initializer;
        this->client = new MQTTAsync;
        int rc;

        char my_addr[20];
        this->constructAddress (my_addr);
        printf ("address: %s", my_addr);
        MQTTAsync_create (  &(this->client),
                            my_addr,
                            this->rover_MQTT_configure.clientID,
                            MQTTCLIENT_PERSISTENCE_NONE,
                            NULL);

        MQTTAsync_setCallbacks(this->client, NULL, onConnectionLost, NULL, NULL);

        conn_opts.keepAliveInterval = 20;
        conn_opts.cleansession = 1;
        conn_opts.onSuccess = rover::RoverPahoMQTT::onPublisherConnect;
        conn_opts.onFailure = onConnectFailure;
        conn_opts.context = this->client;

        if ((rc = MQTTAsync_connect(this->client, &(this->conn_opts))) != MQTTASYNC_SUCCESS)
        {
            printf("Failed to start connect, return code %d\n", rc);
            return rc;
        }

        /*printf("Waiting for publication of %s\n"
             "on topic %s for client with ClientID: %s\n",
             PAYLOAD, TOPIC, CLIENTID);*/
        while (!mqtt_finished)
            usleep(this->rover_MQTT_configure.timeout);

        MQTTAsync_destroy(&client);
        return rc;
    }

    void rover::RoverPahoMQTT::onPublisherConnect_(MQTTAsync_successData* response)
    {
        MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer;
        MQTTAsync_message pubmsg = MQTTAsync_message_initializer;
        int rc;

        printf("Successful connection\n");

        opts.onSuccess = onPublisherSend;
        opts.context = client;

        pubmsg.payload = &default_MQTT_configure.payload;
        pubmsg.payloadlen = strlen(default_MQTT_configure.payload);
        pubmsg.qos = default_MQTT_configure.qos;
        pubmsg.retained = 0;
        deliveredtoken = 0;

        if ((rc = MQTTAsync_sendMessage(client, default_MQTT_configure.topic, &pubmsg, &opts)) != MQTTASYNC_SUCCESS)
        {
            printf("Failed to start sendMessage, return code %d\n", rc);
            exit(EXIT_FAILURE);
        }
    }

    void rover::RoverPahoMQTT::onPublisherConnect (void* context, MQTTAsync_successData* response)
    {
        rover::RoverPahoMQTT* m = (rover::RoverPahoMQTT*) context;
        m->onPublisherConnect_(response);
        //((rover::RoverPahoMQTT*)context)->onPublisherConnect_(response);
        // ^^^HERE IS THE SEGMENTATION FAULT

    }

Body:
As clearly stated here, the callback has to be

registered with the client library by passing it as an argument in
  MQTTAsync_responseOptions

and the context argument is a

pointer to the context value originally passed to
  MQTTAsync_responseOptions, which contains any application-specific
  context.

I suggest a common interface for your classes, which provides a static method that matches the callback prototype:

class myMQTTClass
{
public:
  static void callback(void* context, MQTTAsync_successData* response)
  {
    myMQTTClass * m = (myMQTTClass*)context;
    m->myCallback(response);
  }
protected:
  virtual void myCallback(MQTTAsync_successData* response) = 0;
};

You can now implement different behaviours in subclasses:

class myMQTTClassImpl : public myMQTTClass
{
protected:
  void myCallback(MQTTAsync_successData *response)
  {
    std::cout << "success!!!" << std::endl;
  }
};

Let's see how to use it:

int main()
{
  myMQTTClass * m = new myMQTTClassImpl();

  MQTTAsync_responseOptions options;
  options.onSuccess = myMQTTClass::callback;
  options.context = m;
}

Edit (refers to actual code posted):

In your publish method, this is right:

conn_opts.onSuccess = rover::RoverPahoMQTT::onPublisherConnect;

this is wrong:

conn_opts.context = this->client;

it should be:

conn_opts.context = this;


问:
RandomStringGenerator to generate alphanumeric strings
Can I use Apache's common-text RandomStringGenerator to generate random alphanumeric strings (numbers and lowercase/uppercase letters)?

答:
With Java 8 lambda expressions: </p>

```<code>    private final RandomStringGenerator generator = new RandomStringGenerator.Builder()
            .usingRandom(max -> RandomUtils.getRandomAlphanumericChar()).build();

....................

public class RandomUtils {

    private final static char[] ALPHA_NUMERIC_CHARS = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
            'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
            'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4',
            '5', '6', '7', '8', '9'};

    private final static Random random = new SecureRandom();

    public static char getRandomAlphanumericChar() {
        return ALPHA_NUMERIC_CHARS[random.nextInt(ALPHA_NUMERIC_CHARS.length)];
    }
}
</code>```

Body:
With Java 8 lambda expressions:

    private final RandomStringGenerator generator = new RandomStringGenerator.Builder()
            .usingRandom(max -> RandomUtils.getRandomAlphanumericChar()).build();

....................

public class RandomUtils {

    private final static char[] ALPHA_NUMERIC_CHARS = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
            'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
            'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4',
            '5', '6', '7', '8', '9'};

    private final static Random random = new SecureRandom();

    public static char getRandomAlphanumericChar() {
        return ALPHA_NUMERIC_CHARS[random.nextInt(ALPHA_NUMERIC_CHARS.length)];
    }
}


问:
How to calculate cost for selected items on page load - JS & Laravel
I am able to display the name, price and fetch the quantity previously entered into the database.  On page load, i want the script to calculate the total by multiplying the price and quantity of each selected item and adding up the sub-totals of each item to get the grand total.

how can i achieve this?

```<code><div class="panel_container"></div>

<script type="text/javascript">
    $( document ).ready(function() {

    @foreach ($items->products as $product)
        var product = $('#{!! $product->id !!}');
        var selectedItems = JSON.parse(product.attr('data-products'));

        if(product.prop("checked") )  {
            $('.panel_container').append(
                '<div class="container">' +
                    '<p class="name">' + product.name + '</p>' +
                    '<p class="price" data-price="' + product.price + '">' + product.price + '</p>' +
                    '<p class="sub-total"><span class="sub-total" name="sub-total" id="sub-total"></span></p>'+
                    '<input type="text" class="form-control quantity"  placeholder="qty" name="quantity[]" value="{!!$product->pivot->quantity!!}" required/>'+
                '</div>'

            )

        } else {
            //clear selected item
       }
    @endforeach

    calculate();
});

var sub-total = 0;
var calculate = function() {
    var ship_container = $('.panel_container').closest('div');
    var quantity = Number($('.quantity').val());
    var price = Number($('.panel_container').closest('div').find('.price').data('price'));

    ship_container.find(".sub-total span").text(quantity * price);

}

</script>
</code>```

答:
Your code must be modified to run for each product.

var grandTotal = 0;
var calculate = function() {

  // for each product
  $('.panel_container .container').each(function() {
    var product = $(this),
      quantity = Number(product.find('.quantity').val()), // get quantity
      price = Number(product.find('.price').data('price')), // get price
      total = quantity * price; // calculate product total

    product.find('.sub-total span').text(total); // show product total
    grandTotal += total; // add to grand total
  });

  // use the grandTotal here..
  alert('Grand total: ' + grandTotal);
}
```

Additionally, id attributes are required to be unique in the html so you should remove the id="sub-total" from the loop.

Body:
Your code must be modified to run for each product.

var grandTotal = 0;
var calculate = function() {

  // for each product
  $('.panel_container .container').each(function() {
    var product = $(this),
      quantity = Number(product.find('.quantity').val()), // get quantity
      price = Number(product.find('.price').data('price')), // get price
      total = quantity * price; // calculate product total

    product.find('.sub-total span').text(total); // show product total
    grandTotal += total; // add to grand total
  });

  // use the grandTotal here..
  alert('Grand total: ' + grandTotal);
}

Additionally, id attributes are required to be unique in the html so you should remove the id="sub-total" from the loop.


问:
access NSDictionary content
I have an NSDictionary like

```<code>{
        nodeAttributeArray =         (
                        {
                attributeName = ReportDate;
                nodeContent = "08-31-1986";
            },
                        {
                attributeName = ReportType;
                nodeContent = PQ1;
            }
        );
        nodeName = Period;
    },
    {
        nodeAttributeArray =         (
                        {
                attributeName = ReportDate;
                nodeContent = "08-31-1987";
            },
                        {
                attributeName = ReportType;
                nodeContent = PQ2;
            }
        );
        nodeName = Period;
    }
</code>```

I have shown 2 values here. But there are almost 50 such members inside my dict
How do I access the contents of this inside a for loop ?

I want the value inside "nodeContent"

Thank you.

答:
From looking at the data structure, it seems to me that the root structure is a List and not a dictionary as you pose in the question. Is that correct? If that is the case, then an iteration for printing the attribute values to the console would be:</p>

```<code>NSArray *array; // this is your list with 50 values or so in it
//... some code to load the data into array
NSDictionary *d;
for (NSDictionary *period in array){
    NSLog(@"%@",[period objectForKey:@"nodeName"]);
    for (NSDictionary *nodeAttributeArray in [period objectForKey:@"nodeAttributeArray"]){
        NSLog(@"\t%@=%@",[nodeAttributeArray objectForKey:@"attributeName"],[nodeAttributeArray objectForKey:@"nodeContent"]);
    }
}
</code>```

Title: access NSDictionary content

Body:
I have an NSDictionary like

{
        nodeAttributeArray =         (
                        {
                attributeName = ReportDate;
                nodeContent = "08-31-1986";
            },
                        {
                attributeName = ReportType;
                nodeContent = PQ1;
            }
        );
        nodeName = Period;
    },
    {
        nodeAttributeArray =         (
                        {
                attributeName = ReportDate;
                nodeContent = "08-31-1987";
            },
                        {
                attributeName = ReportType;
                nodeContent = PQ2;
            }
        );
        nodeName = Period;
    }

I have shown 2 values here. But there are almost 50 such members inside my dict
How do I access the contents of this inside a for loop ?

I want the value inside "nodeContent"

Thank you.

Body:
From looking at the data structure, it seems to me that the root structure is a List and not a dictionary as you pose in the question. Is that correct? If that is the case, then an iteration for printing the attribute values to the console would be:

NSArray *array; // this is your list with 50 values or so in it
//... some code to load the data into array
NSDictionary *d;
for (NSDictionary *period in array){
    NSLog(@"%@",[period objectForKey:@"nodeName"]);
    for (NSDictionary *nodeAttributeArray in [period objectForKey:@"nodeAttributeArray"]){
        NSLog(@"\t%@=%@",[nodeAttributeArray objectForKey:@"attributeName"],[nodeAttributeArray objectForKey:@"nodeContent"]);
    }
}


问:
How to assign the User Id to Foreign Key
```<code>type Users struct {
    Id       int `orm:"pk;auto"`
    Username string
    Password string
    Salt     string
    Email    string `orm:"unique"`
}

type Post struct {
    Id          int    `orm:"pk;auto"`
    Users       *Users `orm:"rel(fk)"`
    Author      string
    Title       string    `form:"title,text,Title:" valid:"MinSize(5); MaxSize(20)"`
    Description string    `form:textarea`
    Date        time.Time `orm:"auto_now_add;type(datetime)"`
}
</code>```

I am trying to assign value to Users as it is the foreign key. I want to assign the user id who is logged in. How to assign the user id from Users struct to user id in Post struct which is foreign key.

```<code>o := orm.NewOrm()
o.Using("default")
post := models.Post{}
users := models.Users{}

if this.Ctx.Input.Method() == "POST" {
    inputs := this.Input()

    post.Author = sess.(string)
    post.Title = inputs.Get("title")
    post.Description = inputs.Get("description")
    post.Date = time.Now()
}
</code>```

答:
First, answering your question:

```<code>post.Date = time.Now()
// This is your last line
// Up until now all good
post.Users = &users // Actually the naming is bad, should be post.User = user
o.Insert(users) // First create user
o.Insert(post) // Then insert post
</code>```

This is very similar to the basic example BeeGo ORM provides: https://beego.me/docs/mvc/model/orm.md

In real world, you'll notice that most of the time you have a user, and you only want to create it once. So you'll switch first Insert to ReadOrCreate: https://beego.me/docs/mvc/model/object.md#readorcreate

Having said that, from my experience, using MVC and ORM frameworks with Go is a bad idea.

Body:
type Users struct {
    Id       int `orm:"pk;auto"`
    Username string
    Password string
    Salt     string
    Email    string `orm:"unique"`
}

type Post struct {
    Id          int    `orm:"pk;auto"`
    Users       *Users `orm:"rel(fk)"`
    Author      string
    Title       string    `form:"title,text,Title:" valid:"MinSize(5); MaxSize(20)"`
    Description string    `form:textarea`
    Date        time.Time `orm:"auto_now_add;type(datetime)"`
}

I am trying to assign value to Users as it is the foreign key. I want to assign the user id who is logged in. How to assign the user id from Users struct to user id in Post struct which is foreign key.

o := orm.NewOrm()
o.Using("default")
post := models.Post{}
users := models.Users{}

if this.Ctx.Input.Method() == "POST" {
    inputs := this.Input()

    post.Author = sess.(string)
    post.Title = inputs.Get("title")
    post.Description = inputs.Get("description")
    post.Date = time.Now()
}

Body:
First, answering your question:

post.Date = time.Now()
// This is your last line
// Up until now all good
post.Users = &users // Actually the naming is bad, should be post.User = user
o.Insert(users) // First create user
o.Insert(post) // Then insert post

This is very similar to the basic example BeeGo ORM provides: https://beego.me/docs/mvc/model/orm.md

In real world, you'll notice that most of the time you have a user, and you only want to create it once. So you'll switch first Insert to ReadOrCreate: https://beego.me/docs/mvc/model/object.md#readorcreate

Having said that, from my experience, using MVC and ORM frameworks with Go is a bad idea.


问:
Undefined is not a function (evaluating 'ReactComponentTreeHook.purgeUnmountedComponents()'
I'm facing this error and tried to research from the internet but no luck.
It just suddenly happened without reason so I don't know how to reproduce the error.
I followed this solution (https://github.com/facebook/react/issues/8454). Tried to uninstall, install react js again but still the same.
Can someone help to take a look at this ?
Many thanks.
This is my package.json

```<code>{
  "name": "AwesomeLeadership",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node node_modules/react-native/local-cli/cli.js start",
    "test": "jest"
  },
  "dependencies": {
    "@monterosa/react-native-parallax-scroll": "^1.0.4",
    "create-react-class": "^15.6.2",
    "dateformat": "^2.0.0",
    "k-core": "0.0.1-alpha.2",
    "lodash-node": "^3.10.2",
    "native-base": "^2.3.1",
    "prop-types": "^15.6.0",
    "pusher-js": "^4.0.0",
    "react": "^16.1.1",
    "react-debbuger": "0.0.1",
    "react-native": "^0.47.1",
    "react-native-autogrow-textinput": "^4.0.0",
    "react-native-autolink": "^1.1.1",
    "react-native-confetti": "0.0.6",
    "react-native-console-panel": "^0.1.0",
    "react-native-deprecated-custom-components": "^0.1.1",
    "react-native-drawer": "^2.3.0",
    "react-native-drop-refresh": "^2.2.0",
    "react-native-dropdown-menu": "^1.1.0",
    "react-native-easy-grid": "^0.1.15",
    "react-native-easy-toast": "^1.0.6",
    "react-native-i18n": "^2.0.1",
    "react-native-image-picker": "^0.25.1",
    "react-native-keyboard-aware-scroll-view": "^0.3.0",
    "react-native-keyboard-aware-scrollview": "^1.1.7",
    "react-native-keyboard-manager": "^4.0.10-3",
    "react-native-keyboard-spacer": "^0.4.1",
    "react-native-lightbox": "^0.7.0",
    "react-native-loading-spinner-overlay": "^0.5.2",
    "react-native-media-kit": "git+https://github.com/ldn0x7dc/react-native-media-kit.git#pull/30/head",
    "react-native-modal": "^3.0.2",
    "react-native-modal-datetime-picker": "^4.7.0",
    "react-native-modal-dropdown": "^0.4.4",
    "react-native-modal-wrapper": "^2.3.0",
    "react-native-mov-to-mp4": "^0.2.1",
    "react-native-multiple-select": "^0.2.1",
    "react-native-native-video-player": "^1.3.4",
    "react-native-orientation": "git+https://git@github.com/yamill/react-native-orientation.git",
    "react-native-photo-view": "^1.3.0",
    "react-native-progress": "^3.3.0",
    "react-native-progress-bar-classic": "^1.2.1",
    "react-native-push-notification": "^2.2.1",
    "react-native-scrollable-tab-view": "^0.8.0",
    "react-native-simple-modal": "^6.0.0",
    "react-native-slider": "^0.10.0",
    "react-native-spinkit": "^1.1.1",
    "react-native-star-rating": "^1.0.7",
    "react-native-swiper": "^1.5.4",
    "react-native-textinput-effects": "^0.4.1",
    "react-native-thumbnail": "^1.0.8",
    "react-native-triangle": "0.0.9",
    "react-native-vector-icons": "^4.0.0",
    "react-native-video": "^2.0.0",
    "react-redux": "^4.4.5",
    "redux": "^3.6.0",
    "redux-logger": "^2.7.4",
    "redux-persist": "^4.0.1",
    "redux-thunk": "^2.1.0",
    "underscore": "^1.8.3"
  },
  "jest": {
    "preset": "jest-react-native"
  },
  "devDependencies": {
    "babel-eslint": "^7.1.1",
    "babel-jest": "17.0.0",
    "babel-preset-react-native": "1.9.0",
    "eslint": "^3.11.1",
    "eslint-config-airbnb": "^13.0.0",
    "eslint-plugin-import": "^2.2.0",
    "eslint-plugin-jsx-a11y": "^2.2.3",
    "eslint-plugin-react": "^6.7.1",
    "jest": "^17.0.0",
    "jest-react-native": "17.0.0",
    "react-test-renderer": "15.3.2"
  },
  "rnpm": {
    "assets": [
      "./assets/fonts"
    ]
  }
}
</code>```

index.android.js

```<code>import React, { AppRegistry } from 'react-native';
import AppProvider from './src/index';
AppRegistry.registerComponent('AwesomeLeadership', () => AppProvider);
</code>```

index.js

```<code>import React, { Component } from 'react';
import { AppRegistry } from 'react-native';
import { Provider } from 'react-redux';
import { persistStore, autoRehydrate } from 'redux-persist';
import store from './app/appStore';
import AppContainer from './app/appContainer';
import Splashscreen from './app/splashScreen';
import I18n from './app/i18n';
import SwipUnlocker from './app/SwipeUnlocker';

const Orientation = require('react-native-orientation');

class AwesomeLeadership extends Component {
  render() {
    return <AppContainer /> ;
  }
}

class AppProvider extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isInitializing: true,
    }
  }

  componentDidMount() {
    Orientation.lockToPortrait();
    const unsubscribe = store.subscribe(() => {
      if (store.getState().isHydrated) {
        unsubscribe();
        I18n.locale = 'sv-SE';
        this.setState({
          isInitializing: false,
        });
      }
    });
  }

  render() {
    if(this.state.isInitializing) {
      return <Splashscreen/>;
    } else {
      return (
        <Provider store={store}>
          <AwesomeLeadership/>
        </Provider>
      );
    }
  }
}

export default AppProvider;
</code>```

答:
I had the same error and I beleive it was connected with different versions of React and React Native.

For example, RN 0.51 requires a peer dependency of React 16.0. In my case I had 16 alpha and that caused the error. I suggest you try to install the corresponding version of React.

Hope it helps.

Body:
I'm facing this error and tried to research from the internet but no luck.
It just suddenly happened without reason so I don't know how to reproduce the error.
I followed this solution (https://github.com/facebook/react/issues/8454). Tried to uninstall, install react js again but still the same.
Can someone help to take a look at this ?
Many thanks.
This is my package.json

{
  "name": "AwesomeLeadership",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node node_modules/react-native/local-cli/cli.js start",
    "test": "jest"
  },
  "dependencies": {
    "@monterosa/react-native-parallax-scroll": "^1.0.4",
    "create-react-class": "^15.6.2",
    "dateformat": "^2.0.0",
    "k-core": "0.0.1-alpha.2",
    "lodash-node": "^3.10.2",
    "native-base": "^2.3.1",
    "prop-types": "^15.6.0",
    "pusher-js": "^4.0.0",
    "react": "^16.1.1",
    "react-debbuger": "0.0.1",
    "react-native": "^0.47.1",
    "react-native-autogrow-textinput": "^4.0.0",
    "react-native-autolink": "^1.1.1",
    "react-native-confetti": "0.0.6",
    "react-native-console-panel": "^0.1.0",
    "react-native-deprecated-custom-components": "^0.1.1",
    "react-native-drawer": "^2.3.0",
    "react-native-drop-refresh": "^2.2.0",
    "react-native-dropdown-menu": "^1.1.0",
    "react-native-easy-grid": "^0.1.15",
    "react-native-easy-toast": "^1.0.6",
    "react-native-i18n": "^2.0.1",
    "react-native-image-picker": "^0.25.1",
    "react-native-keyboard-aware-scroll-view": "^0.3.0",
    "react-native-keyboard-aware-scrollview": "^1.1.7",
    "react-native-keyboard-manager": "^4.0.10-3",
    "react-native-keyboard-spacer": "^0.4.1",
    "react-native-lightbox": "^0.7.0",
    "react-native-loading-spinner-overlay": "^0.5.2",
    "react-native-media-kit": "git+https://github.com/ldn0x7dc/react-native-media-kit.git#pull/30/head",
    "react-native-modal": "^3.0.2",
    "react-native-modal-datetime-picker": "^4.7.0",
    "react-native-modal-dropdown": "^0.4.4",
    "react-native-modal-wrapper": "^2.3.0",
    "react-native-mov-to-mp4": "^0.2.1",
    "react-native-multiple-select": "^0.2.1",
    "react-native-native-video-player": "^1.3.4",
    "react-native-orientation": "git+https://git@github.com/yamill/react-native-orientation.git",
    "react-native-photo-view": "^1.3.0",
    "react-native-progress": "^3.3.0",
    "react-native-progress-bar-classic": "^1.2.1",
    "react-native-push-notification": "^2.2.1",
    "react-native-scrollable-tab-view": "^0.8.0",
    "react-native-simple-modal": "^6.0.0",
    "react-native-slider": "^0.10.0",
    "react-native-spinkit": "^1.1.1",
    "react-native-star-rating": "^1.0.7",
    "react-native-swiper": "^1.5.4",
    "react-native-textinput-effects": "^0.4.1",
    "react-native-thumbnail": "^1.0.8",
    "react-native-triangle": "0.0.9",
    "react-native-vector-icons": "^4.0.0",
    "react-native-video": "^2.0.0",
    "react-redux": "^4.4.5",
    "redux": "^3.6.0",
    "redux-logger": "^2.7.4",
    "redux-persist": "^4.0.1",
    "redux-thunk": "^2.1.0",
    "underscore": "^1.8.3"
  },
  "jest": {
    "preset": "jest-react-native"
  },
  "devDependencies": {
    "babel-eslint": "^7.1.1",
    "babel-jest": "17.0.0",
    "babel-preset-react-native": "1.9.0",
    "eslint": "^3.11.1",
    "eslint-config-airbnb": "^13.0.0",
    "eslint-plugin-import": "^2.2.0",
    "eslint-plugin-jsx-a11y": "^2.2.3",
    "eslint-plugin-react": "^6.7.1",
    "jest": "^17.0.0",
    "jest-react-native": "17.0.0",
    "react-test-renderer": "15.3.2"
  },
  "rnpm": {
    "assets": [
      "./assets/fonts"
    ]
  }
}

index.android.js

import React, { AppRegistry } from 'react-native';
import AppProvider from './src/index';
AppRegistry.registerComponent('AwesomeLeadership', () => AppProvider);

index.js

import React, { Component } from 'react';
import { AppRegistry } from 'react-native';
import { Provider } from 'react-redux';
import { persistStore, autoRehydrate } from 'redux-persist';
import store from './app/appStore';
import AppContainer from './app/appContainer';
import Splashscreen from './app/splashScreen';
import I18n from './app/i18n';
import SwipUnlocker from './app/SwipeUnlocker';

const Orientation = require('react-native-orientation');

class AwesomeLeadership extends Component {
  render() {
    return <AppContainer /> ;
  }
}

class AppProvider extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isInitializing: true,
    }
  }

  componentDidMount() {
    Orientation.lockToPortrait();
    const unsubscribe = store.subscribe(() => {
      if (store.getState().isHydrated) {
        unsubscribe();
        I18n.locale = 'sv-SE';
        this.setState({
          isInitializing: false,
        });
      }
    });
  }

  render() {
    if(this.state.isInitializing) {
      return <Splashscreen/>;
    } else {
      return (
        <Provider store={store}>
          <AwesomeLeadership/>
        </Provider>
      );
    }
  }
}

export default AppProvider;


问:
How to give Promise to For Loop in NodeJS
How to stop nodeJS to execute statements written outside for loop till for loop is completed?

```<code>for(i=0;i<=countFromRequest;i++)
{
    REQUEST TO MODEL => then getting result here (its an object)
    licensesArray.push(obj.key);
}
res.status(200).send({info:"Done Releasing Bulk Licenses!!!",licensesArray:licensesArray})
</code>```

The problem is that the statement after For Loop is being executed before For loop, so the licensesArray is empty when i receive the API Data.

Any clue how to do that?

Will be thankful to you.

答:
Using async/await:

```<code>const licensesArray = [];

for(let i = 0; i <= countFromRequest; i++) {
    const obj = await requestModel(); // wait for model and get resolved value
    licensesArray.push(obj.key);
}

res.status(200).send({licensesArray});
</code>```

Using Promise.all:

```<code>const pArr = [];
const licensesArray = [];

for(let i = 0; i <= countFromRequest; i++) {
    pArr.push(requestModel().then(obj => {
        licensesArray.push(obj.key);
    }));
}

Promise.all(pArr).then(() => { // wait for all promises to resolve
    res.status(200).send({licensesArray});
});
</code>```

I would go with async/await if your environment supports it, as it makes things easier to read and lets you program with a synchronous mindset (under the hood it's still asynchronous). If your environment does not support it, you can go with the Promise.all approach.

Further reading:

async function

Promise.all

Body:
How to stop nodeJS to execute statements written outside for loop till for loop is completed?

for(i=0;i<=countFromRequest;i++)
{
    REQUEST TO MODEL => then getting result here (its an object)
    licensesArray.push(obj.key);
}
res.status(200).send({info:"Done Releasing Bulk Licenses!!!",licensesArray:licensesArray})

The problem is that the statement after For Loop is being executed before For loop, so the licensesArray is empty when i receive the API Data.

Any clue how to do that?

Will be thankful to you.

Body:
Using async/await:

const licensesArray = [];

for(let i = 0; i <= countFromRequest; i++) {
    const obj = await requestModel(); // wait for model and get resolved value
    licensesArray.push(obj.key);
}

res.status(200).send({licensesArray});

Using Promise.all:

const pArr = [];
const licensesArray = [];

for(let i = 0; i <= countFromRequest; i++) {
    pArr.push(requestModel().then(obj => {
        licensesArray.push(obj.key);
    }));
}

Promise.all(pArr).then(() => { // wait for all promises to resolve
    res.status(200).send({licensesArray});
});

I would go with async/await if your environment supports it, as it makes things easier to read and lets you program with a synchronous mindset (under the hood it's still asynchronous). If your environment does not support it, you can go with the Promise.all approach.

Further reading:

async function

Promise.all


问:
n steps with 1, 2 or 3 steps taken. How many ways to get to the top?
If we have n steps and we can go up 1 or 2 steps at a time, there is a Fibonacci relation between the number of steps and the ways to climb them. IF and ONLY if we do not count 2+1 and 1+2 as different.

However, this no longer the case, as well as having to add we add a third option, taking 3 steps. How do I do this?

What I have:

```<code>1 step = 1 way
2 steps = 2 ways: 1+1, 2
3 steps = 4 ways: 1+1+1, 2+1, 1+2, 3
</code>```

I have no idea where to go from here to find out the number of ways for n stairs

I get 7 for n = 4 and 14 for n= 5 i get 14+7+4+2+1 by doing the sum of all the combinations before it. so ways for n steps = n-1 ways + n-2 ways + .... 1 ways  assuming i kept all the values.  DYNAMIC programming.
1 2 and 3 steps would be the base-case is that correct?

答:
```<code>def count(steps):
  sol = []
  sol.append(1)
  sol.append(1 + sol[0])
  sol.append(1 + sol[1] + sol[0])

  if(steps > 3):
    for x in range(4, steps+1):
        sol[(x-1)%3] = sum(sol)

return sol[(steps-1)%3]
</code>```

Body:
If we have n steps and we can go up 1 or 2 steps at a time, there is a Fibonacci relation between the number of steps and the ways to climb them. IF and ONLY if we do not count 2+1 and 1+2 as different.

However, this no longer the case, as well as having to add we add a third option, taking 3 steps. How do I do this?

What I have:

1 step = 1 way
2 steps = 2 ways: 1+1, 2
3 steps = 4 ways: 1+1+1, 2+1, 1+2, 3

I have no idea where to go from here to find out the number of ways for n stairs

I get 7 for n = 4 and 14 for n= 5 i get 14+7+4+2+1 by doing the sum of all the combinations before it. so ways for n steps = n-1 ways + n-2 ways + .... 1 ways  assuming i kept all the values.  DYNAMIC programming.
1 2 and 3 steps would be the base-case is that correct?


问:
MediaWiki installed with nginx reverse proxy configuration
I would like to install MediaWiki in such a way.

Download and extract all the MediaWiki installation files to a location where wiki.gaobo.org nginx server block points to;

Set up a reverse proxy configuration in gao.bo nginx server block so that gao.bo/wiki is equivalent to wiki.gaobo.org ;

Launch the installation from gao.bo/wiki so that initially the server URL is gao.bo/wiki instead of wiki.gaobo.org .

Questions:

Is the design above implementable after all?

If possible, how to implement Step 2?

答:
This is certainly doable (although from a generic usability and information security point of view having different things on different domains is usually better). Probably the easiest way to do it is to not expose the MediaWiki server directly to the web, install MediaWiki under /wiki and tell it (via $wgServer) that it is running on gao.bo. That way the proxy does not have to deal with URL rewrites, cookie path rewrites, different domain names etc.

To set that up, you would set something like

```<code>location /wiki/ {
    proxy_pass http://<IP of your MediaWiki server>;
}
</code>```

for the proxy nginx, and make sure the wiki server routes requests for /wiki/ to the MediaWiki installation. Then you can just run the installer via the proxy, as you described, and add the IP of the proxy to $wgSquidServers so that MediaWiki trusts X-Forwarded-For headers.

Body:
This is certainly doable (although from a generic usability and information security point of view having different things on different domains is usually better). Probably the easiest way to do it is to not expose the MediaWiki server directly to the web, install MediaWiki under /wiki and tell it (via $wgServer) that it is running on gao.bo. That way the proxy does not have to deal with URL rewrites, cookie path rewrites, different domain names etc.

To set that up, you would set something like

location /wiki/ {
    proxy_pass http://<IP of your MediaWiki server>;
}

for the proxy nginx, and make sure the wiki server routes requests for /wiki/ to the MediaWiki installation. Then you can just run the installer via the proxy, as you described, and add the IP of the proxy to $wgSquidServers so that MediaWiki trusts X-Forwarded-For headers.