问:
How to override Spring Boot library properties?
I would like to override the library properties that I've written in project that is using it. I'm using this Spring guide on creating library: https://spring.io/guides/gs/multi-module/

I would like to know how to override for example my.properties file in the project that uses my library.

Is it even possible?

答:
Seems you cannot. Since Spring itself also cannot

In the sample above we have configured the service.message for the test using the default attribute of the @SpringBootTest annotation. It is not advisable to put application.properties in a library because there might be a clash at runtime in the application that uses it (only one application.properties is ever loaded from the classpath). You could put application.properties in the test classpath, but not include it in the jar, for instance by placing it in src/test/resources.


来源: stackexchange

问:
How should I read the message a git fetch returns?
I just did

```<code>get fetch origin feature/8067
</code>```

and below it I got 3 columns:

```<code> * branch                feature/8067 -> FETCH_HEAD
 * [new branch]          feature/8067 -> origin/feature/8067
</code>```

Trying to process this...reading from here I just learned that FETCH_HEAD basically means the tip of where I last did a fetch. The file will contain a commit.

Does that [new branch] refer to the new branch created under my refs/remote?

I'm not sure if my reading of the following is correct: feature/8067 -> origin/feature/8067

Is the 2nd column the <nameOfBranchOnRemoteRepo> while the 3rd column is <repoName/nameOfBranchOnRemoteRepo> and it says my fetched remote branch in the refs is pointing to that in the remote?

答:
The fetch output is confusing even to an old hand.  Here's how I decode them:

```<code> * branch                feature/8067 -> FETCH_HEAD
 * [new branch]          feature/8067 -> origin/feature/8067
</code>```

Work each line from right to left:

The first line ends with FETCH_HEAD, which means that the reference was deposited into FETCH_HEAD.  See the note about FETCH_HEAD below.  The arrow is hardcoded (always appears and you can just sort of ignore it); the name feature/8067 is the name of the reference on the remote; and * branch tells you that it was really refs/heads/feature/8067 on the remote, i.e., was a branch.  Because this was deposited into FETCH_HEAD there's no additional information available.

The second line ends with origin/feature/8067.  Your remote-tracking name1 origin/feature/8067 (full name refs/remotes/origin/feature/8067) has been created or updated.  As before, we have the arrow and the same name.  Then we have * [new branch]: this tells us that origin/feature/8067 did not exist before, and that feature/8067 was—as we already know—a branch name on the remote.

Here's what I get updating a Git repository for Git:

```<code>   ab15ad1a3b..aa25c82427  master      -> origin/master
   ef7435264c..5a294203ad  next        -> origin/next
 + f98c0007ae...e49ac33073 pu          -> origin/pu  (forced update)
   0f4b6a451a..ff8db353a4  todo        -> origin/todo
 * [new tag]               v2.22.0-rc1 -> v2.22.0-rc1
</code>```

Again we can work right to left:

My origin/master got created-or-updated, from their master.  The value of my origin/master was ab15ad1a3b but is now aa25c82427.  Since there was a value, it's been updated, not created.

My origin/next has been created-or-updated, with everything else basically the same as above (modulo the obvious differences).

