问:
Piping into grep using cat returns error: no such file or directory
I am practicing on bash. When I try this command, I get an error: "grep: where: No such file or directory".</p>

```<code>cat file2.txt | tr " " "\n" | grep –i where | wc -l
</code>```

```<code>Content of file2.txt = 1 2 3 4 where 5 where 7 where

</code>```

答:
Why the error message

If you copy the command from the question and analyze it with a UTF-8 to Unicode interpreter, the – before i is an en dash U+2013 and not a hyphen-minus - (U+002D).  That means grep treats the –i as the pattern to be searched for and where as the file to be searched, which doesn't exist — as the error message says.

```<code>$ echo "grep –i where | wc -l" | utf8-unicode -w 3
0x67           = U+0067
0x72           = U+0072
0x65           = U+0065
0x70           = U+0070
0x20           = U+0020
0xE2 0x80 0x93 = U+2013
0x69           = U+0069
0x20           = U+0020
0x77           = U+0077
0x68           = U+0068
0x65           = U+0065
0x72           = U+0072
0x65           = U+0065
0x20           = U+0020
0x7C           = U+007C
0x20           = U+0020
0x77           = U+0077
0x63           = U+0063
0x20           = U+0020
0x2D           = U+002D
0x6C           = U+006C
$
</code>```

The code for utf8-unicode is now available in my SOQ (Stack Overflow Questions) repository on GitHub as file utf8-unicode-1.11.tgz in the packages sub-directory.  It's the current version — utf8-unicode -V reports utf8-unicode: UTF8-UNICODE Version 1.11 (2017-06-12 06:22:15) and utf8-unicode -h gives help. Using -w 3 means that it leaves enough space for each code point to be 3 bytes wide, leading to more columnar output (the default is -w 1).

Other improvements

In the analysis above, I have not addressed how to improve the script more generally.  If you have a sufficiently modern GNU grep, you can use just two commands:

```<code>$ grep -iow where file2.txt | wc -l
</code>```

You can't reduce it to one command; using grep -ciow where file2.txt yields 1, not 3 (because there's only one input line that matches).

With a non-GNU grep, you might need to use:

```<code>$ tr ' ' '\n' < file2.txt | grep -ic where
</code>```

Beware UUoC — Useless Use of cat.

Body:
I am practicing on bash. When I try this command, I get an error: "grep: where: No such file or directory".

cat file2.txt | tr " " "\n" | grep –i where | wc -l

Content of file2.txt = 1 2 3 4 where 5 where 7 where

Body:
Why the error message

If you copy the command from the question and analyze it with a UTF-8 to Unicode interpreter, the – before i is an en dash U+2013 and not a hyphen-minus - (U+002D).  That means grep treats the –i as the pattern to be searched for and where as the file to be searched, which doesn't exist — as the error message says.

$ echo "grep –i where | wc -l" | utf8-unicode -w 3
0x67           = U+0067
0x72           = U+0072
0x65           = U+0065
0x70           = U+0070
0x20           = U+0020
0xE2 0x80 0x93 = U+2013
0x69           = U+0069
0x20           = U+0020
0x77           = U+0077
0x68           = U+0068
0x65           = U+0065
0x72           = U+0072
0x65           = U+0065
0x20           = U+0020
0x7C           = U+007C
0x20           = U+0020
0x77           = U+0077
0x63           = U+0063
0x20           = U+0020
0x2D           = U+002D
0x6C           = U+006C
$

The code for utf8-unicode is now available in my SOQ (Stack Overflow Questions) repository on GitHub as file utf8-unicode-1.11.tgz in the packages sub-directory.  It's the current version — utf8-unicode -V reports utf8-unicode: UTF8-UNICODE Version 1.11 (2017-06-12 06:22:15) and utf8-unicode -h gives help. Using -w 3 means that it leaves enough space for each code point to be 3 bytes wide, leading to more columnar output (the default is -w 1).

Other improvements

In the analysis above, I have not addressed how to improve the script more generally.  If you have a sufficiently modern GNU grep, you can use just two commands:

$ grep -iow where file2.txt | wc -l

You can't reduce it to one command; using grep -ciow where file2.txt yields 1, not 3 (because there's only one input line that matches).

With a non-GNU grep, you might need to use:

$ tr ' ' '\n' < file2.txt | grep -ic where

Beware UUoC — Useless Use of cat.


来源: stackexchange

问:
not able to emit a function from one component to another component
I have two components in my angular file.
one is the discussion component and under the discussion component, I created one more component called add-files component.

I want to emit a function from the discussion component to the add-files component.but I am not able to perform this activity.

you can see my efforts below.
add-files component

```<code>@Input('removeFile')
  removeAttachments: boolean = false;

removeitem($event: string)
{
  alert("in file component");
  this.uploader.clearQueue();
}
</code>```

discussion.component.html

```<code><div class="col-12 col-sm-6 col-lg-6">
            <input type="submit" value="Send" (click)="removeitems1()" class="greenBtn float-right addCommentsBtn"
              [disabled]="commentForm.pristine || commentForm.invalid" onclick="closeCommnetPopupBox()">
          </div>

<app-add-files  (removeitems)="removeitem($event)"></app-add-files>
</code>```

discussion.component.ts

```<code>removeitems1()
{
  alert("called");
  this.sessionService.SetSessionItem("removeUploadfile","true");
  //this.comp.removedoc();
  this.removeitem.emit("hi");
}
</code>```

you can see from the above code I want to emit the function in the add-files component whenever the user will click on the submit button.

the above code is not working and I am new to the Angular. can anyone suggest something?

答:
There are two options which you can go for. The first one is similiar to your way. The issue is that you pass the event once. But you want to get triggered each time it is changed:

```<code>@Input() set removeFile(data: boolean) { this.anyFunction(data); }

anyFunction(data) {
  // do some code here
}
</code>```

The second option is to create a service (which I recommend to you). You can do that by angular-cli (ng g s servicename).

discussion.service.ts:

```<code>export class DiscussionService {

  buttonClick: EventEmitter<boolean> = new EventEmitter();

  constructor() { }
}
</code>```

By that, you created a service with an EventEmitter that is available for each component which includes the service. You can read more about EventEmitters here https://angular.io/api/core/EventEmitter.
To sum it, you just need to emit the event by your component:

discussion.component.ts:

```<code>constructor(private discussionService: DiscussionService) { }

clickFkt() { this.discussionService.buttonClick.emit(true) }
</code>```

discussion.component.html:

```<code><input (click)="clickFkt()">
</code>```

Now you can subscribe von every component to your service:

add-files.component.ts:

```<code>constructor(private discussionService: DiscussionService) { }

ngOnInit() {
   this.discussionService.buttonClick.subscribe(click => {
       this.anyFunction(click);
   });
}
anyFunction(data) {
   // do some code here
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have two components in my angular file.
one is the discussion component and under the discussion component, I created one more component called add-files component.

I want to emit a function from the discussion component to the add-files component.but I am not able to perform this activity.

you can see my efforts below.
add-files component

@Input('removeFile')
  removeAttachments: boolean = false;

removeitem($event: string)
{
  alert("in file component");
  this.uploader.clearQueue();
}

discussion.component.html

            <input type="submit" value="Send" (click)="removeitems1()" class="greenBtn float-right addCommentsBtn"
              [disabled]="commentForm.pristine || commentForm.invalid" onclick="closeCommnetPopupBox()">

<app-add-files  (removeitems)="removeitem($event)"></app-add-files>

discussion.component.ts

removeitems1()
{
  alert("called");
  this.sessionService.SetSessionItem("removeUploadfile","true");
  //this.comp.removedoc();
  this.removeitem.emit("hi");
}

you can see from the above code I want to emit the function in the add-files component whenever the user will click on the submit button.

the above code is not working and I am new to the Angular. can anyone suggest something?

Body:
There are two options which you can go for. The first one is similiar to your way. The issue is that you pass the event once. But you want to get triggered each time it is changed:

@Input() set removeFile(data: boolean) { this.anyFunction(data); }

anyFunction(data) {
  // do some code here
}

The second option is to create a service (which I recommend to you). You can do that by angular-cli (ng g s servicename).

discussion.service.ts:

export class DiscussionService {

  buttonClick: EventEmitter<boolean> = new EventEmitter();

  constructor() { }
}

By that, you created a service with an EventEmitter that is available for each component which includes the service. You can read more about EventEmitters here https://angular.io/api/core/EventEmitter.
To sum it, you just need to emit the event by your component:

discussion.component.ts:

constructor(private discussionService: DiscussionService) { }

clickFkt() { this.discussionService.buttonClick.emit(true) }

discussion.component.html:

<input (click)="clickFkt()">

Now you can subscribe von every component to your service:

add-files.component.ts:

constructor(private discussionService: DiscussionService) { }

ngOnInit() {
   this.discussionService.buttonClick.subscribe(click => {
       this.anyFunction(click);
   });
}
anyFunction(data) {
   // do some code here
}


问:
I am not able to understand what is been going in the following code...#Method Overloading

class something:

    def __init__(self, pages):
        self.noofpages=pages

    def __add__(self,b):
        return str(self.noofpages + b.noofpages)+'hii'

m=something(10)
n=something(20)
print(m+n)
```

Output :- 30hii

How 10 is going to self.noofpages and 20 to b.noofpages

答:
Ok so a few things to try and clarify this:

1) class definition

A class definition is nothing but a template for the objects derived from it. In that case the class something has two 'special' methods: init() and add().

init(self,...) methods is called as soon as a object is created. In this case when a object of class something is created, it required to be created with an argument that will internally be added to the attribute noofpages of that object (self refers to the object to be created)

add(self,other) method will tell python what to do if two instances of this class type are added, where self refers to the object from where the addition is being called and other refers to another object of the same class.

So after declaring the template for the class two objects of class something are created.

m=something(10)
n=something(20)
```

<p>These two objects are different instances of class something and so m will have its noofpages set to 10 and n to 20 you can verify this by calling:</p>

<pre class="lang-py prettyprint-override"><code>print(m.noofpages)
print(n.noofpages)
</code>```

Now that we established that even though m and n are two different instances of the same class we can move on to the add overload.

First lets talk about the naming convention when overloading addition (it makes the function make more sense). Usually instead of:

def __add__(self,b):
     return str(self.noofpages + b.noofpages)+'hii'
```

<p>You would have:</p>

<pre class="lang-py prettyprint-override"><code>def __add__(self,other):
    return str(self.noofpages+other.noofpages)+'hii'
</code>```

So self refers to the instance of the object where the method is being called and other means another instance of the same type of object.

Finally calling m+n is the same as calling m.__add__(n). So the add method is called on the leftmost element of the addition.

Hope I was more or less clear.

Body:
class something:

    def __init__(self, pages):
        self.noofpages=pages

    def __add__(self,b):
        return str(self.noofpages + b.noofpages)+'hii'

m=something(10)
n=something(20)
print(m+n)

Output :- 30hii

How 10 is going to self.noofpages and 20 to b.noofpages

Body:
Ok so a few things to try and clarify this:

1) class definition

A class definition is nothing but a template for the objects derived from it. In that case the class something has two 'special' methods: init() and add().