My origin/pu has been updated by force, i.e., this is not a fast-forward and some commits have been deleted.  The source was their pu branch and my origin/pu used to be f98c0007ae but is now ff8db353a4.  The fact that there are three dots between the two hash IDs—the other lines have only two dots—means that the update was forced, hence not a fast-forward.  The plus sign at the very front means that the update was forced.  (Clearly, it's pretty important that the update was forced: I have three announcements to that effect!)

My origin/todo has been created-or-updated, and by the time we get to the left side, it's obviously an update.

My v2.22.0-rc1 has been created-or-updated, from their v2.22.0-rc1; this is a new tag.

Any time you have a new name (branch, tag, or any other reference), it's by definition a regular non-forced creation and there's no old..new hash available, so the left edge will read * [new whatever].

FETCH_HEAD is special: all updates get written to .git/FETCH_HEAD, usually wiping out whatever was in it before (but with -a or --append, git fetch will append instead).  Each fetched reference results in one line appearing in FETCH_HEAD, giving:

the hash ID

an optional not-for-merge string

the type and name of the reference and its source:

```<code>$ cat .git/FETCH_HEAD
aa25c82427ae70aebf3b8f970f2afd54e9a2a8c6        branch 'master' of git://...
[snipped for length]
</code>```

The one line that is not marked not-for-merge is suitable for the git pull script2 to fish out and pass that hash ID to git merge or git rebase.

1A remote-tracking name, which most of Git calls a remote-tracking branch, is a reference in your repository whose full name starts with refs/remotes/ and goes on to include the name of the remote, in this case origin, and another slash, and then normally holds the rest of the branch name as seen on that remote.

A reference is just the generalized name for things that are branches, tags, remote-tracking names, refs/stash, and so on: a string-format name, generally starting with refs/, that remembers one hash ID.  For a branch, the one hash ID the name remembers is the commit that Git should consider to be the tip of that branch.  For a tag, the one hash ID the name remembers is either the hash ID of the commit, or the hash ID of an annotated tag object that contains additional information (perhaps including a signing key), plus the hash ID of the tagged object (typically a commit though any tag can point to any one of Git's internal object types).

Git builds remote-tracking names through a refspec.  You can supply a refspec when you run git fetch.  If you do not supply a refspec, but do supply a remote name like origin, Git fishes the correct refspec from your configuration:

```<code>$ git config --get-all remote.origin.fetch
+refs/heads/*:refs/remotes/origin/*
</code>```

A standard configuration for origin always has this exact default refspec, but there are some useful nonstandard configurations, such as the one created by git clone --single-branch.  You can also make your own totally bizarre refspecs, though depending on how twisted you get, some combinations will result in a non-functioning git fetch.

2Well, back when when git pull was a script, anyway.  It's been re-coded in C for speed on Windows.

ContentLicense: CC BY-SA 4.0

Body:
I just did

get fetch origin feature/8067

and below it I got 3 columns:

 * branch                feature/8067 -> FETCH_HEAD
 * [new branch]          feature/8067 -> origin/feature/8067

Trying to process this...reading from here I just learned that FETCH_HEAD basically means the tip of where I last did a fetch. The file will contain a commit.

Does that [new branch] refer to the new branch created under my refs/remote?

I'm not sure if my reading of the following is correct: feature/8067 -> origin/feature/8067

Is the 2nd column the <nameOfBranchOnRemoteRepo> while the 3rd column is <repoName/nameOfBranchOnRemoteRepo> and it says my fetched remote branch in the refs is pointing to that in the remote?

Body:
The fetch output is confusing even to an old hand.  Here's how I decode them:

 * branch                feature/8067 -> FETCH_HEAD
 * [new branch]          feature/8067 -> origin/feature/8067

Work each line from right to left:

The first line ends with FETCH_HEAD, which means that the reference was deposited into FETCH_HEAD.  See the note about FETCH_HEAD below.  The arrow is hardcoded (always appears and you can just sort of ignore it); the name feature/8067 is the name of the reference on the remote; and * branch tells you that it was really refs/heads/feature/8067 on the remote, i.e., was a branch.  Because this was deposited into FETCH_HEAD there's no additional information available.

The second line ends with origin/feature/8067.  Your remote-tracking name1 origin/feature/8067 (full name refs/remotes/origin/feature/8067) has been created or updated.  As before, we have the arrow and the same name.  Then we have * [new branch]: this tells us that origin/feature/8067 did not exist before, and that feature/8067 was—as we already know—a branch name on the remote.

Here's what I get updating a Git repository for Git:

   ab15ad1a3b..aa25c82427  master      -> origin/master
   ef7435264c..5a294203ad  next        -> origin/next
 + f98c0007ae...e49ac33073 pu          -> origin/pu  (forced update)
   0f4b6a451a..ff8db353a4  todo        -> origin/todo
 * [new tag]               v2.22.0-rc1 -> v2.22.0-rc1

Again we can work right to left:

My origin/master got created-or-updated, from their master.  The value of my origin/master was ab15ad1a3b but is now aa25c82427.  Since there was a value, it's been updated, not created.

My origin/next has been created-or-updated, with everything else basically the same as above (modulo the obvious differences).

My origin/pu has been updated by force, i.e., this is not a fast-forward and some commits have been deleted.  The source was their pu branch and my origin/pu used to be f98c0007ae but is now ff8db353a4.  The fact that there are three dots between the two hash IDs—the other lines have only two dots—means that the update was forced, hence not a fast-forward.  The plus sign at the very front means that the update was forced.  (Clearly, it's pretty important that the update was forced: I have three announcements to that effect!)

My origin/todo has been created-or-updated, and by the time we get to the left side, it's obviously an update.

My v2.22.0-rc1 has been created-or-updated, from their v2.22.0-rc1; this is a new tag.

Any time you have a new name (branch, tag, or any other reference), it's by definition a regular non-forced creation and there's no old..new hash available, so the left edge will read * [new whatever].

FETCH_HEAD is special: all updates get written to .git/FETCH_HEAD, usually wiping out whatever was in it before (but with -a or --append, git fetch will append instead).  Each fetched reference results in one line appearing in FETCH_HEAD, giving:

the hash ID

an optional not-for-merge string

the type and name of the reference and its source:

$ cat .git/FETCH_HEAD
aa25c82427ae70aebf3b8f970f2afd54e9a2a8c6        branch 'master' of git://...
[snipped for length]

The one line that is not marked not-for-merge is suitable for the git pull script2 to fish out and pass that hash ID to git merge or git rebase.

1A remote-tracking name, which most of Git calls a remote-tracking branch, is a reference in your repository whose full name starts with refs/remotes/ and goes on to include the name of the remote, in this case origin, and another slash, and then normally holds the rest of the branch name as seen on that remote.

A reference is just the generalized name for things that are branches, tags, remote-tracking names, refs/stash, and so on: a string-format name, generally starting with refs/, that remembers one hash ID.  For a branch, the one hash ID the name remembers is the commit that Git should consider to be the tip of that branch.  For a tag, the one hash ID the name remembers is either the hash ID of the commit, or the hash ID of an annotated tag object that contains additional information (perhaps including a signing key), plus the hash ID of the tagged object (typically a commit though any tag can point to any one of Git's internal object types).

Git builds remote-tracking names through a refspec.  You can supply a refspec when you run git fetch.  If you do not supply a refspec, but do supply a remote name like origin, Git fishes the correct refspec from your configuration:

$ git config --get-all remote.origin.fetch
+refs/heads/*:refs/remotes/origin/*

A standard configuration for origin always has this exact default refspec, but there are some useful nonstandard configurations, such as the one created by git clone --single-branch.  You can also make your own totally bizarre refspecs, though depending on how twisted you get, some combinations will result in a non-functioning git fetch.

2Well, back when when git pull was a script, anyway.  It's been re-coded in C for speed on Windows.


问:
How to get the data associated with the error response back?
I am making a request from the front-end to a route in my backend that is validating the token associated with a user, which would send an error response back to the front-end if the token has expired. I am sending some json with it but upon doing console.log of the error message in the catch block, the json sent along the error response is not shown.

Sending the error response like this

res.status(401).json({
                message: 'User session has expired'
            })
```

But the response that I am getting in the catch block in the front-end has no sign of the json sent with the error.

POST http://localhost:3001/check-validation 401 (Unauthorized)
  Error: Request failed with status code 401
      at createError (createError.js:17)
      at settle (settle.js:19)
      at XMLHttpRequest.handleLoad (xhr.js:78)

I don't understand why the json sent along the error response is not shown and how to get it?

答:
Upon doing console.log of the error only the stacktrace of the error is shown and not the data associated with it. The data sent with it can be procured and depends on how the request has been made or by what library it has been made. If the request is made by axios then the following can be done:

axios.post('/formulas/create', {
    name: "",
    parts: ""
})
.then(response => {
    console.log(response)
})
.catch(error => {
    console.log(error.response.data.message)
});
```

<p>Here, in axios the details of the error would be wrapped up in <code>error.response</code>. Whereas, if the request was made by the <code>fetch</code> API then something following can resolve the problem:  </p>

<pre class="lang-js prettyprint-override"><code>fetch('/401').then(function(response) {
  if (response.status === 401) {
    return response.json()
  }
}).then(function(object) {
  console.log(object.message)
})
</code>```

P.S I was searching a lot regarding this problem but didn't get an answer on SO, neither got any article or docs regarding it, even the official Express docs on error handling were not helpful. At last, I understood that the problem lies with the library that is being used to make the request. That's why answering my own question to mark the presence of this question on SO. A detailed discussion can be found here related to axios and here related to fetch api

Body:
I am making a request from the front-end to a route in my backend that is validating the token associated with a user, which would send an error response back to the front-end if the token has expired. I am sending some json with it but upon doing console.log of the error message in the catch block, the json sent along the error response is not shown.

Sending the error response like this

res.status(401).json({
                message: 'User session has expired'
            })

But the response that I am getting in the catch block in the front-end has no sign of the json sent with the error.

POST http://localhost:3001/check-validation 401 (Unauthorized)
  Error: Request failed with status code 401
      at createError (createError.js:17)
      at settle (settle.js:19)
      at XMLHttpRequest.handleLoad (xhr.js:78)

I don't understand why the json sent along the error response is not shown and how to get it?

Body:
Upon doing console.log of the error only the stacktrace of the error is shown and not the data associated with it. The data sent with it can be procured and depends on how the request has been made or by what library it has been made. If the request is made by axios then the following can be done:

axios.post('/formulas/create', {
    name: "",
    parts: ""
})
.then(response => {
    console.log(response)
})
.catch(error => {
    console.log(error.response.data.message)
});

Here, in axios the details of the error would be wrapped up in error.response. Whereas, if the request was made by the fetch API then something following can resolve the problem:

fetch('/401').then(function(response) {
  if (response.status === 401) {
    return response.json()
  }
}).then(function(object) {
  console.log(object.message)
})

P.S I was searching a lot regarding this problem but didn't get an answer on SO, neither got any article or docs regarding it, even the official Express docs on error handling were not helpful. At last, I understood that the problem lies with the library that is being used to make the request. That's why answering my own question to mark the presence of this question on SO. A detailed discussion can be found here related to axios and here related to fetch api


问:
Not getting remote address while using proxy in socket.io
In my socket.io code,

```<code>socket.sockets.on('connection', function(client){
    var ip = client.handshake.address.address;
    ..
}
</code>```

ip always returns 127.0.0.1 and this is because the server sits behind a proxy.
How do I get remote address properly ?

Edit: I am using http-proxy

答: For people who may come from Google, using NGINX: none of these worked for me, I followed the answer in this other question and modified my proxy_pass, to create a new header that node could then use. Don't forget to call sudo systemctl restart nginx after.

ContentLicense: CC BY-SA 3.0

Body:
In my socket.io code,

socket.sockets.on('connection', function(client){
    var ip = client.handshake.address.address;
    ..
}

ip always returns 127.0.0.1 and this is because the server sits behind a proxy.
How do I get remote address properly ?

Edit: I am using http-proxy


问:
How to convert dynamoDB BatchSave API failed batch results to list of pojos?
How to convert dynamoDB BatchSave API failed batch results to list of pojos? The dynamoDB BatchSave API failed batch results are represented in DDB low level API classes like PutRequest/DeleteRequest/WriteRequest/Map.

Is there a simple way to convert Map to pojo which represents a DDB table item?

It took hours to find a solution. Hence I would like to create a question and provide answer to save others time if they come across similar use case.

答:
```<code>private List<T> getFailedBatchListItems(final FailedBatch failedBatch, final Class<T> clazz) {
    return failedBatch.getUnprocessedItems()
                      .values()
                      .stream()
                      .flatMap(List::stream)
                      .map(WriteRequest::getPutRequest)
                      .map(PutRequest::getItem)
                      .map(e -> dynamoDBMapper.marshallIntoObject(clazz, e))
                      .collect(toList());
}
</code>```


问:
R, add seperate bewteen each word
I take column datas from a data set data, and hope to feed them into model variable list
    colnames(data)
    "col1" "col2" "col3" "col4"
The model variable list has the format below:
    c("col1", "col2","col3", "col4")
My challenge is the comma, how can I add them ?</p>

答: Paste(colnames(data), collapse=',')</p>

Title: R, add seperate bewteen each word

Body: Paste(colnames(data), collapse=',')


问:
Live character count for EditText
I was wondering what the best way to do a live character count of an edit-text box is in Android. I was looking at this but I couldn't seem to make any sense of it.

To describe the problem, I have an EditText and I'm trying to limit the characters to 150. I can do this with an input filter, however I want to show right below the text box the number of characters a user has entered(Almost like stack overflow is doing right now).

If someone could write a small snippet of example code or point me in the right direction I'd appreciate it a lot.

答:
This solution uses Kotlin and shows the number of characters left. Also, if the current number of characters surpasses the limit of 50, the text color will change to red.

Kotlin

```<code>private val mTitleTextWatcher = object : TextWatcher {
    override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}

    override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
        if(YOUR_EDIT_TEXT_ID.text.toString().trim().length < 51){
            YOUR_CHAR_LEFT_TEXTVIEW_ID.text = (50 - YOUR_EDIT_TEXT_ID.text.toString().trim().length).toString()
            YOUR_CHAR_LEFT_TEXTVIEW_ID.setTextColor(Color.BLACK)
        }
        else{
            YOUR_CHAR_LEFT_TEXTVIEW_ID.text = "0"
            YOUR_CHAR_LEFT_TEXTVIEW_ID.setTextColor(Color.RED)
        }
    }

    override fun afterTextChanged(s: Editable) {}
}
</code>```

Also, don't forget to add the TextWatcher to your EditText

```<code>YOUR_EDIT_TEXT_ID.addTextChangedListener(mTitleTextWatcher)
</code>```

Title: Live character count for EditText

Body:
This solution uses Kotlin and shows the number of characters left. Also, if the current number of characters surpasses the limit of 50, the text color will change to red.

Kotlin

private val mTitleTextWatcher = object : TextWatcher {
    override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}

    override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
        if(YOUR_EDIT_TEXT_ID.text.toString().trim().length < 51){
            YOUR_CHAR_LEFT_TEXTVIEW_ID.text = (50 - YOUR_EDIT_TEXT_ID.text.toString().trim().length).toString()
            YOUR_CHAR_LEFT_TEXTVIEW_ID.setTextColor(Color.BLACK)
        }
        else{
            YOUR_CHAR_LEFT_TEXTVIEW_ID.text = "0"
            YOUR_CHAR_LEFT_TEXTVIEW_ID.setTextColor(Color.RED)
        }
    }

    override fun afterTextChanged(s: Editable) {}
}

Also, don't forget to add the TextWatcher to your EditText

YOUR_EDIT_TEXT_ID.addTextChangedListener(mTitleTextWatcher)


问:
Split file text Angular
I have this :

```<code>export class LeerArchivoComponent implements OnInit {
      private fileText;
      private nombre:String;
      constructor() { }

      ngOnInit() {
      }

      fileUpload(event){
        var reader = new FileReader();
        reader.readAsText(event.srcElement.files[0]);
        var me = this;
        var nombre:String;
        reader.onload = function (){
          me.fileText = reader.result;

        }

}
</code>```

And this one:

```<code><input id="file-upload"
   type="file"
   accept=".txt"
   (change)="fileUpload($event)">
<textarea rows="4" cols="50">{{fileText}}</textarea>
</code>```

Thats read a text file.
I have a text file like :

```<code>"u901_humext  ""2019-02-10 00:00""    99.97   99.97   99.97"

"u901_radpar   ""2019-02-10 15:40""    1002.9  1068.4  1034.3943396226"
</code>```

The problem is that i want to split it by spaces, " and "".
How can i do that?
Thanks.
Im using Angular.

答:
Since parsing csvs can be quite problematic at times.
Are they using spaces or tabs. does the file contain text delimiters or not.
Are there any special formatting scenarios you need to take into account.

I would probably use a library to not reinvent the wheel.

https://github.com/okfn/csv.js/

It takes a blob as an input, so the file you uploaded you can simply pipe into it.

and you get this nice object back

```<code>{
  // an array of arrays - one array each row in the CSV
  // (excluding header row - i.e. first row)
  records: [ [...], [...], ... ],
  // list of fields
  fields: [ 'field-name-1', 'field-name-2', ... ],
  metadata: { may be some metadata e.g. file name }
}
</code>```

Could that be your solution?

Title: Split file text Angular

Body:
I have this :

export class LeerArchivoComponent implements OnInit {
      private fileText;
      private nombre:String;
      constructor() { }

      ngOnInit() {
      }

      fileUpload(event){
        var reader = new FileReader();
        reader.readAsText(event.srcElement.files[0]);
        var me = this;
        var nombre:String;
        reader.onload = function (){
          me.fileText = reader.result;

        }

}

And this one:

<input id="file-upload"
   type="file"
   accept=".txt"
   (change)="fileUpload($event)">
<textarea rows="4" cols="50">{{fileText}}</textarea>

Thats read a text file.
I have a text file like :

"u901_humext  ""2019-02-10 00:00""    99.97   99.97   99.97"

"u901_radpar   ""2019-02-10 15:40""    1002.9  1068.4  1034.3943396226"

The problem is that i want to split it by spaces, " and "".
How can i do that?
Thanks.
Im using Angular.

Body:
Since parsing csvs can be quite problematic at times.
Are they using spaces or tabs. does the file contain text delimiters or not.
Are there any special formatting scenarios you need to take into account.

I would probably use a library to not reinvent the wheel.

https://github.com/okfn/csv.js/

It takes a blob as an input, so the file you uploaded you can simply pipe into it.

and you get this nice object back

{
  // an array of arrays - one array each row in the CSV
  // (excluding header row - i.e. first row)
  records: [ [...], [...], ... ],
  // list of fields
  fields: [ 'field-name-1', 'field-name-2', ... ],
  metadata: { may be some metadata e.g. file name }
}

Could that be your solution?


问:
Setting Resource Arn from Output of step of AWS Step Function
I have a step function where I want to start by getting the resourceArn for an ECS Cluster and then invoke tasks on that cluster.

However, I'm having difficulty dynamically passing the arn from step to step.

```<code>{
 "StartAt": "GetArnLambda",
 "States": {
   "GetArnLambda": {
     "Type": "Task",
     "Resource": "arn:aws:lambda:us-east-1:AWS_ACCOUNT_ID:function:FUNCTION_NAME",
     "Next": "ecs_task"
   },
   "ecs_task": {
     "Type": "Task",
     "Resource": "arn:aws:states:::ecs:runTask.sync",
     "Parameters": {
                "Cluster": "$.arn",
                "TaskDefinition": "ecs_task_def"
            },
     "End": true
    }
}
</code>```

And I get as output from GetArnLambda

```<code>{
  "name": "GetArnLambda",
  "output": {
    "arn": "arn:aws:ecs:us-east-1:AWS_ACCOUNT_ID:cluster/CLUSTER_NAME"
  }
}
</code>```

But this interprets the Cluster arn as "$.arn". How can I reference the arn I just received from the first task?

答:
From the documentation:

Use "Parameters" field to create a collection of key-value pairs that are passed as input. The values of each can either be static values that you include in your state machine definition, or selected from either the input or the context object with a path. For key-value pairs where the value is selected using a path, the key name must end in .$.

So I think you need:

```<code> "Parameters": {
            "Cluster.$": "$.arn",
            "TaskDefinition": "ecs_task_def"
        },
</code>```

Body:
I have a step function where I want to start by getting the resourceArn for an ECS Cluster and then invoke tasks on that cluster.

However, I'm having difficulty dynamically passing the arn from step to step.

{
 "StartAt": "GetArnLambda",
 "States": {
   "GetArnLambda": {
     "Type": "Task",
     "Resource": "arn:aws:lambda:us-east-1:AWS_ACCOUNT_ID:function:FUNCTION_NAME",
     "Next": "ecs_task"
   },
   "ecs_task": {
     "Type": "Task",
     "Resource": "arn:aws:states:::ecs:runTask.sync",
     "Parameters": {
                "Cluster": "$.arn",
                "TaskDefinition": "ecs_task_def"
            },
     "End": true
    }
}

And I get as output from GetArnLambda

{
  "name": "GetArnLambda",
  "output": {
    "arn": "arn:aws:ecs:us-east-1:AWS_ACCOUNT_ID:cluster/CLUSTER_NAME"
  }
}

But this interprets the Cluster arn as "$.arn". How can I reference the arn I just received from the first task?

Body:
From the documentation:

Use "Parameters" field to create a collection of key-value pairs that are passed as input. The values of each can either be static values that you include in your state machine definition, or selected from either the input or the context object with a path. For key-value pairs where the value is selected using a path, the key name must end in .$.

So I think you need:

 "Parameters": {
            "Cluster.$": "$.arn",
            "TaskDefinition": "ecs_task_def"
        },


问:
How to Have Lots of Moving Widgets in Flutter App
I know there are game/sprite engines written for Flutter, but my goal is to better understand painting and widgets, so I want to do this myself.

If I wanted a bunch of small widgets that could move around on a gameboard, what would be the best way to do this? Would I just create a box widget with fixed dimensions and have a bunch of children where I could control their position?

One example would be having a playing area with scrabble tiles that could be moved around.  Or Tetris blocks falling.  Different widgets that can be anywhere and that can be moved.  I'm just looking for someone to point me in the right direction.  Thanks.

答:
You can draw custom shapes and lines using canvas in flutter and then animate them as flutter supports 60 frames per second. You need to understand customPaint very well. Here is a great demonstration of how to use customPaint to draw custom shapes.

https://medium.com/@rjstech/flutter-custom-paint-tutorial-build-a-radial-progress-6f80483494df


问:
Group a dataframe by a column and concactenate strings in another
I know this should be easy but it's driving me mad...

I am trying to turn a dataframe into a grouped dataframe.

df outputs:

```<code>    Postcode    Borough             Neighbourhood
0   M3A         North York          Parkwoods
1   M4A         North York          Victoria Village
2   M5A         Downtown Toronto    Harbourfront
3   M5A         Downtown Toronto    Regent Park
4   M6A         North York          Lawrence Heights
5   M6A         North York          Lawrence Manor
6   M7A         Queen's Park        Not assigned
7   M9A         Etobicoke           Islington Avenue
8   M1B         Scarborough         Rouge
9   M1B         Scarborough         Malvern
10  M3B         North York          Don Mills North
...
</code>```

I want to make a grouped dataframe where the Neighbourhood is grouped by Postcode and all neighborhoods then become a concatenated string of Neighbourhoods as grouped by Postcode...
something like:

```<code>    Postcode    Borough             Neighbourhood
0   M3A         North York          Parkwoods
1   M4A         North York          Victoria Village
2   M5A         Downtown Toronto    Harbourfront, Regent Park
...
</code>```

I am trying to use:

df.groupby(['Postcode'])['Neighbourhood'].apply(lambda strs: ', '.join(strs))

But this does not return a new dataframe .. it outputs the same original dataframe when I use df after running.

if I use:

df = df.groupby(['Postcode'])['Neighbourhood'].apply(lambda strs: ', '.join(strs))

it turns df into an object?

答:
Use this code

```<code>new_df = df.groupby(['Postcode', 'Borough']).agg({'Neighbourhood':lambda x:', '.join(x)}).reset_index()
</code>```

reset_index() will take your group by columns out of the index and return it as a column to the dataframe and create a new integer index.

Body:
I know this should be easy but it's driving me mad...

I am trying to turn a dataframe into a grouped dataframe.

df outputs:

    Postcode    Borough             Neighbourhood
0   M3A         North York          Parkwoods
1   M4A         North York          Victoria Village
2   M5A         Downtown Toronto    Harbourfront
3   M5A         Downtown Toronto    Regent Park
4   M6A         North York          Lawrence Heights
5   M6A         North York          Lawrence Manor
6   M7A         Queen's Park        Not assigned
7   M9A         Etobicoke           Islington Avenue
8   M1B         Scarborough         Rouge
9   M1B         Scarborough         Malvern
10  M3B         North York          Don Mills North
...

I want to make a grouped dataframe where the Neighbourhood is grouped by Postcode and all neighborhoods then become a concatenated string of Neighbourhoods as grouped by Postcode...
something like:

    Postcode    Borough             Neighbourhood
0   M3A         North York          Parkwoods
1   M4A         North York          Victoria Village
2   M5A         Downtown Toronto    Harbourfront, Regent Park
...

I am trying to use:

df.groupby(['Postcode'])['Neighbourhood'].apply(lambda strs: ', '.join(strs))

But this does not return a new dataframe .. it outputs the same original dataframe when I use df after running.

if I use:

df = df.groupby(['Postcode'])['Neighbourhood'].apply(lambda strs: ', '.join(strs))

it turns df into an object?

Body:
Use this code

new_df = df.groupby(['Postcode', 'Borough']).agg({'Neighbourhood':lambda x:', '.join(x)}).reset_index()

reset_index() will take your group by columns out of the index and return it as a column to the dataframe and create a new integer index.


问:
How to redirect html pages internally in Django?
I've included Product and services in Navbar links,
If I click on Product link it should redirect to services page.
I'm Using Django-Oscar. So I don't want to mess around with the urls.py and view.py.</p>

答:
If you don't want to mess with urls and views rather just use javascript. So just add something similar to this on the navlink/navitem.</p>

```<code>onclick="window.location.href = '{% url 'yoururl' %}';"
</code>```

Body:
If you don't want to mess with urls and views rather just use javascript. So just add something similar to this on the navlink/navitem.

onclick="window.location.href = '{% url 'yoururl' %}';"


问:
ArrayList "cannot be resolved" when trying to access an ArrayList in a method, Java
I've created two classes (Team and MarchMadness) to create a MarchMadness bracket in Java. In the MarchMadness class, I've created an ArrayList of type Team for each round and added all the teams for round1. However, I keep getting a "cannot be resolved" error when trying to pull the ArrayList's size and elements in the randomize method.

I've tried moving the ArrayList's outside of the main method, but then I get an error when trying to add teams to the ArrayList. I've also searched online, but haven't found anything.

Here is my code with only the teams for round1 East.

```<code>
public class Team extends MarchMadness {

    private String name;
    private double rating;
    private int seed;

    public Team(String name, double rating, int seed) {
        this.name = name;
        this.rating = rating;
        this.seed = seed;
    }
}

import java.util.ArrayList;
import java.util.List;

public class MarchMadness {

    public static void main(String[] args) {
        ArrayList<Team> round1East = new ArrayList<Team>();

        round1East.add(new Team("Duke", 0.670, 1));
        round1East.add(new Team("North Dakota St", 0.495, 16));
        round1East.add(new Team("VCU", 0.609, 8));
        round1East.add(new Team("UCF", 0.606, 9));
        round1East.add(new Team("Mississippi St", 0.609, 5));
        round1East.add(new Team("Liberty", 0.549, 12));
        round1East.add(new Team("Virginia Tech", 0.605, 4));
        round1East.add(new Team("Saint Louis", 0.547, 13));
        round1East.add(new Team("Maryland", 0.602, 6));
        round1East.add(new Team("Belmont", 0.579, 11));
        round1East.add(new Team("LSU", 0.626, 3));
        round1East.add(new Team("Yale", 0.572, 14));
        round1East.add(new Team("Louisville", 0.594, 7));
        round1East.add(new Team("Minnesota", 0.578, 10));
        round1East.add(new Team("Michigan St", 0.641, 2));
        round1East.add(new Team("Bradley", 0.504, 15));

    }

    private void randomize() {
        if(round2East.isEmpty()) {
            for(int i = 0; i < round1East.size(); i += 2) {
                int x = (int)(Math.random() * 2);
                if(x == 0) {
                    round2East.add(round1East.get(i));
                } else {
                    round2East.add(round1East.get(i++));
                }
            }
     }

}
</code>```

答: You must also try using List  Obj = new ArrayList this allows you to switch between different implementations of the List interface with ease. Polymorphism </p>

Body:
I've created two classes (Team and MarchMadness) to create a MarchMadness bracket in Java. In the MarchMadness class, I've created an ArrayList of type Team for each round and added all the teams for round1. However, I keep getting a "cannot be resolved" error when trying to pull the ArrayList's size and elements in the randomize method.

I've tried moving the ArrayList's outside of the main method, but then I get an error when trying to add teams to the ArrayList. I've also searched online, but haven't found anything.

Here is my code with only the teams for round1 East.

public class Team extends MarchMadness {

    private String name;
    private double rating;
    private int seed;

    public Team(String name, double rating, int seed) {
        this.name = name;
        this.rating = rating;
        this.seed = seed;
    }
}

import java.util.ArrayList;
import java.util.List;

public class MarchMadness {

    public static void main(String[] args) {
        ArrayList<Team> round1East = new ArrayList<Team>();

        round1East.add(new Team("Duke", 0.670, 1));
        round1East.add(new Team("North Dakota St", 0.495, 16));
        round1East.add(new Team("VCU", 0.609, 8));
        round1East.add(new Team("UCF", 0.606, 9));
        round1East.add(new Team("Mississippi St", 0.609, 5));
        round1East.add(new Team("Liberty", 0.549, 12));
        round1East.add(new Team("Virginia Tech", 0.605, 4));
        round1East.add(new Team("Saint Louis", 0.547, 13));
        round1East.add(new Team("Maryland", 0.602, 6));
        round1East.add(new Team("Belmont", 0.579, 11));
        round1East.add(new Team("LSU", 0.626, 3));
        round1East.add(new Team("Yale", 0.572, 14));
        round1East.add(new Team("Louisville", 0.594, 7));
        round1East.add(new Team("Minnesota", 0.578, 10));
        round1East.add(new Team("Michigan St", 0.641, 2));
        round1East.add(new Team("Bradley", 0.504, 15));

    }

    private void randomize() {
        if(round2East.isEmpty()) {
            for(int i = 0; i < round1East.size(); i += 2) {
                int x = (int)(Math.random() * 2);
                if(x == 0) {
                    round2East.add(round1East.get(i));
                } else {
                    round2East.add(round1East.get(i++));
                }
            }
     }

}


问:
tabs/indents blocking code on windows server
I have the following code and it's working great on my local xampp and test linux webhosting:

```<code><?php
// include config file
include('config.php');

// get page intel
$_PAGE = switchPage($_GET);

// require language file
require_once("languages/".$_PAGE['language'].".lang.php");

// include header file
include('includes/header.inc.php');
?>

            <section id="main" class="clearfix">

                <?php
                // include correct page
                include($_PAGE['include_path']);
                ?>

            </section>

<?php
// include footer file
include('includes/footer.inc.php');
?>
</code>```

My client has a windows server with PHP 5.2.6 installed. The hosting company claims that tabs/indents like used in the following snipet out of the code does not work on a windows php hosting.

```<code>            <?php
            // include correct page
            include($_PAGE['include_path']);
            ?>
</code>```

So they claim my code is not valid PHP code.. Can someone advice please? I don't want to rewrite my code just because of all the indents I use to keep my code clean and readable ..

答:
Maybe what is happening is that you are ending each line with line feed character (that's what linux uses) instead of a carriage return + line feed (windows).

If the new line characters are ignored then all the code in a file will end up on one line, causing all kinds of problems (e.g. a comment like '// hello' halfway down a page will end up commenting out all the code that follows).

Try converting the file to windows format (CR+LF). You can do it with a good text editor like Notepad++.

And like others have said, how you indent your code doesn't matter.

Body:
I have the following code and it's working great on my local xampp and test linux webhosting:

<?php
// include config file
include('config.php');

// get page intel
$_PAGE = switchPage($_GET);

// require language file
require_once("languages/".$_PAGE['language'].".lang.php");

// include header file
include('includes/header.inc.php');
?>

                <?php
                // include correct page
                include($_PAGE['include_path']);
                ?>

<?php
// include footer file
include('includes/footer.inc.php');
?>

My client has a windows server with PHP 5.2.6 installed. The hosting company claims that tabs/indents like used in the following snipet out of the code does not work on a windows php hosting.

            <?php
            // include correct page
            include($_PAGE['include_path']);
            ?>

So they claim my code is not valid PHP code.. Can someone advice please? I don't want to rewrite my code just because of all the indents I use to keep my code clean and readable ..


问:
Word frequency elegantly in Powershell
Donald Knuth once got the task to write a literate program computing the word frequency of a file.

Read a file of text, determine the n most frequently used words, and print out a sorted list of those words along with their frequencies.

Doug McIlroy famously rewrote the 10 pages of Pascal in a few lines of sh:

```<code>tr -cs A-Za-z '\n' |
tr A-Z a-z |
sort |
uniq -c |
sort -rn |
sed ${1}q
</code>```

As a little exercise, I converted this to Powershell:

```<code>(-split ((Get-Content -Raw test.txt).ToLower() -replace '[^a-zA-Z]',' ')) |
  Group-Object |
  Sort-Object -Property count -Descending |
  Select-Object -First $Args[0] |
  Format-Table count, name
</code>```

I like that Powershell combines sort | uniq -c into a single Group-Object.

The first line looks ugly, so I wonder if it can be written more elegantly? Maybe there is a way to load the file with a regex delimiter somehow?

One obvious way to shorten the code would be to uses the aliases, but that does not help readability.

答:
Thanks js2010 and LotPings for important hints. To document what is probably the best solution:

```<code>$Input -split '\W+' |
  Group-Object -NoElement |
  Sort-Object count -Descending |
  Select-Object -First $Args[0]
</code>```

Things I learned:

$Input contains stdin. This is closer to McIlroys code than Get-Content some file.

split can actually take regex delimiters

the -NoElement parameter let me get rid of the Format-Table line.

Title: Word frequency elegantly in Powershell

Body:
Donald Knuth once got the task to write a literate program computing the word frequency of a file.

Read a file of text, determine the n most frequently used words, and print out a sorted list of those words along with their frequencies.

Doug McIlroy famously rewrote the 10 pages of Pascal in a few lines of sh:

tr -cs A-Za-z '\n' |
tr A-Z a-z |
sort |
uniq -c |
sort -rn |
sed ${1}q

As a little exercise, I converted this to Powershell:

(-split ((Get-Content -Raw test.txt).ToLower() -replace '[^a-zA-Z]',' ')) |
  Group-Object |
  Sort-Object -Property count -Descending |
  Select-Object -First $Args[0] |
  Format-Table count, name

I like that Powershell combines sort | uniq -c into a single Group-Object.

The first line looks ugly, so I wonder if it can be written more elegantly? Maybe there is a way to load the file with a regex delimiter somehow?

One obvious way to shorten the code would be to uses the aliases, but that does not help readability.

Body:
Thanks js2010 and LotPings for important hints. To document what is probably the best solution:

$Input -split '\W+' |
  Group-Object -NoElement |
  Sort-Object count -Descending |
  Select-Object -First $Args[0]

Things I learned:

$Input contains stdin. This is closer to McIlroys code than Get-Content some file.

split can actually take regex delimiters

the -NoElement parameter let me get rid of the Format-Table line.


问:
Aggregating categorical variables to one variable in python 3 pandas
I have a pandas dataframe with 4 columns. like this

```<code>ID  col1                        col2                col3
1   Strongly Positive   Strongly Positive   Weekly Positive
2   Strongly Positive   Strongly Positive   Neutral
3   Strongly Negative   Strongly Negative   Weekly Negative
4   Weekly Negative      Strongly Negative  Neutral
5   Neutral              Neutral            Neutral
6   Strongly Positive   Strongly Negative   Strongly Negative
7   Strongly Negative   Weekly Positive     Neutral
8   Neutral               Weekly Negative   Weekly Positive
</code>```

Each of the columns can take values like (strongly positive, weekly positive, Neutral, weekly negative and strongly negative and an ID column.
I need to create a new column with these logic

If all the column has positive values or atleast one positive and two neutral values then aggregate that record in the new column as positive

If all the three column has neutral value then flag as neutral

If all the columns have negative values or atleast one negative and two neutral values then flag it as negative

If both positive and negative values are thre then flag it as both
by positive i mean either strong or weekly positive and the same for negative as well.

I need the the final data frame to be like this

```<code>ID  col1                  col2          col3        Aggregated_Col
1   Strongly Positive  Strongly Positive Weekly Positive    Positive
2   Strongly Positive  Strongly Positive Neutral            Positive
3   Strongly Negative  Strongly Negative Weekly Negative    Negative
4   Weekly Negative    Strongly Negative Neutral            Negative
5   Neutral            Neutral       Neutral                Neutral
6   Strongly Positive  Strongly Negative Strongly Negative  Both
7   Strongly Negative  Weekly Positive   Neutral            Both
8   Neutral Weekly     Negative      Weekly Positive        Both
</code>```

Not able to think of a logic

```<code>ID  col1                  col2          col3        Aggregated_Col
1   Strongly Positive  Strongly Positive Weekly Positive    Positive
2   Strongly Positive  Strongly Positive Neutral            Positive
3   Strongly Negative  Strongly Negative Weekly Negative    Negative
4   Weekly Negative    Strongly Negative Neutral            Negative
5   Neutral            Neutral       Neutral            Neutral
6   Strongly Positive  Strongly Negative Strongly Negative  Both
7   Strongly Negative  Weekly Positive   Neutral            Both
8   Neutral Weekly     Negative      Weekly Positive    Both
</code>```

答:
I suggest recoding these values to integers, e.g.

```<code>recode = {"Strongly Positive": 2, "Weakly Positive": 1, "Neutral": 0, "Weakly Negative": -1, "Strongly Negative": -2}
</code>```

Then, you can write a function like this:

```<code>def interpret(values):
  if min(values) >= 0:
    return 1
  elif ...
</code>```

and invoke it using df.apply(interpret, axis=1)

Body:
I have a pandas dataframe with 4 columns. like this

ID  col1                        col2                col3
1   Strongly Positive   Strongly Positive   Weekly Positive
2   Strongly Positive   Strongly Positive   Neutral
3   Strongly Negative   Strongly Negative   Weekly Negative
4   Weekly Negative      Strongly Negative  Neutral
5   Neutral              Neutral            Neutral
6   Strongly Positive   Strongly Negative   Strongly Negative
7   Strongly Negative   Weekly Positive     Neutral
8   Neutral               Weekly Negative   Weekly Positive

Each of the columns can take values like (strongly positive, weekly positive, Neutral, weekly negative and strongly negative and an ID column.
I need to create a new column with these logic

If all the column has positive values or atleast one positive and two neutral values then aggregate that record in the new column as positive

If all the three column has neutral value then flag as neutral

If all the columns have negative values or atleast one negative and two neutral values then flag it as negative

If both positive and negative values are thre then flag it as both
by positive i mean either strong or weekly positive and the same for negative as well.

I need the the final data frame to be like this

ID  col1                  col2          col3        Aggregated_Col
1   Strongly Positive  Strongly Positive Weekly Positive    Positive
2   Strongly Positive  Strongly Positive Neutral            Positive
3   Strongly Negative  Strongly Negative Weekly Negative    Negative
4   Weekly Negative    Strongly Negative Neutral            Negative
5   Neutral            Neutral       Neutral                Neutral
6   Strongly Positive  Strongly Negative Strongly Negative  Both
7   Strongly Negative  Weekly Positive   Neutral            Both
8   Neutral Weekly     Negative      Weekly Positive        Both

Not able to think of a logic

ID  col1                  col2          col3        Aggregated_Col
1   Strongly Positive  Strongly Positive Weekly Positive    Positive
2   Strongly Positive  Strongly Positive Neutral            Positive
3   Strongly Negative  Strongly Negative Weekly Negative    Negative
4   Weekly Negative    Strongly Negative Neutral            Negative
5   Neutral            Neutral       Neutral            Neutral
6   Strongly Positive  Strongly Negative Strongly Negative  Both
7   Strongly Negative  Weekly Positive   Neutral            Both
8   Neutral Weekly     Negative      Weekly Positive    Both

Body:
I suggest recoding these values to integers, e.g.

recode = {"Strongly Positive": 2, "Weakly Positive": 1, "Neutral": 0, "Weakly Negative": -1, "Strongly Negative": -2}

Then, you can write a function like this:

def interpret(values):
  if min(values) >= 0:
    return 1
  elif ...

and invoke it using df.apply(interpret, axis=1)


答:
you can use .split()
string.split([separator])  the separator specifies the character to use for separating the string. </p>

Title: Split file text Angular


问:
How to apply a trained neural network?
[Python 3.7, Tensorflow] I have trained a neural network. Everything works fine, it learns, but once its done learning it just shuts down and the progress is lost. Now what I want to do is to input new data and see by hand, how good the network does.

I already fiddled around with

```<code>saver = tf.train.Saver()
saver.save(sess, 'model/model.ckpt')
</code>```

but that always results in a mile-long error report ending with "Unknown Error: Failed to rename 'model/model.ckpt'" etc.

The code in context looks like this:

```<code>def train_neural_network(x):
    training_data = generate_training_data() # i cut getting training data since its a bit out of context here, but its basically like mnist data

    prediction = neural_network_model(x) # normal, 3-layer feed forward NN
    cost = tf.reduce_mean( tf.square(prediction - y) )
    optimizer = tf.train.AdamOptimizer(0.01).minimize(cost)

    hm_epochs = 10
    saver = tf.train.Saver()

    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())

        for epoch in range(hm_epochs+1):
            epoch_loss = 0

            for i in range(10):
                epoch_x, epoch_y = training_data

                _, c = sess.run([optimizer, cost], feed_dict = {x: epoch_x, y: epoch_y})

        saver.save(sess, 'model/model.ckpt')
</code>```

I try to call this trained neural network in main:

```<code>train_neural_network(x)

X, Y = generate_training_data()

prediction = neural_network_model(x)
saver = tf.train.Saver()

with tf.Session() as sess:

     saver.restore(sess, 'model/model.ckpt')
     result = sess.run(prediction, feed_dict={x: X})

print(Y, result)
</code>```

Its all in one file so far, but I can also do with two seperate files.

This results in an error, which says the usual python error consisting of its path and ends with

"...in _do_call
    raise type(e)(node_def, op, message)"
before a, what I think, Tensorflow-specific error comes up:
"Unknown Error: Failed to rename 'model/model.ckpt'"
and
"Caused by op 'save_13/SaveV2', defined at:",
then theres a long, long path, about 87 lines long,
"Unknown Error" is repeated again.

What I want to have is the printed out label with the from the neural network predicted output. (the print line in the code.)

Unfortunately I have not found anything that works on various internet searches so far, but I feel like it should not be too hard to get this to work.
Thank you in advance.

答:
If you take a look in the folder where your model outputs the checkpoints (/model), you should see 3 separate files per each save: model.ckpt-xxx.data, model.ckpt-xxx.index and model.ckpt-xxx.meta, where xxx is the ID of the checkpoint appended by Tensorflow.

When you want to restore a certain checkpoint, you have to add the ID as well, because typically several checkpoints of the same network are being created during training so that we can re-train the network later if necessary.

So I would take a look in the model folder and double check the file name, my guess is
saver.restore(sess, 'model/model.ckpt-0') would do the trick if you only created one checkpoint.

Title: How to apply a trained neural network?

Body:
[Python 3.7, Tensorflow] I have trained a neural network. Everything works fine, it learns, but once its done learning it just shuts down and the progress is lost. Now what I want to do is to input new data and see by hand, how good the network does.

I already fiddled around with

saver = tf.train.Saver()
saver.save(sess, 'model/model.ckpt')

but that always results in a mile-long error report ending with "Unknown Error: Failed to rename 'model/model.ckpt'" etc.

The code in context looks like this:

def train_neural_network(x):
    training_data = generate_training_data() # i cut getting training data since its a bit out of context here, but its basically like mnist data

    prediction = neural_network_model(x) # normal, 3-layer feed forward NN
    cost = tf.reduce_mean( tf.square(prediction - y) )
    optimizer = tf.train.AdamOptimizer(0.01).minimize(cost)

    hm_epochs = 10
    saver = tf.train.Saver()

    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())

        for epoch in range(hm_epochs+1):
            epoch_loss = 0

            for i in range(10):
                epoch_x, epoch_y = training_data

                _, c = sess.run([optimizer, cost], feed_dict = {x: epoch_x, y: epoch_y})

        saver.save(sess, 'model/model.ckpt')

I try to call this trained neural network in main:

train_neural_network(x)

X, Y = generate_training_data()

prediction = neural_network_model(x)
saver = tf.train.Saver()

with tf.Session() as sess:

     saver.restore(sess, 'model/model.ckpt')
     result = sess.run(prediction, feed_dict={x: X})

print(Y, result)

Its all in one file so far, but I can also do with two seperate files.

This results in an error, which says the usual python error consisting of its path and ends with

"...in _do_call
    raise type(e)(node_def, op, message)"
before a, what I think, Tensorflow-specific error comes up:
"Unknown Error: Failed to rename 'model/model.ckpt'"
and
"Caused by op 'save_13/SaveV2', defined at:",
then theres a long, long path, about 87 lines long,
"Unknown Error" is repeated again.

What I want to have is the printed out label with the from the neural network predicted output. (the print line in the code.)

Unfortunately I have not found anything that works on various internet searches so far, but I feel like it should not be too hard to get this to work.
Thank you in advance.


问:
Laravel Route resource destroy not working
Here is my form :

```<code><form action="{{ route('invoice.destroy' , $invoice->id)}}" method="DELETE">
              <div class="modal-footer no-border">
                <button type="button" class="btn btn-info" data-dismiss="modal">No</button>
                <button type="submit" class="btn btn-primary">Yes</button>
               <input type="hidden" name="_method" value="DELETE" />

              </div>
              </form>
</code>```

Here is my controller :

```<code>public function destroy($id)
{
    $invoice = Invoice::find($id);
    if(!$invoice){
        return redirect()->route('invoice.index')->with(['fail' => 'Page not found !']);
    }
    $invoice->delete();
    return redirect()->route('invoice.index')->with(['success' => 'Invoice Deleted.']);
}
</code>```

But it can not delete where is the problem ? How solve this ?

答:
Also, if you are using blade templates, you can add the method field like so:
@method('DELETE')</p>

Body:
Here is my form :

<form action="{{ route('invoice.destroy' , $invoice->id)}}" method="DELETE">

                <button type="button" class="btn btn-info" data-dismiss="modal">No</button>
                <button type="submit" class="btn btn-primary">Yes</button>
               <input type="hidden" name="_method" value="DELETE" />

              </form>

Here is my controller :

public function destroy($id)
{
    $invoice = Invoice::find($id);
    if(!$invoice){
        return redirect()->route('invoice.index')->with(['fail' => 'Page not found !']);
    }
    $invoice->delete();
    return redirect()->route('invoice.index')->with(['success' => 'Invoice Deleted.']);
}

But it can not delete where is the problem ? How solve this ?


问:
Is there a way to overload an abstract method in a functional interface?
I would like to be able to provide a functional interface that accepts several different types of lambda functions.

I read this. The first answer to this question clarifies why overloading an abstract method in a functional interface could cause undefined behavior. However, is there a way to do the equivalent of overloading an abstract method in a functional interface if I supply all of the defaults?

I would like to be able to write something like the following code:

Ball b = () -> System.out.println("You hit it!");
Ball ba = (boolean miss) -> System.out.println(miss);

b.hit();
b.hit(false);
ba.hit();
ba.hit(false);
```

<p>The desired result would be:</p>

```You hit it!
default false
default hit
false
```

<p>Consider the following (non-compilable) code (mostly copied from the linked question):</p>

```@FunctionalInterface
public interface Ball
{
    void hit();
    void hit(boolean miss);
    default void hit(){
        System.out.println("default hit");
    }
    default void hit(boolean miss){
        System.out.println("default" + miss);
    }

}
```

I am looking for an alternative to this code that would compile.

答:
You could do something like this.  But you would need to name your variables properly to keep track of both the arg and the consumer that takes it.

```<code>@FunctionalInterface
interface Ball<T> {
   void hit();

   static <T> Ball<T> withArg(T arg, Consumer<T> com) {
      return () -> com.accept(arg);
   }
}

public class Demo {
   public static void main(String[] args) {
      Ball<Boolean> b = () -> System.out.println("You Hit it!");
      b.hit();
      Ball<Boolean> ba = Ball.withArg(false, a -> System.out.println(a));
      Ball<Boolean> bb = Ball.withArg(true, a -> System.out.println(a));
      ba.hit();
      bb.hit();
   }
}
</code>```

Body:
I would like to be able to provide a functional interface that accepts several different types of lambda functions.

I read this. The first answer to this question clarifies why overloading an abstract method in a functional interface could cause undefined behavior. However, is there a way to do the equivalent of overloading an abstract method in a functional interface if I supply all of the defaults?

I would like to be able to write something like the following code:

Ball b = () -> System.out.println("You hit it!");
Ball ba = (boolean miss) -> System.out.println(miss);

b.hit();
b.hit(false);
ba.hit();
ba.hit(false);

The desired result would be:

You hit it!
default false
default hit
false

Consider the following (non-compilable) code (mostly copied from the linked question):

@FunctionalInterface
public interface Ball
{
    void hit();
    void hit(boolean miss);
    default void hit(){
        System.out.println("default hit");
    }
    default void hit(boolean miss){
        System.out.println("default" + miss);
    }

}

I am looking for an alternative to this code that would compile.

Body:
You could do something like this.  But you would need to name your variables properly to keep track of both the arg and the consumer that takes it.

@FunctionalInterface
interface Ball<T> {
   void hit();

   static <T> Ball<T> withArg(T arg, Consumer<T> com) {
      return () -> com.accept(arg);
   }
}

public class Demo {
   public static void main(String[] args) {
      Ball<Boolean> b = () -> System.out.println("You Hit it!");
      b.hit();
      Ball<Boolean> ba = Ball.withArg(false, a -> System.out.println(a));
      Ball<Boolean> bb = Ball.withArg(true, a -> System.out.println(a));
      ba.hit();
      bb.hit();
   }
}


问:
Do Godot signals act as event handlers?
I am a beginner at Godot game development. I am having some difficulties in understanding what a signal in Godot is. I have looked at the official documentation, but could not understand well. However, I am getting a feeling that these signals are some kind of event handler.

Please, help me to understand what a signal in godot is and whether my understanding of signals as event handlers is correct or not?

答:
You are correct, a signal is an event that you can emit from a Node.

```<code>emit_signal("signalName") #emit's signal with no data
emit_signal("signalName", whateverDataToSend) #emit's signal with data
</code>```

You can then register to receive notifications when the signal is fired, hence connect to a signal.

nodeWithSignalInIt.connect( String signalName, Object target, String methodToCall)

Note: connect needs to be called from a node that has the signal inside of it

It's also worth noting that signals can be found all over Nodes we use in Godot, for example, if you want to get notified of a collision entry on Area2D then just connect to that Area2D's area_entered signal.

Example:

```<code>func _ready() -> void:
        #NOTE: InteractiveArea is of type Area2D
        $InteractiveArea.connect("mouse_entered", self, "_on_mouse_entered")
        $InteractiveArea.connect("mouse_exited", self, "_on_mouse_exited")
        $InteractiveArea.connect("area_entered", self, "_on_player_entered")
        $InteractiveArea.connect("area_exited", self, "_on_player_exited")

func _on_mouse_entered() -> void:
    mouse_entered = true

func _on_mouse_exited() -> void:
    mouse_entered = false

func _on_player_entered(area: Area2D) -> void:
    print ("Player entered chest opening zone.")
    interaction_zone = true;

func _on_player_exited(area: Area2D) -> void:
    print ("Player exited chest opening zone.")
    interaction_zone = false
</code>```

Title: Do Godot signals act as event handlers?

Body:
You are correct, a signal is an event that you can emit from a Node.

emit_signal("signalName") #emit's signal with no data
emit_signal("signalName", whateverDataToSend) #emit's signal with data

You can then register to receive notifications when the signal is fired, hence connect to a signal.

nodeWithSignalInIt.connect( String signalName, Object target, String methodToCall)

Note: connect needs to be called from a node that has the signal inside of it

It's also worth noting that signals can be found all over Nodes we use in Godot, for example, if you want to get notified of a collision entry on Area2D then just connect to that Area2D's area_entered signal.

Example:

func _ready() -> void:
        #NOTE: InteractiveArea is of type Area2D
        $InteractiveArea.connect("mouse_entered", self, "_on_mouse_entered")
        $InteractiveArea.connect("mouse_exited", self, "_on_mouse_exited")
        $InteractiveArea.connect("area_entered", self, "_on_player_entered")
        $InteractiveArea.connect("area_exited", self, "_on_player_exited")

func _on_mouse_entered() -> void:
    mouse_entered = true

func _on_mouse_exited() -> void:
    mouse_entered = false

func _on_player_entered(area: Area2D) -> void:
    print ("Player entered chest opening zone.")
    interaction_zone = true;

func _on_player_exited(area: Area2D) -> void:
    print ("Player exited chest opening zone.")
    interaction_zone = false


问:
Connect localdb from production database
I have a local db server like:

```<code>(LocalDB)\MSSQLLocalDB
</code>```

As other questions solution to access to other server from main server is to do something like:

```<code>myserver.mydatabase.dbo.mytable
</code>```

So I try:

```<code>SELECT *
FROM (LocalDB)\MSSQLLocalDB.mydatabase.dbo.mytable
</code>```

But it throws an error:

Msg 102, Level 15, State 1, Line 3

  Incorrect syntax near ')'.

What is the correct way to connect to local server database? Regards

答:
It is not possible to connect to a localDB from a different server.

If you need such connections you will be better with installing SQL Server Developer edition on a dev box.

Body:
I have a local db server like:

(LocalDB)\MSSQLLocalDB

As other questions solution to access to other server from main server is to do something like:

myserver.mydatabase.dbo.mytable

So I try:

SELECT *
FROM (LocalDB)\MSSQLLocalDB.mydatabase.dbo.mytable

But it throws an error:

Msg 102, Level 15, State 1, Line 3

  Incorrect syntax near ')'.

What is the correct way to connect to local server database? Regards


问:
How can I create a runnable JAR file with Maven + JavaFX
I going to create a runnable JAR file inside Eclipse IDE. All my dependencies are from Maven. In Eclipse I'm creating a JavaFX GUI application for desktop.

The problem is that when I creating the runnable JAR file. I got this error.

The error is very clear.

Jar export finished with problems. See details for additional
  information.   Could not find main method from given launch
  configuration.

But what is main method? Is it the public static void main(String[] args) method here?

What should I do to solve this?

```<code>package se.danielmartensson.start;

import java.util.Optional;

import javafx.application.Application;
import javafx.application.Platform;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.ButtonType;
import javafx.stage.Stage;
import se.danielmartensson.concurrency.Measureing;

public class Main extends Application{

    /*
     * Start the start(Stage front)
     */
    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage front) throws Exception {
        front.setOnCloseRequest(e->{
            e.consume();
            askForClosing();
        });
        Parent root = FXMLLoader.load(getClass().getResource("/se/danielmartensson/fxml/front.fxml"));
        Scene scene = new Scene(root);
        front.setScene(scene);
        front.setTitle("JUBSPlotter");
        front.show();
    }

    private void askForClosing() {
        Alert question = new Alert(AlertType.CONFIRMATION);
        question.setTitle("Closing");
        question.setHeaderText("Do you want to close?");
        question.setResizable(false);
        question.setContentText("Press OK to close.");
        Optional<ButtonType> answer = question.showAndWait();
        if(answer.get() == ButtonType.OK) {
            Measureing.active = false;
            Platform.exit();
        }

    }

}
</code>```

答:
You have to use the following maven plugin to create a runnable jar file.

```<code><plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <configuration>
                    <archive>
                        <manifest>
                            <mainClass>
                                com.ddlab.rnd.App
                            </mainClass>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>
</code>```

This is for very simple project where you want to learn about how to create an executable jar file to run.
To have a good idea about how to create a runnable/executable jar file, check this github link.
https://github.com/debjava/runnableJar
If you have other libraries to use as part of your application. You have to create fat jar file. To create a fat jar file, you have to use Maven Shade plugin. Find below the link for maven shade plugin.

https://maven.apache.org/plugins/maven-shade-plugin/

Body:
I going to create a runnable JAR file inside Eclipse IDE. All my dependencies are from Maven. In Eclipse I'm creating a JavaFX GUI application for desktop.

The problem is that when I creating the runnable JAR file. I got this error.

The error is very clear.

Jar export finished with problems. See details for additional
  information.   Could not find main method from given launch
  configuration.

But what is main method? Is it the public static void main(String[] args) method here?

What should I do to solve this?

package se.danielmartensson.start;

import java.util.Optional;

import javafx.application.Application;
import javafx.application.Platform;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.ButtonType;
import javafx.stage.Stage;
import se.danielmartensson.concurrency.Measureing;

public class Main extends Application{

    /*
     * Start the start(Stage front)
     */
    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage front) throws Exception {
        front.setOnCloseRequest(e->{
            e.consume();
            askForClosing();
        });
        Parent root = FXMLLoader.load(getClass().getResource("/se/danielmartensson/fxml/front.fxml"));
        Scene scene = new Scene(root);
        front.setScene(scene);
        front.setTitle("JUBSPlotter");
        front.show();
    }

    private void askForClosing() {
        Alert question = new Alert(AlertType.CONFIRMATION);
        question.setTitle("Closing");
        question.setHeaderText("Do you want to close?");
        question.setResizable(false);
        question.setContentText("Press OK to close.");
        Optional<ButtonType> answer = question.showAndWait();
        if(answer.get() == ButtonType.OK) {
            Measureing.active = false;
            Platform.exit();
        }

    }

}

Body:
You have to use the following maven plugin to create a runnable jar file.

<plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <configuration>
                    <archive>
                        <manifest>
                            <mainClass>
                                com.ddlab.rnd.App
                            </mainClass>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>

This is for very simple project where you want to learn about how to create an executable jar file to run.
To have a good idea about how to create a runnable/executable jar file, check this github link.
https://github.com/debjava/runnableJar
If you have other libraries to use as part of your application. You have to create fat jar file. To create a fat jar file, you have to use Maven Shade plugin. Find below the link for maven shade plugin.

https://maven.apache.org/plugins/maven-shade-plugin/


问:
Understanding the types of functions
I am trying to understand the types of functions and being able to explain them.

Two functions:

```<code>insert :: t -> Bool -> ([t],[t]) -> ([t],[t])
insert a True (b,c) = (a:b,c)
insert a False (b,c) = (b,a:c)

partition :: (t -> Bool) -> [t] -> ([t],[t])
partition p [] = ([],[])
partition p (x : xs) = insert x (p x) (partition p xs)
</code>```

From my limited knowledge I think that insert function:

insert is of type t, it takes two arguments one of bool and one of a tuple of two lists of type t and returns a tuple of two lists of type t.

partition is a tuple of type t which returns a bool, and it takes a list of type t as it's argument and returns a tuple of two lists of type t.

Is that the right way of thinking about it or am I getting it wrong? I have been following some tutorials and this is what I've u   nderstood so far.

答:
No, the types are exactly as shown:

insert has type t -> Bool -> ([t], [t]) -> ([t], [t]), which means it is a function that takes a value of type t as an argument and returns a function of type Bool -> ([t], [t]) -> ([t], [t]). Informally, you can think of insert as a function that takes 3 arguments: one of type t, one of type Bool, and one of type ([t], [t]), and returns another value of type ([t], [t]).

partition is a function that takes another function (of type t -> Bool) as its argument, and returns a function of type [t] -> ([t],[t]). Again informally, you can think of partition as taking two arguments (of type t -> Bool and type [t]) and returning a value of type ([t], [t]).

-> itself is a type-level operator; it takes two types as arguments and returns a function type. It is right-associative, which means a -> (b -> c) and a -> b -> c are equivalent.

Title: Understanding the types of functions

Body:
I am trying to understand the types of functions and being able to explain them.

Two functions:

insert :: t -> Bool -> ([t],[t]) -> ([t],[t])
insert a True (b,c) = (a:b,c)
insert a False (b,c) = (b,a:c)

partition :: (t -> Bool) -> [t] -> ([t],[t])
partition p [] = ([],[])
partition p (x : xs) = insert x (p x) (partition p xs)

From my limited knowledge I think that insert function:

insert is of type t, it takes two arguments one of bool and one of a tuple of two lists of type t and returns a tuple of two lists of type t.

partition is a tuple of type t which returns a bool, and it takes a list of type t as it's argument and returns a tuple of two lists of type t.

Is that the right way of thinking about it or am I getting it wrong? I have been following some tutorials and this is what I've u   nderstood so far.


问:
SSRS using vbcrlf in TextBox to Concatenate field need exclude blank return line
I've created an SSRS report to print per address.

I am using vbcrlf to concatenate multiple fields in one text box.

On some occurrences, one of the fields with in the concatenate might be null.  If this is the case, the line returned creates a blank line within my textbox.

Is there a way to remove the blank line break?

```<code>=Fields!SOP10200_ADDRESS1.Value & vbcrlf & Fields!SOP10200_ADDRESS2.Value & vbcrlf & TRIM(Fields!SOP10200_CITY.Value) & "," & TRIM(Fields!SOP10200_STATE.Value) & " " & TRIM(Fields!SOP10200_ZIPCODE.Value)
</code>```

Expected Results:

4349 Green Ash Dr.
 Earth City,MO 63045

Actual Results:

4349 Green Ash Dr.

                                                                                Earth City,MO 63045

答:
Thank you Hannover.  I had to change it slightly and then it worked!</p>

```<code>=Fields!SOP10200_ADDRESS1.Value & vbcrlf &
IIF(ISNOTHING(Fields!SOP10200_ADDRESS2.Value)
OR Fields!SOP10200_ADDRESS2.Value = "",vbcrlf,"")
 & TRIM(Fields!SOP10200_CITY.Value) & "," & TRIM(Fields!SOP10200_STATE.Value)
 & " " & TRIM(Fields!SOP10200_ZIPCODE.Value)
</code>```

Body:
I've created an SSRS report to print per address.

I am using vbcrlf to concatenate multiple fields in one text box.

On some occurrences, one of the fields with in the concatenate might be null.  If this is the case, the line returned creates a blank line within my textbox.

Is there a way to remove the blank line break?

=Fields!SOP10200_ADDRESS1.Value & vbcrlf & Fields!SOP10200_ADDRESS2.Value & vbcrlf & TRIM(Fields!SOP10200_CITY.Value) & "," & TRIM(Fields!SOP10200_STATE.Value) & " " & TRIM(Fields!SOP10200_ZIPCODE.Value)

Expected Results:

4349 Green Ash Dr.
 Earth City,MO 63045

Actual Results:

4349 Green Ash Dr.

                                                                                Earth City,MO 63045

Body:
Thank you Hannover.  I had to change it slightly and then it worked!

=Fields!SOP10200_ADDRESS1.Value & vbcrlf &
IIF(ISNOTHING(Fields!SOP10200_ADDRESS2.Value)
OR Fields!SOP10200_ADDRESS2.Value = "",vbcrlf,"")
 & TRIM(Fields!SOP10200_CITY.Value) & "," & TRIM(Fields!SOP10200_STATE.Value)
 & " " & TRIM(Fields!SOP10200_ZIPCODE.Value)


问:
Only extract those words from a list that include no repeating letters, using regex
I have a large word list file with one word per line. I would like to filter out the words with repeating alphabets.

```<code>INPUT:
  abducts
  abe
  abeam
  abel
  abele

OUTPUT:
  abducts
  abe
  abel
</code>```

I'd like to do this using Regex (grep or perl or python). Is that possible?

答:
cjm gave the regex, but here's an interesting non-regex way:</p>

```<code>@words = qw/abducts abe abeam abel abele/;
for my $word (@words) {
    my $mask1 = $word x ( length($word) - 1 );
    my $mask2 = join( '', map { substr($word, $_), substr($word, 0, $_) } 1..length($word)-1 );
    if ( ( $mask1 ^ $mask2 ) !~ tr/\0// ) {
        print "$word\n";
    }
}
</code>```

Body:
I have a large word list file with one word per line. I would like to filter out the words with repeating alphabets.

INPUT:
  abducts
  abe
  abeam
  abel
  abele

OUTPUT:
  abducts
  abe
  abel

I'd like to do this using Regex (grep or perl or python). Is that possible?

Body:
cjm gave the regex, but here's an interesting non-regex way:

@words = qw/abducts abe abeam abel abele/;
for my $word (@words) {
    my $mask1 = $word x ( length($word) - 1 );
    my $mask2 = join( '', map { substr($word, $_), substr($word, 0, $_) } 1..length($word)-1 );
    if ( ( $mask1 ^ $mask2 ) !~ tr/\0// ) {
        print "$word\n";
    }
}


问:
Merge dataframes inside a function
I have two dataframes and want to merge them inside a function.

```<code>df = pd.DataFrame(data={'col1': [1, 2], 'A': ['A', 'A']})
df_temp = pd.DataFrame(data={'col1': [1, 2], 'B': ['B', 'B']})

def func(df):

    dx = df.merge(df_temp, how='left', left_on='col1', right_on='col1')
    return dx

df.pipe(func)
print(df)
</code>```

Result:

```<code>pd.DataFrame(data={'col1': [1, 2], 'A': ['A', 'A']})
</code>```

I get the same original df as a result. The column B from df_temp is not being added to the dataframe df as I am expecting. Why this does not work?

答:
You forgot to assign df to the result of the pipe applied function (func).</p>

```<code>OLD:  df.pipe(func)

NEW:  df=df.pipe(func)
</code>```

Title: Merge dataframes inside a function

Body:
I have two dataframes and want to merge them inside a function.

df = pd.DataFrame(data={'col1': [1, 2], 'A': ['A', 'A']})
df_temp = pd.DataFrame(data={'col1': [1, 2], 'B': ['B', 'B']})

def func(df):

    dx = df.merge(df_temp, how='left', left_on='col1', right_on='col1')
    return dx

df.pipe(func)
print(df)

Result:

pd.DataFrame(data={'col1': [1, 2], 'A': ['A', 'A']})

I get the same original df as a result. The column B from df_temp is not being added to the dataframe df as I am expecting. Why this does not work?

Body:
You forgot to assign df to the result of the pipe applied function (func).

OLD:  df.pipe(func)

NEW:  df=df.pipe(func)


问:
Create a 2d array/list in python 3 based on only one number to create a blank matrix
I am attempting to create a 2D array/list that can dynamically change based on one number, so say I input the number 3, it would create a 2d array like this, with three rows and three columns. inputting 10 would create an array with 10 columns and 10 rows, etc.

```<code>array = [
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]
]
</code>```

I have researched quite a bit on both google and stack overflow, neither have turned up results that actually help me a whole lot.

what I have at the moment is a function that takes one parameter (numberOfCells) and uses for loops to attempt to fill the array, it returns TypeError: 'int' object is not iterable, so I am open to suggestions to implement this in other ways

both of the chunks of code below will be creating a new cell using this class

class Cell:

    def __init__(self, id):
        self.infected = False
        self.dead = False
        self.id = id

    def printId(self):
        print(self.id)
```

<p><br><hr><br></p>

<pre class="lang-py prettyprint-override"><code>def createTestingEnv(numberOfCells):
    # creates a simulated cell tissue
    row = list(range(numberOfCells + 1))  # +1 because range uses < not <=
    column = numberOfCells
    env = [[]]
    for i in range(numberOfCells):
        for j in range(numberOfCells):
            env.append(list(i))

    # env = list([row] * column)  # create a 2D array/list based on number of cells
    print(env)

createTestingEnv(3)
</code>```

(above) this code returns an error, so i don't know if this is the right approach.

(below) this code sort of works, but it doesn't produce the result that I would like

def createTestingEnv(numberOfCells):
    # creates a simulated cell tissue
    row = list(range(numberOfCells + 1))  # +1 because range uses < not <=
    column = numberOfCells
    env = list([row] * column)  # create a 2D array/list based on number of cells
    for i in range(numberOfCells):
        for j in range(numberOfCells):
            k = Cell(i + j)
            k.printId()

createTestingEnv(10)
```

I'm new to python, is there something I should be doing differently?
or am I taking a totally wrong approach to this? If so, how should i go about doing this?

Thanks, Asher

答:
If the arrays need to be filled with 0's, this should work:</p>

```<code>def createTestingEnv(numberOfCells):
   holder = []
   env = []
   for i in range(numberOfCells):
      holder.append(0)
   for i in range(numberOfCells):
      env.append(holder)

   print(env)
</code>```

Body:
I am attempting to create a 2D array/list that can dynamically change based on one number, so say I input the number 3, it would create a 2d array like this, with three rows and three columns. inputting 10 would create an array with 10 columns and 10 rows, etc.

array = [
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]
]

I have researched quite a bit on both google and stack overflow, neither have turned up results that actually help me a whole lot.

what I have at the moment is a function that takes one parameter (numberOfCells) and uses for loops to attempt to fill the array, it returns TypeError: 'int' object is not iterable, so I am open to suggestions to implement this in other ways

both of the chunks of code below will be creating a new cell using this class

class Cell:

    def __init__(self, id):
        self.infected = False
        self.dead = False
        self.id = id

    def printId(self):
        print(self.id)

def createTestingEnv(numberOfCells):
    # creates a simulated cell tissue
    row = list(range(numberOfCells + 1))  # +1 because range uses < not <=
    column = numberOfCells
    env = [[]]
    for i in range(numberOfCells):
        for j in range(numberOfCells):
            env.append(list(i))

    # env = list([row] * column)  # create a 2D array/list based on number of cells
    print(env)

createTestingEnv(3)

(above) this code returns an error, so i don't know if this is the right approach.

(below) this code sort of works, but it doesn't produce the result that I would like

def createTestingEnv(numberOfCells):
    # creates a simulated cell tissue
    row = list(range(numberOfCells + 1))  # +1 because range uses < not <=
    column = numberOfCells
    env = list([row] * column)  # create a 2D array/list based on number of cells
    for i in range(numberOfCells):
        for j in range(numberOfCells):
            k = Cell(i + j)
            k.printId()