init(self,...) methods is called as soon as a object is created. In this case when a object of class something is created, it required to be created with an argument that will internally be added to the attribute noofpages of that object (self refers to the object to be created)

add(self,other) method will tell python what to do if two instances of this class type are added, where self refers to the object from where the addition is being called and other refers to another object of the same class.

So after declaring the template for the class two objects of class something are created.

m=something(10)
n=something(20)

These two objects are different instances of class something and so m will have its noofpages set to 10 and n to 20 you can verify this by calling:

print(m.noofpages)
print(n.noofpages)

Now that we established that even though m and n are two different instances of the same class we can move on to the add overload.

First lets talk about the naming convention when overloading addition (it makes the function make more sense). Usually instead of:

def __add__(self,b):
     return str(self.noofpages + b.noofpages)+'hii'

You would have:

def __add__(self,other):
    return str(self.noofpages+other.noofpages)+'hii'

So self refers to the instance of the object where the method is being called and other means another instance of the same type of object.

Finally calling m+n is the same as calling m.__add__(n). So the add method is called on the leftmost element of the addition.

Hope I was more or less clear.


问:
Renaming the containing project folder in VS.net under TFS
I have a vs.net project, and after some refactoring, have modified the name of the project.  How can I easily rename the underlying windows folder name to match this new project name under a TFS controlled project and solution?<br>
Note, I used to be able to do by fiddling with things in the background using SourceSafe ... </p>

答:
For Visual Studio 2019 and ASP.NET Core 2.2 I had to modify Scott Munro's answer slightly. Here's what worked for me:

Before you start: Check in all changes and make a backup of your solution.

Rename the project using the Solution Explorer (i.e. right click the project and click rename).

Rename the project folder in Source Control Explorer.

Open your solution's .sln file in a text editor, and fix the file path. (Replace any references to "OldProjectName" with "NewProjectName").

Reload your solution in Visual Studio.

Find and replace all the old namespaces with the new project name.

Done. Check in changes.

I had to do step 1 first in order to get the project to load after fixing the file path in step 3.

OwnerDisplayName: Bermo

ContentLicense: CC BY-SA 2.5

Body:
I have a vs.net project, and after some refactoring, have modified the name of the project.  How can I easily rename the underlying windows folder name to match this new project name under a TFS controlled project and solution?

Note, I used to be able to do by fiddling with things in the background using SourceSafe ...

LastEditorDisplayName: moocha


问:
regex to remove alphanumeric from text
I am trying to remove the alphanumeric attached in front the text of words variable. I tried regex but not works.Please help. </p>

```<code>words = c("A120 condition of returned veh","B520 vehivle of returned ve","petrol reserve switch")
</code>```

```<code>Expected result =
"condition of returned veh"
"vehivle of returned ve"
"petrol reserve switch"
</code>```

答:
We can use gsub to match the pattern or zero or more digits (\\d*) followed by one or more alphabets and one or more digits as pattern and replace with blank ("")

```<code>gsub("\\b\\d*[A-Za-z]+\\d+\\s*", '', words)
#[1] "condition of returned veh" "vehivle of returned ve"    "petrol reserve switch"
</code>```

If we also need to remove numbers as well

```<code>gsub("\\b\\S*\\d+\\S*\\s", '', c(words, "120 condition of returned 35 veh"))
#[1] "condition of returned veh" "vehivle of returned ve"    "petrol reserve switch"     "condition of returned veh"
</code>```

Title: regex to remove alphanumeric from text

Body:
I am trying to remove the alphanumeric attached in front the text of words variable. I tried regex but not works.Please help.

words = c("A120 condition of returned veh","B520 vehivle of returned ve","petrol reserve switch")

Expected result =
"condition of returned veh"
"vehivle of returned ve"
"petrol reserve switch"

Body:
We can use gsub to match the pattern or zero or more digits (\\d*) followed by one or more alphabets and one or more digits as pattern and replace with blank ("")

gsub("\\b\\d*[A-Za-z]+\\d+\\s*", '', words)
#[1] "condition of returned veh" "vehivle of returned ve"    "petrol reserve switch"

If we also need to remove numbers as well

gsub("\\b\\S*\\d+\\S*\\s", '', c(words, "120 condition of returned 35 veh"))
#[1] "condition of returned veh" "vehivle of returned ve"    "petrol reserve switch"     "condition of returned veh"


问:
VBA: Save a file with a name by default in a specific folder
Please I want to make a macro in Excel 2010 than the user can save a file in a specific folder but the name of the file would be given by default, can not be changed by the user. This for avoid that the user click other file looking the specific folder to save the file and the name of it change.  This is what I have:

```<code>ActiveWorkbook.Save
name = "File Name"
folder = Application.GetSaveAsFilename(name)
ActiveWorkbook.SaveAs Filename:= folder & "xlsm"
</code>```

答:
One option would be to enforce this rule after coming back from the SaveAs dialog.  Since you are only interested in the folder, build your Filename like this:

```<code>ActiveWorkbook.SaveAs Filename:=fso.GetParentFolderName(folder) & "\" & name & ".xlsm"
</code>```

This requires a reference to Microsoft Scripting Runtime and declaring fso like this:

```<code>Dim fso As FileSystemObject
Set fso = New FileSystemObject
</code>```

Body:
Please I want to make a macro in Excel 2010 than the user can save a file in a specific folder but the name of the file would be given by default, can not be changed by the user. This for avoid that the user click other file looking the specific folder to save the file and the name of it change.  This is what I have:

ActiveWorkbook.Save
name = "File Name"
folder = Application.GetSaveAsFilename(name)
ActiveWorkbook.SaveAs Filename:= folder & "xlsm"

Body:
One option would be to enforce this rule after coming back from the SaveAs dialog.  Since you are only interested in the folder, build your Filename like this:

ActiveWorkbook.SaveAs Filename:=fso.GetParentFolderName(folder) & "\" & name & ".xlsm"

This requires a reference to Microsoft Scripting Runtime and declaring fso like this:

Dim fso As FileSystemObject
Set fso = New FileSystemObject


问:
How can I get back access to the backend of TYPO3 when fluidpages are causing an error on backend and frontend?
I got to work on a Typo3 page and I have to say I'm at the very beginning if it comes to TYPO3.

So I wanted to fix a bug and updated the plugin "fluidpages" from version 4.1.0 (I guess) to 4.3. That cause the "Oops, an error occurred!" in the backend and frontend, so I dont have access from that side. I still have the FTP login for the website. The version of TYPO3 is 8.7.18.

The errorcode I get is that one:

Could not analyse class:

  "FluidTYPO3\Flux\Configuration\ConfigurationManager" maybe not loaded
  or no autoloader?

  Class FluidTYPO3\Flux\Configuration\ConfigurationManager does not exist

So does anyone know what I need to do?

From my research I think I need to update another plugins to make it back to work? And can I update them just by uploading them through FTP?

Thanks in advance!

Edit: After I tried to get the old version of the plugin running, I'm getting this error code from the log file:

Mon, 17 Feb 2020 22:59:56 +0100 [ALERT] request="fec23f8baf6dc" component="TYPO3.CMS.Frontend.ContentObject.Exception.ProductionExceptionHandler": Oops, an error occurred! Code: 2020021722595594039a4d - {"exception":"TYPO3\CMS\Extbase\Mvc\Exception: The default controller for extension \"Flux\" and plugin \"Page\" can not be determined. Please check for TYPO3\CMS\Extbase\Utility\ExtensionUtility::configurePlugin() in your ext_localconf.php.

答:
You can enter the Install Tool via https://example.org/typo3/install.php and start with Check for broken extensions. If that doesn't yield the extension in question, you can always manually change the PackageStates.php file and remove the extension you want to unload. Afterwards you should flush all caches through the Install Tool.

In the long term you should consider a few things:

Use a local development environment which mirrors your production environment. You can safely perform all steps without any risk here before deploying.

Use a deployment strategy/tool which allows for rollbacks. This allows you to quickly revert to a working version of your instance in case all other checks have failed. A simple but flexible solution is Deployer, you'll need SSH for this though.


问:
How to rename key of object in an array
How to replace array element value with another

i have array like this, without using jquery

```<code> this.products = [
      {
        text: 'prod1',
        value: 1
      },
      {
        text: 'prod2',
        value: 2
      },
      {
        text: 'prod3',
        value: 3
      }
 ];
</code>```

i want to replace 'text' to  'label'

答:
using ES6:</p>

```<code>const updatedProducts = products.map(({text: label, value})=>({value, label}));
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to rename key of object in an array

Body:
How to replace array element value with another

i have array like this, without using jquery

 this.products = [
      {
        text: 'prod1',
        value: 1
      },
      {
        text: 'prod2',
        value: 2
      },
      {
        text: 'prod3',
        value: 3
      }
 ];

i want to replace 'text' to  'label'

Body:
using ES6:

const updatedProducts = products.map(({text: label, value})=>({value, label}));


问:
Calculate the accuracy every epoch in PyTorch
I am working on a Neural Network problem, to classify data as 1 or 0. I am using Binary cross entropy loss to do this. The loss is fine, however, the accuracy is very low and isn't improving. I am assuming I did a mistake in the accuracy calculation. After every epoch, I am calculating the correct predictions after thresholding the output, and dividing that number by the total number of the dataset. Is there any thing wrong I did in the accuracy calculation? And why isn't it improving, but getting more worse?
This is my code:

net = Model()
criterion = torch.nn.BCELoss(size_average=True)
optimizer = torch.optim.SGD(net.parameters(), lr=0.1)

num_epochs = 100
for epoch in range(num_epochs):
    for i, (inputs,labels) in enumerate (train_loader):
        inputs = Variable(inputs.float())
        labels = Variable(labels.float())
        output = net(inputs)
        optimizer.zero_grad()
        loss = criterion(output, labels)
        loss.backward()
        optimizer.step()

    #Accuracy
    output = (output>0.5).float()
    correct = (output == labels).float().sum()
    print("Epoch {}/{}, Loss: {:.3f}, Accuracy: {:.3f}".format(epoch+1,num_epochs, loss.data[0], correct/x.shape[0]))
```

<p>And this is the strange output I get:</p>

```Epoch 1/100, Loss: 0.389, Accuracy: 0.035
Epoch 2/100, Loss: 0.370, Accuracy: 0.036
Epoch 3/100, Loss: 0.514, Accuracy: 0.030
Epoch 4/100, Loss: 0.539, Accuracy: 0.030
Epoch 5/100, Loss: 0.583, Accuracy: 0.029
Epoch 6/100, Loss: 0.439, Accuracy: 0.031
Epoch 7/100, Loss: 0.429, Accuracy: 0.034
Epoch 8/100, Loss: 0.408, Accuracy: 0.035
Epoch 9/100, Loss: 0.316, Accuracy: 0.035
Epoch 10/100, Loss: 0.436, Accuracy: 0.035
Epoch 11/100, Loss: 0.365, Accuracy: 0.034
Epoch 12/100, Loss: 0.485, Accuracy: 0.031
Epoch 13/100, Loss: 0.392, Accuracy: 0.033
Epoch 14/100, Loss: 0.494, Accuracy: 0.030
Epoch 15/100, Loss: 0.369, Accuracy: 0.035
Epoch 16/100, Loss: 0.495, Accuracy: 0.029
Epoch 17/100, Loss: 0.415, Accuracy: 0.034
Epoch 18/100, Loss: 0.410, Accuracy: 0.035
Epoch 19/100, Loss: 0.282, Accuracy: 0.038
Epoch 20/100, Loss: 0.499, Accuracy: 0.031
Epoch 21/100, Loss: 0.446, Accuracy: 0.030
Epoch 22/100, Loss: 0.585, Accuracy: 0.026
Epoch 23/100, Loss: 0.419, Accuracy: 0.035
Epoch 24/100, Loss: 0.492, Accuracy: 0.031
Epoch 25/100, Loss: 0.537, Accuracy: 0.031
Epoch 26/100, Loss: 0.439, Accuracy: 0.033
Epoch 27/100, Loss: 0.421, Accuracy: 0.035
Epoch 28/100, Loss: 0.532, Accuracy: 0.034
Epoch 29/100, Loss: 0.234, Accuracy: 0.038
Epoch 30/100, Loss: 0.492, Accuracy: 0.027
Epoch 31/100, Loss: 0.407, Accuracy: 0.035
Epoch 32/100, Loss: 0.305, Accuracy: 0.038
Epoch 33/100, Loss: 0.663, Accuracy: 0.025
Epoch 34/100, Loss: 0.588, Accuracy: 0.031
Epoch 35/100, Loss: 0.329, Accuracy: 0.035
Epoch 36/100, Loss: 0.474, Accuracy: 0.033
Epoch 37/100, Loss: 0.535, Accuracy: 0.031
Epoch 38/100, Loss: 0.406, Accuracy: 0.033
Epoch 39/100, Loss: 0.513, Accuracy: 0.030
Epoch 40/100, Loss: 0.593, Accuracy: 0.030
Epoch 41/100, Loss: 0.265, Accuracy: 0.036
Epoch 42/100, Loss: 0.576, Accuracy: 0.031
Epoch 43/100, Loss: 0.565, Accuracy: 0.027
Epoch 44/100, Loss: 0.576, Accuracy: 0.030
Epoch 45/100, Loss: 0.396, Accuracy: 0.035
Epoch 46/100, Loss: 0.423, Accuracy: 0.034
Epoch 47/100, Loss: 0.489, Accuracy: 0.033
Epoch 48/100, Loss: 0.591, Accuracy: 0.029
Epoch 49/100, Loss: 0.415, Accuracy: 0.034
Epoch 50/100, Loss: 0.291, Accuracy: 0.039
Epoch 51/100, Loss: 0.395, Accuracy: 0.033
Epoch 52/100, Loss: 0.540, Accuracy: 0.026
Epoch 53/100, Loss: 0.436, Accuracy: 0.033
Epoch 54/100, Loss: 0.346, Accuracy: 0.036
Epoch 55/100, Loss: 0.519, Accuracy: 0.029
Epoch 56/100, Loss: 0.456, Accuracy: 0.031
Epoch 57/100, Loss: 0.425, Accuracy: 0.035
Epoch 58/100, Loss: 0.311, Accuracy: 0.039
Epoch 59/100, Loss: 0.406, Accuracy: 0.034
Epoch 60/100, Loss: 0.360, Accuracy: 0.035
Epoch 61/100, Loss: 0.476, Accuracy: 0.030
Epoch 62/100, Loss: 0.404, Accuracy: 0.034
Epoch 63/100, Loss: 0.382, Accuracy: 0.036
Epoch 64/100, Loss: 0.538, Accuracy: 0.031
Epoch 65/100, Loss: 0.392, Accuracy: 0.034
Epoch 66/100, Loss: 0.434, Accuracy: 0.033
Epoch 67/100, Loss: 0.479, Accuracy: 0.031
Epoch 68/100, Loss: 0.494, Accuracy: 0.031
Epoch 69/100, Loss: 0.415, Accuracy: 0.034
Epoch 70/100, Loss: 0.390, Accuracy: 0.036
Epoch 71/100, Loss: 0.330, Accuracy: 0.038
Epoch 72/100, Loss: 0.449, Accuracy: 0.030
Epoch 73/100, Loss: 0.315, Accuracy: 0.039
Epoch 74/100, Loss: 0.450, Accuracy: 0.031
Epoch 75/100, Loss: 0.562, Accuracy: 0.030
Epoch 76/100, Loss: 0.447, Accuracy: 0.031
Epoch 77/100, Loss: 0.408, Accuracy: 0.038
Epoch 78/100, Loss: 0.359, Accuracy: 0.034
Epoch 79/100, Loss: 0.372, Accuracy: 0.035
Epoch 80/100, Loss: 0.452, Accuracy: 0.034
Epoch 81/100, Loss: 0.360, Accuracy: 0.035
Epoch 82/100, Loss: 0.453, Accuracy: 0.031
Epoch 83/100, Loss: 0.578, Accuracy: 0.030
Epoch 84/100, Loss: 0.537, Accuracy: 0.030
Epoch 85/100, Loss: 0.483, Accuracy: 0.035
Epoch 86/100, Loss: 0.343, Accuracy: 0.036
Epoch 87/100, Loss: 0.439, Accuracy: 0.034
Epoch 88/100, Loss: 0.686, Accuracy: 0.023
Epoch 89/100, Loss: 0.265, Accuracy: 0.039
Epoch 90/100, Loss: 0.369, Accuracy: 0.035
Epoch 91/100, Loss: 0.521, Accuracy: 0.027
Epoch 92/100, Loss: 0.662, Accuracy: 0.027
Epoch 93/100, Loss: 0.581, Accuracy: 0.029
Epoch 94/100, Loss: 0.322, Accuracy: 0.034
Epoch 95/100, Loss: 0.375, Accuracy: 0.035
Epoch 96/100, Loss: 0.575, Accuracy: 0.031
Epoch 97/100, Loss: 0.489, Accuracy: 0.030
Epoch 98/100, Loss: 0.435, Accuracy: 0.033
Epoch 99/100, Loss: 0.440, Accuracy: 0.031
Epoch 100/100, Loss: 0.444, Accuracy: 0.033
```

答:
Here is my solution:

```<code>def evaluate(model, validation_loader, use_cuda=True):
    model.eval()
    with torch.no_grad():
        acc = .0
        for i, data in enumerate(validation_loader):
            X = data[0]
            y = data[1]
            if use_cuda:
                X = X.cuda()
                y = y.cuda()
            predicted = model(X)
            acc+=(predicted.round() == y).sum()/float(predicted.shape[0])
    model.train()
    return (acc/(i+1)).detach().item()
</code>```

Note 1: Set the model to eval mode while validating and then back to train mode.

Note 2: I'm not sure if autograd needs to be disabled. Here is a thread on it

For one-hot results torch.max can be used. Example:

```<code>correct = 0
total = 0
with torch.no_grad():
    for data in testloader:
        images, labels = data
        outputs = net(images)
        _, predicted = torch.max(outputs.data, 1)
        total += labels.size(0)
        correct += (predicted == labels).sum().item()

print('Accuracy of the network on the 10000 test images: %d %%' % (
    100 * correct / total))
</code>```

Body:
I am working on a Neural Network problem, to classify data as 1 or 0. I am using Binary cross entropy loss to do this. The loss is fine, however, the accuracy is very low and isn't improving. I am assuming I did a mistake in the accuracy calculation. After every epoch, I am calculating the correct predictions after thresholding the output, and dividing that number by the total number of the dataset. Is there any thing wrong I did in the accuracy calculation? And why isn't it improving, but getting more worse?
This is my code:

net = Model()
criterion = torch.nn.BCELoss(size_average=True)
optimizer = torch.optim.SGD(net.parameters(), lr=0.1)

num_epochs = 100
for epoch in range(num_epochs):
    for i, (inputs,labels) in enumerate (train_loader):
        inputs = Variable(inputs.float())
        labels = Variable(labels.float())
        output = net(inputs)
        optimizer.zero_grad()
        loss = criterion(output, labels)
        loss.backward()
        optimizer.step()

    #Accuracy
    output = (output>0.5).float()
    correct = (output == labels).float().sum()
    print("Epoch {}/{}, Loss: {:.3f}, Accuracy: {:.3f}".format(epoch+1,num_epochs, loss.data[0], correct/x.shape[0]))

And this is the strange output I get:

Epoch 1/100, Loss: 0.389, Accuracy: 0.035
Epoch 2/100, Loss: 0.370, Accuracy: 0.036
Epoch 3/100, Loss: 0.514, Accuracy: 0.030
Epoch 4/100, Loss: 0.539, Accuracy: 0.030
Epoch 5/100, Loss: 0.583, Accuracy: 0.029
Epoch 6/100, Loss: 0.439, Accuracy: 0.031
Epoch 7/100, Loss: 0.429, Accuracy: 0.034
Epoch 8/100, Loss: 0.408, Accuracy: 0.035
Epoch 9/100, Loss: 0.316, Accuracy: 0.035
Epoch 10/100, Loss: 0.436, Accuracy: 0.035
Epoch 11/100, Loss: 0.365, Accuracy: 0.034
Epoch 12/100, Loss: 0.485, Accuracy: 0.031
Epoch 13/100, Loss: 0.392, Accuracy: 0.033
Epoch 14/100, Loss: 0.494, Accuracy: 0.030
Epoch 15/100, Loss: 0.369, Accuracy: 0.035
Epoch 16/100, Loss: 0.495, Accuracy: 0.029
Epoch 17/100, Loss: 0.415, Accuracy: 0.034
Epoch 18/100, Loss: 0.410, Accuracy: 0.035
Epoch 19/100, Loss: 0.282, Accuracy: 0.038
Epoch 20/100, Loss: 0.499, Accuracy: 0.031
Epoch 21/100, Loss: 0.446, Accuracy: 0.030
Epoch 22/100, Loss: 0.585, Accuracy: 0.026
Epoch 23/100, Loss: 0.419, Accuracy: 0.035
Epoch 24/100, Loss: 0.492, Accuracy: 0.031
Epoch 25/100, Loss: 0.537, Accuracy: 0.031
Epoch 26/100, Loss: 0.439, Accuracy: 0.033
Epoch 27/100, Loss: 0.421, Accuracy: 0.035
Epoch 28/100, Loss: 0.532, Accuracy: 0.034
Epoch 29/100, Loss: 0.234, Accuracy: 0.038
Epoch 30/100, Loss: 0.492, Accuracy: 0.027
Epoch 31/100, Loss: 0.407, Accuracy: 0.035
Epoch 32/100, Loss: 0.305, Accuracy: 0.038
Epoch 33/100, Loss: 0.663, Accuracy: 0.025
Epoch 34/100, Loss: 0.588, Accuracy: 0.031
Epoch 35/100, Loss: 0.329, Accuracy: 0.035
Epoch 36/100, Loss: 0.474, Accuracy: 0.033
Epoch 37/100, Loss: 0.535, Accuracy: 0.031
Epoch 38/100, Loss: 0.406, Accuracy: 0.033
Epoch 39/100, Loss: 0.513, Accuracy: 0.030
Epoch 40/100, Loss: 0.593, Accuracy: 0.030
Epoch 41/100, Loss: 0.265, Accuracy: 0.036
Epoch 42/100, Loss: 0.576, Accuracy: 0.031
Epoch 43/100, Loss: 0.565, Accuracy: 0.027
Epoch 44/100, Loss: 0.576, Accuracy: 0.030
Epoch 45/100, Loss: 0.396, Accuracy: 0.035
Epoch 46/100, Loss: 0.423, Accuracy: 0.034
Epoch 47/100, Loss: 0.489, Accuracy: 0.033
Epoch 48/100, Loss: 0.591, Accuracy: 0.029
Epoch 49/100, Loss: 0.415, Accuracy: 0.034
Epoch 50/100, Loss: 0.291, Accuracy: 0.039
Epoch 51/100, Loss: 0.395, Accuracy: 0.033
Epoch 52/100, Loss: 0.540, Accuracy: 0.026
Epoch 53/100, Loss: 0.436, Accuracy: 0.033
Epoch 54/100, Loss: 0.346, Accuracy: 0.036
Epoch 55/100, Loss: 0.519, Accuracy: 0.029
Epoch 56/100, Loss: 0.456, Accuracy: 0.031
Epoch 57/100, Loss: 0.425, Accuracy: 0.035
Epoch 58/100, Loss: 0.311, Accuracy: 0.039
Epoch 59/100, Loss: 0.406, Accuracy: 0.034
Epoch 60/100, Loss: 0.360, Accuracy: 0.035
Epoch 61/100, Loss: 0.476, Accuracy: 0.030
Epoch 62/100, Loss: 0.404, Accuracy: 0.034
Epoch 63/100, Loss: 0.382, Accuracy: 0.036
Epoch 64/100, Loss: 0.538, Accuracy: 0.031
Epoch 65/100, Loss: 0.392, Accuracy: 0.034
Epoch 66/100, Loss: 0.434, Accuracy: 0.033
Epoch 67/100, Loss: 0.479, Accuracy: 0.031
Epoch 68/100, Loss: 0.494, Accuracy: 0.031
Epoch 69/100, Loss: 0.415, Accuracy: 0.034
Epoch 70/100, Loss: 0.390, Accuracy: 0.036
Epoch 71/100, Loss: 0.330, Accuracy: 0.038
Epoch 72/100, Loss: 0.449, Accuracy: 0.030
Epoch 73/100, Loss: 0.315, Accuracy: 0.039
Epoch 74/100, Loss: 0.450, Accuracy: 0.031
Epoch 75/100, Loss: 0.562, Accuracy: 0.030
Epoch 76/100, Loss: 0.447, Accuracy: 0.031
Epoch 77/100, Loss: 0.408, Accuracy: 0.038
Epoch 78/100, Loss: 0.359, Accuracy: 0.034
Epoch 79/100, Loss: 0.372, Accuracy: 0.035
Epoch 80/100, Loss: 0.452, Accuracy: 0.034
Epoch 81/100, Loss: 0.360, Accuracy: 0.035
Epoch 82/100, Loss: 0.453, Accuracy: 0.031
Epoch 83/100, Loss: 0.578, Accuracy: 0.030
Epoch 84/100, Loss: 0.537, Accuracy: 0.030
Epoch 85/100, Loss: 0.483, Accuracy: 0.035
Epoch 86/100, Loss: 0.343, Accuracy: 0.036
Epoch 87/100, Loss: 0.439, Accuracy: 0.034
Epoch 88/100, Loss: 0.686, Accuracy: 0.023
Epoch 89/100, Loss: 0.265, Accuracy: 0.039
Epoch 90/100, Loss: 0.369, Accuracy: 0.035
Epoch 91/100, Loss: 0.521, Accuracy: 0.027
Epoch 92/100, Loss: 0.662, Accuracy: 0.027
Epoch 93/100, Loss: 0.581, Accuracy: 0.029
Epoch 94/100, Loss: 0.322, Accuracy: 0.034
Epoch 95/100, Loss: 0.375, Accuracy: 0.035
Epoch 96/100, Loss: 0.575, Accuracy: 0.031
Epoch 97/100, Loss: 0.489, Accuracy: 0.030
Epoch 98/100, Loss: 0.435, Accuracy: 0.033
Epoch 99/100, Loss: 0.440, Accuracy: 0.031
Epoch 100/100, Loss: 0.444, Accuracy: 0.033

Body:
Here is my solution:

def evaluate(model, validation_loader, use_cuda=True):
    model.eval()
    with torch.no_grad():
        acc = .0
        for i, data in enumerate(validation_loader):
            X = data[0]
            y = data[1]
            if use_cuda:
                X = X.cuda()
                y = y.cuda()
            predicted = model(X)
            acc+=(predicted.round() == y).sum()/float(predicted.shape[0])
    model.train()
    return (acc/(i+1)).detach().item()

Note 1: Set the model to eval mode while validating and then back to train mode.

Note 2: I'm not sure if autograd needs to be disabled. Here is a thread on it

For one-hot results torch.max can be used. Example:

correct = 0
total = 0
with torch.no_grad():
    for data in testloader:
        images, labels = data
        outputs = net(images)
        _, predicted = torch.max(outputs.data, 1)
        total += labels.size(0)
        correct += (predicted == labels).sum().item()

print('Accuracy of the network on the 10000 test images: %d %%' % (
    100 * correct / total))


问:
Segfault after deleting elements from vector
I'm currently working on a project, more precisely a tangram game.
I have a problem with a segfault and I don't understand why.

Given that I have a whole project, I will try to simplify the problem :
I have a GameManager class that contains in particular a Menu object (and other things, but I don't think that is important. The gameManager is used to inititialize this object and manage it.
The Menu contains a vector of Button(each button has a lambda to perform an action when the user click on it).

```<code>std::vector<std::unique_ptr<Button>> buttons;
</code>```

To illustrate how it works I will take an example : if the user clicks on the "Load" button, the gameManager delete the current Buttons contained in the menu and add new buttons in that menu.

```<code>void GameManager::initMainMenuButtons() {
...
menu -> addButton(std::unique_ptr<Button>(new Button(x1, y1, x2, y2, "Create",
    [this]{
        std::cout << "Create level" << std::endl;
        menu->clear()
        initCreateLevelButtons();
        actionManager->setMenu(menu);
    }
)));
...
}
</code>```

In that code sample, I have a method initMainMenuButtons that adds several buttons in the menu , like "Load" or "Quit".
When the user clicks on "Create", I want to change the interface (adding and deleting buttons). So, to delete the buttons, i call the method clear()

```<code>void Menu::clear() {
  buttons.clear();
  decorationPieces.clear(); // not interesting
}
</code>```

I'm using unique_ptr, thus, I don't have to delete the buttons mannualy.
So far, no problem : the vector of buttons seems to be empty (size is 0).
Next, the method initCreateLevelButtons() is called. This method is very similar to initMainMenu : it adds buttons in the menu, nothing else. During this call, the buttons seems to be correctly added in the vector, I printed the content of the vector at the end and the vector contains the correct buttons.

And there, the problem appears : after the call of initCreateLevelButtons(), there is a segfault when i want to use the menu, so, actionManager->setMenu(menu); doesn't work. I tried to print the menu std::cout << menu << std::endl, and test if this pointer is nullptr, but it doesn't work either. I don't understand why the menu seems to be correct at the last line of initCreateLevelButtons() and becomes invalid just after.
If I doesn't clear the vector of buttons (the menu->clear instruction), the program works, but, the last buttons are still here).

I tried to use raw pointers and I notices that the program is able to clear the vector as long as the buttons are not deleted (If I add a loop to delete the buttons, the problem arises), so, I conclued that the probleme is the buttons deleting. I don't understanf why, I'm stuck.
I don't know if I explained it weel, because, as I have already said, the code is part of a whole project, it's hard to introduce classes without introduce other things.
if you want details or the complete code of methods, I can provide them.

答:
When you call menu->clear() it calls buttons.clear().

When you call buttons.clear() it destroys all the elements of buttons.

When you destroy the unique_ptr for the "Create" button, it destroys the "Create" button.

I assume button's callback is a std::function. When the button is destroyed, so is the std::function.

When the std::function is destroyed, your callback lambda object ([this]{...}) is destroyed.

The this pointer inside a lambda is stored in the lambda object. So now the memory that held the this pointer has been deallocated.

Since actionManager is a member variable of GameManager, actionManager->setMenu(menu) is really this->actionManager->setMenu(menu) which crashes because it uses a dangling pointer.

One workaround is to put the button code in a function of GameManager (since the GameManager is not destroyed), and call that from the lambda. Then, it's okay if you destroy the button while inside that function. It's okay to destroy an object whose code is currently running, as long as you are careful to not access the object after it's destroyed! This is also okay with std::function. I.e.:

```<code>    [this]{
        // move the rest of the code to the CreateLevel function
        this->CreateLevel();

        // At this point the lambda has been destroyed, but it's not a problem
        // because we don't do anything.
    }
</code>```

Body:
I'm currently working on a project, more precisely a tangram game.
I have a problem with a segfault and I don't understand why.

Given that I have a whole project, I will try to simplify the problem :
I have a GameManager class that contains in particular a Menu object (and other things, but I don't think that is important. The gameManager is used to inititialize this object and manage it.
The Menu contains a vector of Button(each button has a lambda to perform an action when the user click on it).

std::vector<std::unique_ptr<Button>> buttons;

To illustrate how it works I will take an example : if the user clicks on the "Load" button, the gameManager delete the current Buttons contained in the menu and add new buttons in that menu.

void GameManager::initMainMenuButtons() {
...
menu -> addButton(std::unique_ptr<Button>(new Button(x1, y1, x2, y2, "Create",
    [this]{
        std::cout << "Create level" << std::endl;
        menu->clear()
        initCreateLevelButtons();
        actionManager->setMenu(menu);
    }
)));
...
}

In that code sample, I have a method initMainMenuButtons that adds several buttons in the menu , like "Load" or "Quit".
When the user clicks on "Create", I want to change the interface (adding and deleting buttons). So, to delete the buttons, i call the method clear()

void Menu::clear() {
  buttons.clear();
  decorationPieces.clear(); // not interesting
}

I'm using unique_ptr, thus, I don't have to delete the buttons mannualy.
So far, no problem : the vector of buttons seems to be empty (size is 0).
Next, the method initCreateLevelButtons() is called. This method is very similar to initMainMenu : it adds buttons in the menu, nothing else. During this call, the buttons seems to be correctly added in the vector, I printed the content of the vector at the end and the vector contains the correct buttons.

And there, the problem appears : after the call of initCreateLevelButtons(), there is a segfault when i want to use the menu, so, actionManager->setMenu(menu); doesn't work. I tried to print the menu std::cout << menu << std::endl, and test if this pointer is nullptr, but it doesn't work either. I don't understand why the menu seems to be correct at the last line of initCreateLevelButtons() and becomes invalid just after.
If I doesn't clear the vector of buttons (the menu->clear instruction), the program works, but, the last buttons are still here).

I tried to use raw pointers and I notices that the program is able to clear the vector as long as the buttons are not deleted (If I add a loop to delete the buttons, the problem arises), so, I conclued that the probleme is the buttons deleting. I don't understanf why, I'm stuck.
I don't know if I explained it weel, because, as I have already said, the code is part of a whole project, it's hard to introduce classes without introduce other things.
if you want details or the complete code of methods, I can provide them.

Body:
When you call menu->clear() it calls buttons.clear().

When you call buttons.clear() it destroys all the elements of buttons.

When you destroy the unique_ptr for the "Create" button, it destroys the "Create" button.

I assume button's callback is a std::function. When the button is destroyed, so is the std::function.

When the std::function is destroyed, your callback lambda object ([this]{...}) is destroyed.

The this pointer inside a lambda is stored in the lambda object. So now the memory that held the this pointer has been deallocated.

Since actionManager is a member variable of GameManager, actionManager->setMenu(menu) is really this->actionManager->setMenu(menu) which crashes because it uses a dangling pointer.

One workaround is to put the button code in a function of GameManager (since the GameManager is not destroyed), and call that from the lambda. Then, it's okay if you destroy the button while inside that function. It's okay to destroy an object whose code is currently running, as long as you are careful to not access the object after it's destroyed! This is also okay with std::function. I.e.:

    [this]{
        // move the rest of the code to the CreateLevel function
        this->CreateLevel();

        // At this point the lambda has been destroyed, but it's not a problem
        // because we don't do anything.
    }


问:
javascript find all the object in an array and convert it into an array to array
I have a list of array with object in it like address and details

Input

```<code>var arr = [
    {id: 1, name: "abc", address: {street: "some text1", pin: 879888, state: "my-state1"}, details: {section: "A", roll: 12, branch:"CSE"}},
    {id: 2, name: "xyz", address: {street: "some text2", pin: 879887, state: "my-state2"}, details: {section: "B", roll: 13, branch:"IT"}}
]
</code>```

I want to iterate on this array and convert all the inner object so that it will look something like below

Expected Result

```<code>var arr = [
    {id: 1, name: "abc", street: "some text1", pin: 879888, state: "my-state1", section: "A", roll: 12, branch: "CSE"},
    {id: 2, name: "xyz", street: "some text2", pin: 879887, state: "my-state2", section: "B", roll: 13, branch: "IT"}
]
</code>```

答:
use map and spread operator will simplify.

Alternatively, you can do generic way with out hard coding keys.

var arr = [
  {
    id: 1,
    name: "abc",
    address: { street: "some text1", pin: 879888, state: "my-state1" },
    details: { section: "A", roll: 12, branch: "CSE" }
  },
  {
    id: 2,
    name: "xyz",
    address: { street: "some text2", pin: 879887, state: "my-state2" },
    details: { section: "B", roll: 13, branch: "IT" }
  }
];

const updated = arr.map(item => ({
  id: item.id,
  name: item.name,
  ...item.address,
  ...item.details
}));

const updatedGeneric = arr.map(item => {
  let res = {};
  Object.entries(item).forEach(([key, value]) => Object.assign(res, typeof value === "object" ? value : { [key]: value }));
  return res;
});

console.log(updated);
console.log(updatedGeneric);```

Body:
I have a list of array with object in it like address and details

Input

var arr = [
    {id: 1, name: "abc", address: {street: "some text1", pin: 879888, state: "my-state1"}, details: {section: "A", roll: 12, branch:"CSE"}},
    {id: 2, name: "xyz", address: {street: "some text2", pin: 879887, state: "my-state2"}, details: {section: "B", roll: 13, branch:"IT"}}
]

I want to iterate on this array and convert all the inner object so that it will look something like below

Expected Result

var arr = [
    {id: 1, name: "abc", street: "some text1", pin: 879888, state: "my-state1", section: "A", roll: 12, branch: "CSE"},
    {id: 2, name: "xyz", street: "some text2", pin: 879887, state: "my-state2", section: "B", roll: 13, branch: "IT"}
]


问:
bootstrap button dropdown set selected value to li
I am having a select box in my form, and after page loading, it is then transformed to bootstrap button before the select box. I can't set the selected value for the converted bootstrap button drop-down li.

```<code><button type="button" class="btn dropdown-toggle btn-default" data-toggle="dropdown" data-id="Occupation" title="-- Please select Occupation--">
<span class="filter-option pull-left">-- Please select Occupation--</span> <span class="bs-caret">
<span class="caret"></span></span></button>
<div class="dropdown-menu open"><ul class="dropdown-menu inner" role="menu">
<li data-original-index="0" class="selected"><a tabindex="0" class="" style="" data-tokens="null"><span class="text">-- Please select Occupation--</span><span class="glyphicon glyphicon-ok check-mark"></span></a></li>
<li data-original-index="1"><a tabindex="0" class="" style="" data-tokens="null"><span class="text">Salaried</span><span class="glyphicon glyphicon-ok check-mark"></span></a></li>
<li data-original-index="2"><a tabindex="0" class="" style="" data-tokens="null"><span class="text">Business</span><span class="glyphicon glyphicon-ok check-mark"></span></a></li>
<li data-original-index="3"><a tabindex="0" class="" style="" data-tokens="null"><span class="text">Above 18 Years</span><span class="glyphicon glyphicon-ok check-mark"></span></a></li></ul></div>
<select name="Occupation" class="form-control show-tick" required="" tabindex="-98">
          <option value="">-- Please select Occupation--</option>
          <option value="Salaried">Salaried</option>
          <option value="Business">Business</option>
          <option value="Above 18">Above 18 Years</option>
</select>
</code>```

I am having the value in localStorage.getItem('Occupation'), and I tried to set the value to that li by using

```<code>$('#Occupation ul li').eq(1).find('span').eq(1).text(localStorage.getItem('Occupation'));    //not worked
$('#Occupation').parents('.btn-group').find('.dropdown-toggle').html(localStorage.getItem('Occupation')+' <span class="caret"></span>');  //not worked
$("#Occupation li a").filter("[value=" + localStorage.getItem('Occupation') + "]"); //not worked
$("#Occupation").html(localStorage.getItem('Occupation') + ' <span class="caret"></span>');  //not worked
</code>```

Could someone suggest to me a solution to set the value to that drop-down?

Thanks :)

答:
Upon checking, there is a plugin (bootstrap-select) installed in my site. That plugin modifies my select box to the bootstrap button.

Then I visited the plugin site and got a solution,

$('select[name="Occupation"]').selectpicker('val', localStorage.getItem('Occupation'));

Body:
I am having a select box in my form, and after page loading, it is then transformed to bootstrap button before the select box. I can't set the selected value for the converted bootstrap button drop-down li.

<button type="button" class="btn dropdown-toggle btn-default" data-toggle="dropdown" data-id="Occupation" title="-- Please select Occupation--">
-- Please select Occupation--
</button>

-- Please select Occupation--

Salaried

Business

Above 18 Years

<select name="Occupation" class="form-control show-tick" required="" tabindex="-98">
          <option value="">-- Please select Occupation--</option>
          <option value="Salaried">Salaried</option>
          <option value="Business">Business</option>
          <option value="Above 18">Above 18 Years</option>
</select>

I am having the value in localStorage.getItem('Occupation'), and I tried to set the value to that li by using

$('#Occupation ul li').eq(1).find('span').eq(1).text(localStorage.getItem('Occupation'));    //not worked
$('#Occupation').parents('.btn-group').find('.dropdown-toggle').html(localStorage.getItem('Occupation')+' ');  //not worked
$("#Occupation li a").filter("[value=" + localStorage.getItem('Occupation') + "]"); //not worked
$("#Occupation").html(localStorage.getItem('Occupation') + ' ');  //not worked

Could someone suggest to me a solution to set the value to that drop-down?

Thanks :)


问:
Why parent is stored in git notes?
The way git store notes:

Git only store one note per commit for single namespace. One can have multiple namespace. Default namespace is commit.

.git/refs/notes/ contain one hash (say, MainHash_2), which is a tree object. Whenever you create a note the hash get changed.

This tree object contain two more hashes. One to another tree structure (the notes tree structure, say NOTES_2) and one to parent tree object(the one in the the .git/refs/notes/ before creating this note, say MainHash_1 )

The notes tree structure contains one entry for each note. Each entry have two hash: one to note content and other to specified commit.

As mentioned in third point why the parent is stored? As this parent(its type is same what is mentioned in point two) also contain another tree which contain one entry per note.

Suppose currently you have three notes. MainHash_2 contains a hash to NOTES_2, which contain three entries for each note. MainHash_1 contains a hash to NOTES_1, which contain two entries(for all the remaining notes except the one created now). Why storing these two entries twice and so on??

答:
git notes was introduced in in commit 73f77b9, Git v1.6.6-rc0.

The notion of fanout was introduced with Git v1.7.1-rc0 in Feb. 2010 with commit 73f77b9, to determine optimal on-disk fanout for this part of the notes tree, in .git/refs/notes/commits.

Values of the 'fanout' variable:

0: No fanout (all notes are stored directly in the root notes tree)

1: 2/38 fanout

2: 2/2/36 fanout

3: 2/2/2/34 fanout

With Git 2.25.2 (March 2020), The code to automatically shrink the fan-out in the notes tree had an off-by-one bug, which has been killed.

See commit dbc2747, commit e1c5253 (03 Feb 2020) by Johan Herland (jherland).

(Merged by Junio C Hamano -- gitster -- in commit 8833260, 14 Feb 2020)

t3305: check notes fanout more carefully and robustly

In short, before this patch, this test script:

creates many notes

verifies that all notes in the notes tree has a fanout of 1

removes most notes

verifies that the notes in the notes tree now has a fanout of 0

The fanout verification only happened twice: after creating all the notes, and after removing most of them.

This patch strengthens the test by checking the fanout after _each_ added/removed note: We assert that the switch from fanout 0 -> 1 happens exactly once while adding notes (and that the switch pervades the entire notes tree). Likewise, we assert that the switch from fanout 1 -> 0 happens exactly once while removing notes.

Additionally, we decrease the number of notes left after removal, from 50 to 15 notes, in order to ensure that fanout 1 -> 0 transition keeps happening regardless of external factors (1).

(1): Currently (with the SHA1 hash function and the deterministic object ids of the test environment) the fanout heuristic in the notes code happens to switch from 0 -> 1 at 109 notes, and from 1 -> 0 at 59 notes.

  However, changing the hash function or other external factors will vary these numbers, and the latter may - in theory - go as low as 15.

  For more details, please see the discussion.

And:

notes.c: fix off-by-one error when decreasing notes fanout

As noted in the previous commit, the nature of the fanout heuristic in the notes code causes the exact point at which we increase or decrease the notes fanout to vary with the objects being annotated.

  Since the object ids generated by the test environment are deterministic (by design), the notes generated and tested by t3305 are always the same, and we therefore happen to see the same fanout behavior from one run to the next.

Coincidentally, if we were to change the test environment slightly (say by making a test commit on an unrelated branch before we start the t3305 test proper), we not only see the fanout switch happen at different points, we also manage to trigger a bug in the notes code where the fanout 1 -> 0 switch is not applied uniformly across the notes tree, but instead yields a notes tree like this:

```<code>...
bdeafb301e44b0e4db0f738a2d2a7beefdb70b70
bff2d39b4f7122bd4c5caee3de353a774d1e632a
d3/8ec8f851adf470131178085bfbaab4b12ad2a7
e0b173960431a3e692ae929736df3c9b73a11d5b
eb3c3aede523d729990ac25c62a93eb47c21e2e3
...
</code>```

The bug occurs when we are writing out a notes tree with a newly decreased fanout, and the notes tree contains unexpanded subtrees that should be consolidated into the parent tree as a consequence of the decreased fanout):

Subtrees that happen to sit at an even level in the internal notes 16-tree structure (in other words: subtrees whose path - "d3" in the example above - is unique in the first nibble - i.e. there are no other note paths that start with "d") are not unpacked as part of the tree writeout.

  This error will repeat itself in subsequent note trees until the subtree is forced to be unpacked. In t3305 this only happens when the d38ec8f8 note is itself removed from the tree.

The error is not severe (no information is lost, and the notes code is able to read/decode this tree and manipulate it correctly), but this is nonetheless a bug in the current implementation that should be fixed.

That said, fixing the off-by-one error is not without complications:

We must take into account that the load_subtree() call from for_each_note_helper() (that is now done to correctly unpack the subtree while we're writing out the notes tree) may end up inserting unpacked non-notes into the linked list of non_note entries held by the struct notes_tree.

  Since we are in the process of writing out the notes tree, this linked list is currently in the process of being traversed by write_each_non_note_until().

  The unpacked non-notes are necessarily inserted between the last non-note we wrote out, and the next non-note to be written.

  Hence, we cannot simply hold the next_non_note to write in struct write_each_note_data (as we would then silently skip these newly inserted notes), but must instead always follow the ->next pointer from the last non-note we wrote. (This part was caught by an existing test in t3304.)

Title: Why parent is stored in git notes?

Body:
git notes was introduced in in commit 73f77b9, Git v1.6.6-rc0.

The notion of fanout was introduced with Git v1.7.1-rc0 in Feb. 2010 with commit 73f77b9, to determine optimal on-disk fanout for this part of the notes tree, in .git/refs/notes/commits.

Values of the 'fanout' variable:

0: No fanout (all notes are stored directly in the root notes tree)

1: 2/38 fanout

2: 2/2/36 fanout

3: 2/2/2/34 fanout

With Git 2.25.2 (March 2020), The code to automatically shrink the fan-out in the notes tree had an off-by-one bug, which has been killed.

See commit dbc2747, commit e1c5253 (03 Feb 2020) by Johan Herland (jherland).

(Merged by Junio C Hamano -- gitster -- in commit 8833260, 14 Feb 2020)

t3305: check notes fanout more carefully and robustly

In short, before this patch, this test script:

creates many notes

verifies that all notes in the notes tree has a fanout of 1

removes most notes

verifies that the notes in the notes tree now has a fanout of 0

The fanout verification only happened twice: after creating all the notes, and after removing most of them.

This patch strengthens the test by checking the fanout after _each_ added/removed note: We assert that the switch from fanout 0 -> 1 happens exactly once while adding notes (and that the switch pervades the entire notes tree). Likewise, we assert that the switch from fanout 1 -> 0 happens exactly once while removing notes.

Additionally, we decrease the number of notes left after removal, from 50 to 15 notes, in order to ensure that fanout 1 -> 0 transition keeps happening regardless of external factors (1).

(1): Currently (with the SHA1 hash function and the deterministic object ids of the test environment) the fanout heuristic in the notes code happens to switch from 0 -> 1 at 109 notes, and from 1 -> 0 at 59 notes.

  However, changing the hash function or other external factors will vary these numbers, and the latter may - in theory - go as low as 15.

  For more details, please see the discussion.

And:

notes.c: fix off-by-one error when decreasing notes fanout

As noted in the previous commit, the nature of the fanout heuristic in the notes code causes the exact point at which we increase or decrease the notes fanout to vary with the objects being annotated.

  Since the object ids generated by the test environment are deterministic (by design), the notes generated and tested by t3305 are always the same, and we therefore happen to see the same fanout behavior from one run to the next.

Coincidentally, if we were to change the test environment slightly (say by making a test commit on an unrelated branch before we start the t3305 test proper), we not only see the fanout switch happen at different points, we also manage to trigger a bug in the notes code where the fanout 1 -> 0 switch is not applied uniformly across the notes tree, but instead yields a notes tree like this:

...
bdeafb301e44b0e4db0f738a2d2a7beefdb70b70
bff2d39b4f7122bd4c5caee3de353a774d1e632a
d3/8ec8f851adf470131178085bfbaab4b12ad2a7
e0b173960431a3e692ae929736df3c9b73a11d5b
eb3c3aede523d729990ac25c62a93eb47c21e2e3
...

The bug occurs when we are writing out a notes tree with a newly decreased fanout, and the notes tree contains unexpanded subtrees that should be consolidated into the parent tree as a consequence of the decreased fanout):

Subtrees that happen to sit at an even level in the internal notes 16-tree structure (in other words: subtrees whose path - "d3" in the example above - is unique in the first nibble - i.e. there are no other note paths that start with "d") are not unpacked as part of the tree writeout.

  This error will repeat itself in subsequent note trees until the subtree is forced to be unpacked. In t3305 this only happens when the d38ec8f8 note is itself removed from the tree.

The error is not severe (no information is lost, and the notes code is able to read/decode this tree and manipulate it correctly), but this is nonetheless a bug in the current implementation that should be fixed.

That said, fixing the off-by-one error is not without complications:

We must take into account that the load_subtree() call from for_each_note_helper() (that is now done to correctly unpack the subtree while we're writing out the notes tree) may end up inserting unpacked non-notes into the linked list of non_note entries held by the struct notes_tree.

  Since we are in the process of writing out the notes tree, this linked list is currently in the process of being traversed by write_each_non_note_until().

  The unpacked non-notes are necessarily inserted between the last non-note we wrote out, and the next non-note to be written.

  Hence, we cannot simply hold the next_non_note to write in struct write_each_note_data (as we would then silently skip these newly inserted notes), but must instead always follow the ->next pointer from the last non-note we wrote. (This part was caught by an existing test in t3304.)


问:
can't seen in kubernetes cluster
I create a yaml file to create rabbitmq kubernetes cluster. I can see pods. But when I write kubectl get deployment. I cant see there. I can't access to rabbitmq ui page.</p>

```<code>apiVersion: v1
kind: Service
metadata:
  labels:
    app: rabbit
  name: rabbit
spec:
  ports:
  - port: 5672
    protocol: TCP
    name: mqtt
  - port: 15672
    protocol: TCP
    name: ui
  type: NodePort
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: rabbit
spec:
  serviceName: rabbit
  replicas: 3
  selector:
    matchLabels:
      app: rabbit
  template:
    metadata:
      labels:
        app: rabbit
    spec:
      containers:
        - name: rabbitmq
          image: rabbitmq
      nodeSelector:
        rabbitmq: "clustered"
</code>```

答:
statefulsets and deployments are different kubernetes resources. You have created statefulsets. That's why you don't see deployments. If you do

kubectl get statefulset you should see it and also both statefulset and deployment creates pod finally so you should be able to see rabbitmq pods if you do kubectl get pods

Since you have created a Nodeport service. You should be able to access it via http://nodeip:nodeport where nodeip is ip of any worker node in your kubernetes cluster.

You can get to know what is the Nodeport(a number between 30000-32767) by

```<code>kubectl describe services rabbit
</code>```

Here is the doc on accessing a Nodeport service from outside the cluster.

Title: can't seen in kubernetes cluster

Body:
I create a yaml file to create rabbitmq kubernetes cluster. I can see pods. But when I write kubectl get deployment. I cant see there. I can't access to rabbitmq ui page.

apiVersion: v1
kind: Service
metadata:
  labels:
    app: rabbit
  name: rabbit
spec:
  ports:
  - port: 5672
    protocol: TCP
    name: mqtt
  - port: 15672
    protocol: TCP
    name: ui
  type: NodePort
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: rabbit
spec:
  serviceName: rabbit
  replicas: 3
  selector:
    matchLabels:
      app: rabbit
  template:
    metadata:
      labels:
        app: rabbit
    spec:
      containers:
        - name: rabbitmq
          image: rabbitmq
      nodeSelector:
        rabbitmq: "clustered"

Body:
statefulsets and deployments are different kubernetes resources. You have created statefulsets. That's why you don't see deployments. If you do

kubectl get statefulset you should see it and also both statefulset and deployment creates pod finally so you should be able to see rabbitmq pods if you do kubectl get pods

Since you have created a Nodeport service. You should be able to access it via http://nodeip:nodeport where nodeip is ip of any worker node in your kubernetes cluster.

You can get to know what is the Nodeport(a number between 30000-32767) by

kubectl describe services rabbit

Here is the doc on accessing a Nodeport service from outside the cluster.


问:
Why include when you can require in PHP?
What is the point of attempting to include or include_once a library in PHP if you often have to use require or require_once instead (as they're usually critically important)?

答:
All four can take a local file or URL as input. require() and include() functions are virtually similar in their function except for the way they handle an irretrievable resource. include() and include_once() gives warning if the resource cannot be retrieved and try to continue execution of the program(if possible) while require() and require_once functions stops processing the page if they cannot find the resource.

It is best to use require_once() to include files which contains code and include_once() to include files that do not contains code e.g. HTML, CSS, etc. (This is my approach other's can differ.)

Also read this: http://arin.me/blog/php-require-vs-include-vs-require_once-vs-include_once-performance-test


问:
How to pass a CSV file to a Flask app running inside a Docker container?
I have a Flask app running inside Docker container. My app takes the path of a CSV file as input, processes it, and gives some results.

While creating the container I stored a CSV file inside the container itself to test the code. And now when everything is working fine I have to pass this CSV file from outside.

This is because for every API call there will be different CSV file.

Please note that the CSV file will be passed by end-user so it can't be anywhere on the system when we start the container. It will be received after running the container.

How can I provide this CSV file to my application?

答:
My app takes the path of a CSV file as input

It shouldn't take a path to a file. Your users won't have access to the server's filesystem, and your server doesn't have access to your clients' filesystem.

Instead, it should take a file payload in an HTTP request:

A <form> tag is marked with enctype=multipart/form-data and an <input type=file> is placed in that form

The application accesses the file from the files dictionary on the request object.

use the save() method of the file to save the file permanently somewhere on the filesystem.


问:
How can I pass an array to a function that cannot modify it?
I'm programming in C and I want to pass an array to a function; this function cannot modify the elements of the array. What is the correct syntax for the arguments of the function?

```<code>void func(const Foo array_in[])
</code>```

or

```<code>void func(Foo const array_in[])
</code>```

or maybe they are the same?
Thank you.

答:
First, the declarations const Foo array_in[] and Foo const array_in[] are exactly the same in C.

Second, when the parameter type of a function has "array of T" type, it is automatically adjusted to "pointer to T" type. So the compiler pretends as if you wrote:

```<code>void func(const Foo *array_in)
</code>```

or equivalently

```<code>void func(Foo const *array_in)
</code>```

Note that both const Foo *array_in and Foo const *array_in mean the exact same thing in C (pointer to const Foo). However, Foo * const array_in means something different (const pointer to Foo).

Body:
I'm programming in C and I want to pass an array to a function; this function cannot modify the elements of the array. What is the correct syntax for the arguments of the function?

void func(const Foo array_in[])

or

void func(Foo const array_in[])

or maybe they are the same?
Thank you.

Body:
First, the declarations const Foo array_in[] and Foo const array_in[] are exactly the same in C.

Second, when the parameter type of a function has "array of T" type, it is automatically adjusted to "pointer to T" type. So the compiler pretends as if you wrote:

void func(const Foo *array_in)

or equivalently

void func(Foo const *array_in)

Note that both const Foo *array_in and Foo const *array_in mean the exact same thing in C (pointer to const Foo). However, Foo * const array_in means something different (const pointer to Foo).


问:
Is there a way of using Python/Tkinter Canvas's highlightthickness using turtle?
I am extremely new to Python and just started working in turtle contrary to tkinter.

I've been trying to make a borderless window using overridedirect(True) and making the  background color
 of the window transparent by using wm_attributes("-transparentcolor", "color") which I had to use "turtle.Screen().getcanvas()._root()" to be able to use the mentioned methods using turtle.

using the two methods indeed removes the window's border and turns the background of the window transparent although there seems to be a "frame" that so far I haven't found a way to remove nor did I manage to figure out(or find online) how to apply highlightthickness=0 to my code/in turtle.

I attached an image showing the undesired frame, any help would be appreciated.
Thanks in advance,

-Omri

答:
Ended up making a Canvas, passed the Canvas into TurtleScreen and then passed TurtleScreen into RawTurtle.

Doing so allows me to draw analog clock hands using turtle on an analog clock image while still being able to make the window draggable,
with no border(without the undesired frame mentioned/linked above) and with a transparent background. Current clock


问:
GWT dev mode not accepting requests forwarded through router
Our application uses the PayPal api, in order to test it PayPal needs to be able to post data to a serlvet on our servers.  This is no problem in production however when running in GWT-Dev mode I cannot seem to get GWT to work through my home router.  GWT is running on port 8888 and I have added the needed firewall rules to get this to work.

Does GWT somehow stop requests from working from outside the local area network?  I tried -bindAddress 192.167.x.x  but it did not work.

答:
For security reasons the jetty server used in gwt dev mode only binds to localhost.

If you want to bind it to all intefaces use the parameter -bindAddress 0.0.0.0

To make sure the servlets are reachable try to connect from a different host on your network (e.g. with Telnet).


问:
How to take Multiple values input(with different types and separated with comma) from user in java
I want to accept multiple values from user like productName,Price,gstAmount like this:

```<code>sample input:2 //System.out.println("enter no of products");
mobile,2356,15
watch,200,10
</code>```

After this calculate the item with minimum price

```<code>sample output:watch
</code>```

答:
Do it as follows:

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

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter no of products: ");
        int np = Integer.parseInt(in.nextLine());
        String productName, minPricedProduct = "", input;
        String[] inputArr;
        int price, gst, grossPrice;
        int min = Integer.MAX_VALUE;
        for (int i = 1; i <= np; i++) {
            System.out.print("Enter Product name, Price, GST amount (like productname,1234,123): ");
            input = in.nextLine();
            inputArr = input.split(",");
            productName = inputArr[0];
            price = Integer.parseInt(inputArr[1]);
            gst = Integer.parseInt(inputArr[2]);
            grossPrice = price + gst;
            if (grossPrice < min) {
                min = grossPrice;
                minPricedProduct = productName;
            }
        }
        System.out.println(minPricedProduct);
    }
}
</code>```

A sample run:

```<code>Enter no of products: 3
Enter Product name, Price, GST amount (like productname,1234,123): spectacles,4500,125
Enter Product name, Price, GST amount (like productname,1234,123): watch,200,10
Enter Product name, Price, GST amount (like productname,1234,123): mobile,2356,15
watch
</code>```

Note: You should treat this program as a guide and try to improve it e.g. I've not done exception handling deliberately so that you can do it yourself and learn further.

Body:
I want to accept multiple values from user like productName,Price,gstAmount like this:

sample input:2 //System.out.println("enter no of products");
mobile,2356,15
watch,200,10

After this calculate the item with minimum price

sample output:watch

Body:
Do it as follows:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter no of products: ");
        int np = Integer.parseInt(in.nextLine());
        String productName, minPricedProduct = "", input;
        String[] inputArr;
        int price, gst, grossPrice;
        int min = Integer.MAX_VALUE;
        for (int i = 1; i <= np; i++) {
            System.out.print("Enter Product name, Price, GST amount (like productname,1234,123): ");
            input = in.nextLine();
            inputArr = input.split(",");
            productName = inputArr[0];
            price = Integer.parseInt(inputArr[1]);
            gst = Integer.parseInt(inputArr[2]);
            grossPrice = price + gst;
            if (grossPrice < min) {
                min = grossPrice;
                minPricedProduct = productName;
            }
        }
        System.out.println(minPricedProduct);
    }
}

A sample run:

Enter no of products: 3
Enter Product name, Price, GST amount (like productname,1234,123): spectacles,4500,125
Enter Product name, Price, GST amount (like productname,1234,123): watch,200,10
Enter Product name, Price, GST amount (like productname,1234,123): mobile,2356,15
watch

Note: You should treat this program as a guide and try to improve it e.g. I've not done exception handling deliberately so that you can do it yourself and learn further.


问:
C# While loop skipping virst line when parsing csv
I have a simple CSV file I need to parse that has variable column lengths. CSV File for reference.

I'm attempting to write some conditions to parse each line and store into a discreet string based off what value the first column contains in each line.

The first issue that I'm running into is that my loop seems to start reading at row 2. Is this because TextFieldParser assumes a header?

The second issue is that my if statements don't seem to be evaluating correctly. If I shift the order of the rows within the file, my first if in the order is supposed to parse the "Lighting" rows (regardless of which rows in the file contain "Lighting").

Just as a note, I am working in a .net 3.5 environment

Here's what I've got so far:

```<code>namespace CSV_Handler_Console
{
    public class Program
    {

        public static void Main(string[] args)
        {
            //Console.WriteLine("Press Enter");

            string filePath  = "C:\\Users\\chris\\Desktop\\ConfigFile.csv";

            string subLight = "Lighting";
            string subPin = "PIN";
            string subProc = "Processor";
            string subFab = "Fabuloso";
            string subQuirky = "Quirky";

            //string[] fields = csvParser.ReadFields();
            string category = string.Empty;
            string index = string.Empty;
            string load1 = string.Empty;
            string load2 = string.Empty;
            string load3 = string.Empty;
            string load4 = string.Empty;
            string value = string.Empty;

            string light1 = string.Empty;
            string light2 = string.Empty;
            string light3 = string.Empty;
            string pin = string.Empty;
            string processor1 = string.Empty;
            string processor2 = string.Empty;
            string processor3 = string.Empty;
            string processor4 = string.Empty;
            string processor5 = string.Empty;
            string processor6 = string.Empty;
            string processor7 = string.Empty;
            string processor8 = string.Empty;
            string display1 = string.Empty;
            string display2 = string.Empty;
            string display3 = string.Empty;
            string display4 = string.Empty;
            string display5 = string.Empty;
            string display6 = string.Empty;
            string display7 = string.Empty;
            string display8 = string.Empty;

            var path = String.Format("{0}", filePath);

            using (TextFieldParser csvParser = new TextFieldParser(path))
            {

                csvParser.SetDelimiters(new string[] { "," });
                //csvParser.HasFieldsEnclosedInQuotes = false;

                string row = csvParser.ReadLine();

                while (!csvParser.EndOfData)
                {
                        if (row.Contains(subLight))
                        {
                            string[] fields = csvParser.ReadFields();

                            category = fields[0];
                            index = fields[1];
                            load1 = fields[2];
                            load2 = fields[3];
                            load3 = fields[4];
                            load4 = fields[5];

                            if(index.Contains("1"))
                            {
                                light1 = row;
                            }
                            else if (index.Contains("2"))
                            {
                                light2 = row;
                            }
                            else if (index.Contains("3"))
                            {
                                light3 = row;
                            }

                            string rowData = string.Format("{0},{1},{2},{3},{4},{5}", category, index, load1, load2, load3, load4);
                            Console.WriteLine(rowData);
                            //Console.ReadLine();
                        }
                        else if (row.Contains(subPin))
                        {
                            string[] fields = csvParser.ReadFields();

                            category = fields[0];
                            index = fields[1];
                            value = fields[2];
                            string rowData = string.Format("{0},{1},{2}", category, index, value);
                            Console.WriteLine(rowData);
                        }
                        else if (row.Contains(subProc))
                        {
                            string[] fields = csvParser.ReadFields();

                            category = fields[0];
                            index = fields[1];
                            value = fields[2];

                            if (index.Contains("A"))
                            {
                                processor1 = row;
                            }
                            else if (index.Contains("B"))
                            {
                                processor2 = row;
                            }
                            else if (index.Contains("C"))
                            {
                                processor3 = row;
                            }
                            else if (index.Contains("D"))
                            {
                                processor4 = row;
                            }
                            else if (index.Contains("E"))
                            {
                                processor5 = row;
                            }
                            else if (index.Contains("F"))
                            {
                                processor6 = row;
                            }
                            else if (index.Contains("G"))
                            {
                                processor7 = row;
                            }
                            else if (index.Contains("H"))
                            {
                                processor8 = row;
                            }
                            string rowData = string.Format("{0},{1},{2}", category, index, value);
                            Console.WriteLine(rowData);
                        }
                        else if (row.Contains(subQuirky) || row.Contains(subFab))
                        {
                            string[] fields = csvParser.ReadFields();

                            category = fields[0];
                            index = fields[1];
                            value = fields[2];

                            if (index.Contains("A"))
                            {
                                display1 = row;
                            }
                            else if (index.Contains("B"))
                            {
                                display2 = row;
                            }
                            else if (index.Contains("C"))
                            {
                                display3 = row;
                            }
                            else if (index.Contains("D"))
                            {
                                display4 = row;
                            }
                            else if (index.Contains("E"))
                            {
                                display5 = row;
                            }
                            else if (index.Contains("F"))
                            {
                                display6 = row;
                            }
                            else if (index.Contains("G"))
                            {
                                display7 = row;
                            }
                            else if (index.Contains("H"))
                            {
                                display8 = row;
                            }
                            string rowData = string.Format("{0},{1},{2}", category, index, value);
                            Console.WriteLine(rowData);
                        }
                        else
                        {
                            Console.WriteLine("No Match Found");
                        }
                    }

                Console.ReadLine();

                }
        }

}
</code>```

Any guidance would be appreciated.

答:
It's your implementation. You first grab the first row with ReadLine, which advances the cursor to the next line. Then if the row contains your search property, you do a ReadFields, which is the 2nd line of the document.

If your data is always guaranteed to have the category, you could just use ReadFields and compare against the first element. You could look at PeekChars if you want to look at the content of the current row without advancing the cursor.

TextFieldParser.ReadLine: Returns the current line as a string and
  advances the cursor to the next line.

TextFieldParser.ReadFields: Reads all fields on the current line,
  returns them as an array of strings, and advances the cursor to the
  next line containing data.

TextFieldParser.PeekChars: Reads the specified number of characters without advancing the cursor.

Body:
I have a simple CSV file I need to parse that has variable column lengths. CSV File for reference.

I'm attempting to write some conditions to parse each line and store into a discreet string based off what value the first column contains in each line.

The first issue that I'm running into is that my loop seems to start reading at row 2. Is this because TextFieldParser assumes a header?

The second issue is that my if statements don't seem to be evaluating correctly. If I shift the order of the rows within the file, my first if in the order is supposed to parse the "Lighting" rows (regardless of which rows in the file contain "Lighting").

Just as a note, I am working in a .net 3.5 environment

Here's what I've got so far:

namespace CSV_Handler_Console
{
    public class Program
    {

        public static void Main(string[] args)
        {
            //Console.WriteLine("Press Enter");

            string filePath  = "C:\\Users\\chris\\Desktop\\ConfigFile.csv";

            string subLight = "Lighting";
            string subPin = "PIN";
            string subProc = "Processor";
            string subFab = "Fabuloso";
            string subQuirky = "Quirky";

            //string[] fields = csvParser.ReadFields();
            string category = string.Empty;
            string index = string.Empty;
            string load1 = string.Empty;
            string load2 = string.Empty;
            string load3 = string.Empty;
            string load4 = string.Empty;
            string value = string.Empty;

            string light1 = string.Empty;
            string light2 = string.Empty;
            string light3 = string.Empty;
            string pin = string.Empty;
            string processor1 = string.Empty;
            string processor2 = string.Empty;
            string processor3 = string.Empty;
            string processor4 = string.Empty;
            string processor5 = string.Empty;
            string processor6 = string.Empty;
            string processor7 = string.Empty;
            string processor8 = string.Empty;
            string display1 = string.Empty;
            string display2 = string.Empty;
            string display3 = string.Empty;
            string display4 = string.Empty;
            string display5 = string.Empty;
            string display6 = string.Empty;
            string display7 = string.Empty;
            string display8 = string.Empty;

            var path = String.Format("{0}", filePath);

            using (TextFieldParser csvParser = new TextFieldParser(path))
            {

                csvParser.SetDelimiters(new string[] { "," });
                //csvParser.HasFieldsEnclosedInQuotes = false;

                string row = csvParser.ReadLine();

                while (!csvParser.EndOfData)
                {
                        if (row.Contains(subLight))
                        {
                            string[] fields = csvParser.ReadFields();

                            category = fields[0];
                            index = fields[1];
                            load1 = fields[2];
                            load2 = fields[3];
                            load3 = fields[4];
                            load4 = fields[5];

                            if(index.Contains("1"))
                            {
                                light1 = row;
                            }
                            else if (index.Contains("2"))
                            {
                                light2 = row;
                            }
                            else if (index.Contains("3"))
                            {
                                light3 = row;
                            }

                            string rowData = string.Format("{0},{1},{2},{3},{4},{5}", category, index, load1, load2, load3, load4);
                            Console.WriteLine(rowData);
                            //Console.ReadLine();
                        }
                        else if (row.Contains(subPin))
                        {
                            string[] fields = csvParser.ReadFields();

                            category = fields[0];
                            index = fields[1];
                            value = fields[2];
                            string rowData = string.Format("{0},{1},{2}", category, index, value);
                            Console.WriteLine(rowData);
                        }
                        else if (row.Contains(subProc))
                        {
                            string[] fields = csvParser.ReadFields();

                            category = fields[0];
                            index = fields[1];
                            value = fields[2];

                            if (index.Contains("A"))
                            {
                                processor1 = row;
                            }
                            else if (index.Contains("B"))
                            {
                                processor2 = row;
                            }
                            else if (index.Contains("C"))
                            {
                                processor3 = row;
                            }
                            else if (index.Contains("D"))
                            {
                                processor4 = row;
                            }
                            else if (index.Contains("E"))
                            {
                                processor5 = row;
                            }
                            else if (index.Contains("F"))
                            {
                                processor6 = row;
                            }
                            else if (index.Contains("G"))
                            {
                                processor7 = row;
                            }
                            else if (index.Contains("H"))
                            {
                                processor8 = row;
                            }
                            string rowData = string.Format("{0},{1},{2}", category, index, value);
                            Console.WriteLine(rowData);
                        }
                        else if (row.Contains(subQuirky) || row.Contains(subFab))
                        {
                            string[] fields = csvParser.ReadFields();

                            category = fields[0];
                            index = fields[1];
                            value = fields[2];

                            if (index.Contains("A"))
                            {
                                display1 = row;
                            }
                            else if (index.Contains("B"))
                            {
                                display2 = row;
                            }
                            else if (index.Contains("C"))
                            {
                                display3 = row;
                            }
                            else if (index.Contains("D"))
                            {
                                display4 = row;
                            }
                            else if (index.Contains("E"))
                            {
                                display5 = row;
                            }
                            else if (index.Contains("F"))
                            {
                                display6 = row;
                            }
                            else if (index.Contains("G"))
                            {
                                display7 = row;
                            }
                            else if (index.Contains("H"))
                            {
                                display8 = row;
                            }
                            string rowData = string.Format("{0},{1},{2}", category, index, value);
                            Console.WriteLine(rowData);
                        }
                        else
                        {
                            Console.WriteLine("No Match Found");
                        }
                    }

                Console.ReadLine();

                }
        }

}

Any guidance would be appreciated.


问:
How to use Order By in a stored procedure without using dynamic SQL
I've the following MS SQL stored procedure. I need to sort the results without using dynamic SQL and sp_executesql method

@Order by can have the possible values ProductName ASC, ProductName DESC, ProductCode ASC, VendorName DESC, VendorCode or ClientName

I was trying to use ORDER BY CASE, is there any issue if the  ProductName, ProductCode are of different type?

```<code>ALTER PROCEDURE [dbo].[SortedReport]
(
    @ClientID INT,
    @RecordLimit,
    @FromDate DATETIME,
    @ToDate DATETIME,
    @OrderBy NVARCHAR(MAX)
)

AS
BEGIN

IF (@OrderBy IS NULL) BEGIN
    SET @OrderBy = 'ProductName';
END

SELECT TOP (@RecordLimit)
        sv.ClientID,
        sv.VendorID,
        sv.ProductID,
        sv.TransactionTime,
        sv.ClientName,
        sv.VendorName,
        sv.ProductName,
        sv.ProductCode,
        sv.VendorCode,
FROM SortedReportiew AS sv
WHERE (sv.ClientID = @ClientID)
    AND (sv.TransactionTime >= @FromDate)
    AND (sv.TransactionTime < @Date)
</code>```

Update:

Is the below part correct? ref from here

```<code>ORDER BY
    CASE @OrderBy WHEN 'ProductCode ASC' THEN ProductCode WHEN 'ProductCode DESC' THEN ProductCode END DESC,
    CASE @OrderBy WHEN 'ProductName ASC' THEN ProductName WHEN 'ProductName DESC' THEN ProductName END DESC,
</code>```

答:
As you already said: Use ORDER BY CASE, but multiple times to avoid the problems with different column types:

```<code>...
ORDER BY
 CASE WHEN @OrderBy ='ProductName ASC' THEN sv.ProductName END,
 CASE WHEN @OrderBy ='ProductName DESC' THEN sv.ProductName END DESC,
 CASE WHEN @OrderBy ='ProductCode ASC' THEN sv.ProductCode END,
 CASE WHEN @OrderBy ='ProductCode DESC' THEN sv.ProductCode END DESC,
 CASE WHEN @OrderBy ='VendorName ASC' THEN sv.VendorName END,
 CASE WHEN @OrderBy ='VendorName DESC' THEN sv.VendorName END DESC,
 CASE WHEN @OrderBy ='VendorCode' THEN sv.VendorCode END,
 CASE WHEN @OrderBy ='ClientName' THEN sv.ClientName END
</code>```

EDIT:

Updated the query to fit your updated question. I assume you meant ProductCode ASC and ProductCode DESC?

Body:
I've the following MS SQL stored procedure. I need to sort the results without using dynamic SQL and sp_executesql method

@Order by can have the possible values ProductName ASC, ProductName DESC, ProductCode ASC, VendorName DESC, VendorCode or ClientName

I was trying to use ORDER BY CASE, is there any issue if the  ProductName, ProductCode are of different type?

ALTER PROCEDURE [dbo].[SortedReport]
(
    @ClientID INT,
    @RecordLimit,
    @FromDate DATETIME,
    @ToDate DATETIME,
    @OrderBy NVARCHAR(MAX)
)

AS
BEGIN

IF (@OrderBy IS NULL) BEGIN
    SET @OrderBy = 'ProductName';
END

SELECT TOP (@RecordLimit)
        sv.ClientID,
        sv.VendorID,
        sv.ProductID,
        sv.TransactionTime,
        sv.ClientName,
        sv.VendorName,
        sv.ProductName,
        sv.ProductCode,
        sv.VendorCode,
FROM SortedReportiew AS sv
WHERE (sv.ClientID = @ClientID)
    AND (sv.TransactionTime >= @FromDate)
    AND (sv.TransactionTime < @Date)

Update:

Is the below part correct? ref from here

ORDER BY
    CASE @OrderBy WHEN 'ProductCode ASC' THEN ProductCode WHEN 'ProductCode DESC' THEN ProductCode END DESC,
    CASE @OrderBy WHEN 'ProductName ASC' THEN ProductName WHEN 'ProductName DESC' THEN ProductName END DESC,

Body:
As you already said: Use ORDER BY CASE, but multiple times to avoid the problems with different column types:

...
ORDER BY
 CASE WHEN @OrderBy ='ProductName ASC' THEN sv.ProductName END,
 CASE WHEN @OrderBy ='ProductName DESC' THEN sv.ProductName END DESC,
 CASE WHEN @OrderBy ='ProductCode ASC' THEN sv.ProductCode END,
 CASE WHEN @OrderBy ='ProductCode DESC' THEN sv.ProductCode END DESC,
 CASE WHEN @OrderBy ='VendorName ASC' THEN sv.VendorName END,
 CASE WHEN @OrderBy ='VendorName DESC' THEN sv.VendorName END DESC,
 CASE WHEN @OrderBy ='VendorCode' THEN sv.VendorCode END,
 CASE WHEN @OrderBy ='ClientName' THEN sv.ClientName END

EDIT:

Updated the query to fit your updated question. I assume you meant ProductCode ASC and ProductCode DESC?