createTestingEnv(10)

I'm new to python, is there something I should be doing differently?
or am I taking a totally wrong approach to this? If so, how should i go about doing this?

Thanks, Asher

Body:
If the arrays need to be filled with 0's, this should work:

def createTestingEnv(numberOfCells):
   holder = []
   env = []
   for i in range(numberOfCells):
      holder.append(0)
   for i in range(numberOfCells):
      env.append(holder)

   print(env)


问:
error CS0234: The type or namespace name 'VisualStudio' does not exist in the namespace 'Microsoft' (are you missing an assembly reference?
I am using Visual Studio 2015 professional edition to run some test cases on my local machine. I am able to build the solution & run test cases locally.

When I build my application on TeamCity server (build agent is also hosted on team city server), I am getting following errors:

```<code>Controllers\OneControllerTest.cs(5, 17): error CS0234: The type or namespace name 'VisualStudio' does not exist in the namespace 'Microsoft' (are you missing an assembly reference?)
Controllers\LandingControllerTest.cs(2, 17): error CS0234: The type or namespace name 'VisualStudio' does not exist in the namespace 'Microsoft' (are you missing an assembly reference?)
Controllers\TwoControllerTest.cs(5, 17): error CS0234: The type or namespace name 'VisualStudio' does not exist in the namespace 'Microsoft' (are you missing an assembly reference?)
Controllers\OneControllerTest.cs(15, 10): error CS0118: 'My_api.Test.OneControllerTest.TestInitialize()' is a 'method' but is used like a 'type'
Controllers\OneControllerTest.cs(15, 10): error CS0246: The type or namespace name 'TestInitializeAttribute' could not be found (are you missing a using directive or an assembly reference?)
Controllers\OneControllerTest.cs(22, 10): error CS0246: The type or namespace name 'TestMethod' could not be found (are you missing a using directive or an assembly reference?)
Controllers\OneControllerTest.cs(22, 10): error CS0246: The type or namespace name 'TestMethodAttribute' could not be found (are you missing a using directive or an assembly reference?)
Controllers\OneControllerTest.cs(39, 10): error CS0246: The type or namespace name 'TestMethod' could not be found (are you missing a using directive or an assembly reference?)
Controllers\OneControllerTest.cs(39, 10): error CS0246: The type or namespace name 'TestMethodAttribute' could not be found (are you missing a using directive or an assembly reference?)
Controllers\OneControllerTest.cs(40, 10): error CS0246: The type or namespace name 'ExpectedException' could not be found (are you missing a using directive or an assembly reference?)
Controllers\OneControllerTest.cs(40, 10): error CS0246: The type or namespace name 'ExpectedExceptionAttribute' could not be found (are you missing a using directive or an assembly reference?)
Controllers\OneControllerTest.cs(11, 6): error CS0246: The type or namespace name 'TestClass' could not be found (are you missing a using directive or an assembly reference?)
Controllers\OneControllerTest.cs(11, 6): error CS0246: The type or namespace name 'TestClassAttribute' could not be found (are you missing a using directive or an assembly reference?)
Controllers\LandingControllerTest.cs(10, 10): error CS0246: The type or namespace name 'TestMethod' could not be found (are you missing a using directive or an assembly reference?)
Controllers\LandingControllerTest.cs(10, 10): error CS0246: The type or namespace name 'TestMethodAttribute' could not be found (are you missing a using directive or an assembly reference?)
Controllers\LandingControllerTest.cs(7, 6): error CS0246: The type or namespace name 'TestClass' could not be found (are you missing a using directive or an assembly reference?)
Controllers\LandingControllerTest.cs(7, 6): error CS0246: The type or namespace name 'TestClassAttribute' could not be found (are you missing a using directive or an assembly reference?)
Controllers\TwoControllerTest.cs(18, 10): error CS0118: 'My_api.Test.Controllers.TwoControllerTest.TestInitialize()' is a 'method' but is used like a 'type'
Controllers\TwoControllerTest.cs(18, 10): error CS0246: The type or namespace name 'TestInitializeAttribute' could not be found (are you missing a using directive or an assembly reference?)
Controllers\TwoControllerTest.cs(44, 10): error CS0246: The type or namespace name 'TestMethod' could not be found (are you missing a using directive or an assembly reference?)
Controllers\TwoControllerTest.cs(44, 10): error CS0246: The type or namespace name 'TestMethodAttribute' could not be found (are you missing a using directive or an assembly reference?)
Controllers\TwoControllerTest.cs(60, 10): error CS0246: The type or namespace name 'TestMethod' could not be found (are you missing a using directive or an assembly reference?)
Controllers\TwoControllerTest.cs(60, 10): error CS0246: The type or namespace name 'TestMethodAttribute' could not be found (are you missing a using directive or an assembly reference?)
Controllers\TwoControllerTest.cs(13, 6): error CS0246: The type or namespace name 'TestClass' could not be found (are you missing a using directive or an assembly reference?)
Controllers\TwoControllerTest.cs(13, 6): error CS0246: The type or namespace name 'TestClassAttribute' could not be found (are you missing a using directive or an assembly reference?)
</code>```

I am using following nuget packages:

```<code><packages>
  <package id="Castle.Core" version="4.2.1" targetFramework="net45" />
  <package id="Microsoft.AspNet.WebApi.Core" version="5.2.3" targetFramework="net45" />
  <package id="Microsoft.UnitTestFramework.Extensions" version="2.0.0" targetFramework="net45" />
  <package id="Moq" version="4.8.0" targetFramework="net45" />
  <package id="MSTest.TestAdapter" version="1.3.2" targetFramework="net45" />
  <package id="MSTest.TestFramework" version="1.3.2" targetFramework="net45" />
  <package id="Newtonsoft.Json" version="9.0.1" targetFramework="net45" />
  <package id="System.Diagnostics.Contracts" version="4.0.1" targetFramework="net45" />
  <package id="System.Threading.Tasks.Extensions" version="4.4.0" targetFramework="net45" />
  <package id="System.ValueTuple" version="4.4.0" targetFramework="net45" />
  <package id="Unity.AspNet.WebApi" version="4.0.1" targetFramework="net452" />
</packages>
</code>```

My team city server box has .net framework 4.0 installed on it. I am trying to avoid installing Visual Studio on team city server,

What could be the reason for this error?

答:
For VS 2019, I had to change the Target Framework.

From target framework 4 to 4.6(last version)

Body:
I am using Visual Studio 2015 professional edition to run some test cases on my local machine. I am able to build the solution & run test cases locally.

When I build my application on TeamCity server (build agent is also hosted on team city server), I am getting following errors:

Controllers\OneControllerTest.cs(5, 17): error CS0234: The type or namespace name 'VisualStudio' does not exist in the namespace 'Microsoft' (are you missing an assembly reference?)
Controllers\LandingControllerTest.cs(2, 17): error CS0234: The type or namespace name 'VisualStudio' does not exist in the namespace 'Microsoft' (are you missing an assembly reference?)
Controllers\TwoControllerTest.cs(5, 17): error CS0234: The type or namespace name 'VisualStudio' does not exist in the namespace 'Microsoft' (are you missing an assembly reference?)
Controllers\OneControllerTest.cs(15, 10): error CS0118: 'My_api.Test.OneControllerTest.TestInitialize()' is a 'method' but is used like a 'type'
Controllers\OneControllerTest.cs(15, 10): error CS0246: The type or namespace name 'TestInitializeAttribute' could not be found (are you missing a using directive or an assembly reference?)
Controllers\OneControllerTest.cs(22, 10): error CS0246: The type or namespace name 'TestMethod' could not be found (are you missing a using directive or an assembly reference?)
Controllers\OneControllerTest.cs(22, 10): error CS0246: The type or namespace name 'TestMethodAttribute' could not be found (are you missing a using directive or an assembly reference?)
Controllers\OneControllerTest.cs(39, 10): error CS0246: The type or namespace name 'TestMethod' could not be found (are you missing a using directive or an assembly reference?)
Controllers\OneControllerTest.cs(39, 10): error CS0246: The type or namespace name 'TestMethodAttribute' could not be found (are you missing a using directive or an assembly reference?)
Controllers\OneControllerTest.cs(40, 10): error CS0246: The type or namespace name 'ExpectedException' could not be found (are you missing a using directive or an assembly reference?)
Controllers\OneControllerTest.cs(40, 10): error CS0246: The type or namespace name 'ExpectedExceptionAttribute' could not be found (are you missing a using directive or an assembly reference?)
Controllers\OneControllerTest.cs(11, 6): error CS0246: The type or namespace name 'TestClass' could not be found (are you missing a using directive or an assembly reference?)
Controllers\OneControllerTest.cs(11, 6): error CS0246: The type or namespace name 'TestClassAttribute' could not be found (are you missing a using directive or an assembly reference?)
Controllers\LandingControllerTest.cs(10, 10): error CS0246: The type or namespace name 'TestMethod' could not be found (are you missing a using directive or an assembly reference?)
Controllers\LandingControllerTest.cs(10, 10): error CS0246: The type or namespace name 'TestMethodAttribute' could not be found (are you missing a using directive or an assembly reference?)
Controllers\LandingControllerTest.cs(7, 6): error CS0246: The type or namespace name 'TestClass' could not be found (are you missing a using directive or an assembly reference?)
Controllers\LandingControllerTest.cs(7, 6): error CS0246: The type or namespace name 'TestClassAttribute' could not be found (are you missing a using directive or an assembly reference?)
Controllers\TwoControllerTest.cs(18, 10): error CS0118: 'My_api.Test.Controllers.TwoControllerTest.TestInitialize()' is a 'method' but is used like a 'type'
Controllers\TwoControllerTest.cs(18, 10): error CS0246: The type or namespace name 'TestInitializeAttribute' could not be found (are you missing a using directive or an assembly reference?)
Controllers\TwoControllerTest.cs(44, 10): error CS0246: The type or namespace name 'TestMethod' could not be found (are you missing a using directive or an assembly reference?)
Controllers\TwoControllerTest.cs(44, 10): error CS0246: The type or namespace name 'TestMethodAttribute' could not be found (are you missing a using directive or an assembly reference?)
Controllers\TwoControllerTest.cs(60, 10): error CS0246: The type or namespace name 'TestMethod' could not be found (are you missing a using directive or an assembly reference?)
Controllers\TwoControllerTest.cs(60, 10): error CS0246: The type or namespace name 'TestMethodAttribute' could not be found (are you missing a using directive or an assembly reference?)
Controllers\TwoControllerTest.cs(13, 6): error CS0246: The type or namespace name 'TestClass' could not be found (are you missing a using directive or an assembly reference?)
Controllers\TwoControllerTest.cs(13, 6): error CS0246: The type or namespace name 'TestClassAttribute' could not be found (are you missing a using directive or an assembly reference?)

I am using following nuget packages:

<packages>
  <package id="Castle.Core" version="4.2.1" targetFramework="net45" />
  <package id="Microsoft.AspNet.WebApi.Core" version="5.2.3" targetFramework="net45" />
  <package id="Microsoft.UnitTestFramework.Extensions" version="2.0.0" targetFramework="net45" />
  <package id="Moq" version="4.8.0" targetFramework="net45" />
  <package id="MSTest.TestAdapter" version="1.3.2" targetFramework="net45" />
  <package id="MSTest.TestFramework" version="1.3.2" targetFramework="net45" />
  <package id="Newtonsoft.Json" version="9.0.1" targetFramework="net45" />
  <package id="System.Diagnostics.Contracts" version="4.0.1" targetFramework="net45" />
  <package id="System.Threading.Tasks.Extensions" version="4.4.0" targetFramework="net45" />
  <package id="System.ValueTuple" version="4.4.0" targetFramework="net45" />
  <package id="Unity.AspNet.WebApi" version="4.0.1" targetFramework="net452" />
</packages>

My team city server box has .net framework 4.0 installed on it. I am trying to avoid installing Visual Studio on team city server,

What could be the reason for this error?