问:
Values don't leave the stack after Pop (Stack<T>)
The stack is formed from a list that was grouped. Then there are several foreachs where Pop is called.
But the number of values in the stacks does not decrease.
Please explain why. Thank you in advance!

```<code>    public static void N(){
    var test = new List<int>(){1,1,1,2,2,3,3,3,3,4,4,5,6,7,7,7,7,8};
    var testGr = test.GroupBy(x=>x);

    var stacked = testGr.Select(x=> new {
        num = x.Key,
        stack = new Stack<int>(x)
    });

    var testNumOne = stacked.First(x=>x.num==1);
    Console.WriteLine(testNumOne.stack.Count());

    foreach(var x in new List<int>(){1,2,1,2,3}){
        var flush = stacked.First(y => y.num == x).stack.Pop();
    }

    testNumOne = stacked.First(x=>x.num==1);
    Console.WriteLine(testNumOne.stack.Count());
}
</code>```

答:
The copy of "stacked" solves the problem (through stacked.ToList())

```<code>public static void Main()
{
    var test = new List<int>(){1,1,1,2,2,3,3,3,3,4,4,5,6,7,7,7,7,8};
    var testGr = test.GroupBy(x=>x);

    var stacked = testGr.Select(x=> new {
        num = x.Key,
        stack = new Stack<int>(x)
    });
    var stackedCopy = stacked.ToList();
    var testNumOne = stackedCopy.First(x=>x.num==1);
    Console.WriteLine(testNumOne.stack.Count());

    foreach(var x in new List<int>(){1,2,1,2,3}){
        var flush = stackedCopy.First(y => y.num == x).stack.Pop();
    }

    testNumOne = stackedCopy.First(x=>x.num==1);
    Console.WriteLine(testNumOne.stack.Count());
}
</code>```

I'm already learning how the Linq library works with memory. Thank you all very much!)

Body:
The stack is formed from a list that was grouped. Then there are several foreachs where Pop is called.
But the number of values in the stacks does not decrease.
Please explain why. Thank you in advance!

    public static void N(){
    var test = new List<int>(){1,1,1,2,2,3,3,3,3,4,4,5,6,7,7,7,7,8};
    var testGr = test.GroupBy(x=>x);

    var stacked = testGr.Select(x=> new {
        num = x.Key,
        stack = new Stack<int>(x)
    });

    var testNumOne = stacked.First(x=>x.num==1);
    Console.WriteLine(testNumOne.stack.Count());

    foreach(var x in new List<int>(){1,2,1,2,3}){
        var flush = stacked.First(y => y.num == x).stack.Pop();
    }

    testNumOne = stacked.First(x=>x.num==1);
    Console.WriteLine(testNumOne.stack.Count());
}

Body:
The copy of "stacked" solves the problem (through stacked.ToList())

public static void Main()
{
    var test = new List<int>(){1,1,1,2,2,3,3,3,3,4,4,5,6,7,7,7,7,8};
    var testGr = test.GroupBy(x=>x);

    var stacked = testGr.Select(x=> new {
        num = x.Key,
        stack = new Stack<int>(x)
    });
    var stackedCopy = stacked.ToList();
    var testNumOne = stackedCopy.First(x=>x.num==1);
    Console.WriteLine(testNumOne.stack.Count());

    foreach(var x in new List<int>(){1,2,1,2,3}){
        var flush = stackedCopy.First(y => y.num == x).stack.Pop();
    }

    testNumOne = stackedCopy.First(x=>x.num==1);
    Console.WriteLine(testNumOne.stack.Count());
}

I'm already learning how the Linq library works with memory. Thank you all very much!)


来源: stackexchange

问:
How to set headers properly for suds soap client
I am trying to send a request to an api using suds client.

The request is formed like this:

```<code><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:v20="https://API">
   <soapenv:Header>
      <v20:apiHeader>
         <v20:username>username</v20:username>
         <v20:password>password</v20:password>
         <!--Optional:-->
         <v20:name>?</v20:name>
      </v20:apiHeader>
   </soapenv:Header>
   <soapenv:Body>
      <v20:getLoginDetails/>
   </soapenv:Body>
</soapenv:Envelope>
</code>```

I am sending the request for this like:

```<code>client = Client('https://wsdl', faults=False)

client.set_options(headers={'username': username 'authToken': auth_token, 'name': ''})
client.service.getLoginDetails()
</code>```

the error I am receiving is:

```<code>(<HTTPStatus.INTERNAL_SERVER_ERROR: 500>, (Fault){
   faultcode = "soap:Server"
   faultstring = "apiHeader should not be null"
   detail = ""
 })
</code>```

Is this how I should be sending the request? It is definitely something to do with the apiHeader I think; not sure what though, I get the same error using this:

```<code>username = Element('username').setText(name)
        password= Element('password').setText(pass)
        header_list = [username, pass]
        self.client.set_options(soapheaders=header_list)
        return self.client.service.getLoginDetails()
</code>```

答:
If you wish to add several elements to the SOAP header:

```<code>userName = Element('UserName').setText(config['fco.user'])
password = Element('Password').setText(config['fco.pwd'])
fdxns = Attribute('xmlns', "http://fdx.co.il/Authentication")
for field in userName, password:
    field.append(fdxns)
soapheaders = [userName, password]
client.set_options(soapheaders=tuple(soapheaders))
</code>```

This is working for me with Python 2.7, suds 0.4.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to send a request to an api using suds client.

The request is formed like this:

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:v20="https://API">
   <soapenv:Header>
      <v20:apiHeader>
         <v20:username>username</v20:username>
         <v20:password>password</v20:password>

         <v20:name>?</v20:name>
      </v20:apiHeader>
   </soapenv:Header>
   <soapenv:Body>
      <v20:getLoginDetails/>
   </soapenv:Body>
</soapenv:Envelope>

I am sending the request for this like:

client = Client('https://wsdl', faults=False)

client.set_options(headers={'username': username 'authToken': auth_token, 'name': ''})
client.service.getLoginDetails()

the error I am receiving is:

(<HTTPStatus.INTERNAL_SERVER_ERROR: 500>, (Fault){
   faultcode = "soap:Server"
   faultstring = "apiHeader should not be null"
   detail = ""
 })

Is this how I should be sending the request? It is definitely something to do with the apiHeader I think; not sure what though, I get the same error using this:

username = Element('username').setText(name)
        password= Element('password').setText(pass)
        header_list = [username, pass]
        self.client.set_options(soapheaders=header_list)
        return self.client.service.getLoginDetails()

Body:
If you wish to add several elements to the SOAP header:

userName = Element('UserName').setText(config['fco.user'])
password = Element('Password').setText(config['fco.pwd'])
fdxns = Attribute('xmlns', "http://fdx.co.il/Authentication")
for field in userName, password:
    field.append(fdxns)
soapheaders = [userName, password]
client.set_options(soapheaders=tuple(soapheaders))

This is working for me with Python 2.7, suds 0.4.

ContentLicense: CC BY-SA 4.0


问:
Nested array computations in Python using numpy
I am trying to use numpy in Python in solving my project.

I have a random binary array  rndm = [1, 0, 1, 1] and a resource_arr = [[2, 3], 4, 2, [1, 2]]. What I am trying to do is to multiply the array element wise, then get their sum. As an expected output for the sample above,
output = 5 0 2 3. I find hard to solve such problem because of the nested array/list.

So far my code looks like this:

```<code>   def fitness_score():

   output = numpy.add(rndm * resource_arr)
   return output

   fitness_score()
</code>```

I keep getting

```<code>ValueError: invalid number of arguments.
</code>```

For which I think is because of the addition that I am trying to do. Any help would be appreciated. Thank you!

答:
I have not worked much with pandas/numpy so I'm not sure if this is most efficient way, but it works (atleast for the example you have shown):

```<code>import numpy as np
rndm = [1, 0, 1, 1]
resource_arr = [[2, 3], 4, 2, [1, 2]]

multiplied_output = np.multiply(rndm, resource_arr)
print(multiplied_output)

output = []
for elem in multiplied_output:
  output.append(sum(elem)) if isinstance(elem, list) else output.append(elem)

final_output = np.array(output)
print(final_output)
</code>```

Body:
I am trying to use numpy in Python in solving my project.

I have a random binary array  rndm = [1, 0, 1, 1] and a resource_arr = [[2, 3], 4, 2, [1, 2]]. What I am trying to do is to multiply the array element wise, then get their sum. As an expected output for the sample above,
output = 5 0 2 3. I find hard to solve such problem because of the nested array/list.

So far my code looks like this:

   def fitness_score():

   output = numpy.add(rndm * resource_arr)
   return output

   fitness_score()

I keep getting

ValueError: invalid number of arguments.

For which I think is because of the addition that I am trying to do. Any help would be appreciated. Thank you!

Body:
I have not worked much with pandas/numpy so I'm not sure if this is most efficient way, but it works (atleast for the example you have shown):

import numpy as np
rndm = [1, 0, 1, 1]
resource_arr = [[2, 3], 4, 2, [1, 2]]

multiplied_output = np.multiply(rndm, resource_arr)
print(multiplied_output)

output = []
for elem in multiplied_output:
  output.append(sum(elem)) if isinstance(elem, list) else output.append(elem)

final_output = np.array(output)
print(final_output)


问:
Error while debugging using gdb debugger on VS Code using Windows 10 and MINGW complier
I was following the documentation on https://code.visualstudio.com/docs/cpp/config-mingw to set up my C++ development environment on VS code.

I succesfully created my build task and ran my build task, but when i tried to set up my debugger (GDB debugger), i got the following output on the terminal.

```<code>C:\Users\Ayon\c++\helloworld> cmd /C "c:\Users\Ayon\.vscode\extensions\ms-vscode.cpptools-0.28.1\debugAdapters\bin\WindowsDebugLauncher.exe --stdin=Microsoft-MIEngine-In-shlwrnf5.x12 --stdout=Microsoft-MIEngine-Out-vg12hskh.c52 --stderr=Microsoft-MIEngine-Error-nrcvh0zz.0u0 --pid=Microsoft-MIEngine-Pid-m1nmxyvs.qk2 --dbgExe=C:\MinGW\bin\gdb.exe --interpreter=mi "
'cmd' is not recognized as an internal or external command,
operable program or batch file.
</code>```

Im curious as to how the "cmd /" came about in the output. Please help me fix this error.

Thanks in advance.

For reference, here is my launch.json

```<code>{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "g++.exe - Build and debug active file",
            "type": "cppdbg",
            "request": "launch",
            "program": "${fileDirname}\\${fileBasenameNoExtension}.exe",
            "args": [],
            "stopAtEntry": false,
            "cwd": "${workspaceFolder}",
            "environment": [],
            "externalConsole": false,
            "MIMode": "gdb",
            "miDebuggerPath": "C:\\MinGW\\bin\\gdb.exe",
            "setupCommands": [
                {
                    "description": "Enable pretty-printing for gdb",
                    "text": "-enable-pretty-printing",
                    "ignoreFailures": true
                }
            ],
            "preLaunchTask": "g++.exe build active file"
        }
    ]
}
</code>```

答:
Did you add mingw64/bin to your system path? Here's how to do so:

```<code>Control panel -> Edit path -> Environment variables -> Path -> New
</code>```

You can also find more guidance on
vscode official website.

Body:
I was following the documentation on https://code.visualstudio.com/docs/cpp/config-mingw to set up my C++ development environment on VS code.

I succesfully created my build task and ran my build task, but when i tried to set up my debugger (GDB debugger), i got the following output on the terminal.

C:\Users\Ayon\c++\helloworld> cmd /C "c:\Users\Ayon\.vscode\extensions\ms-vscode.cpptools-0.28.1\debugAdapters\bin\WindowsDebugLauncher.exe --stdin=Microsoft-MIEngine-In-shlwrnf5.x12 --stdout=Microsoft-MIEngine-Out-vg12hskh.c52 --stderr=Microsoft-MIEngine-Error-nrcvh0zz.0u0 --pid=Microsoft-MIEngine-Pid-m1nmxyvs.qk2 --dbgExe=C:\MinGW\bin\gdb.exe --interpreter=mi "
'cmd' is not recognized as an internal or external command,
operable program or batch file.

Im curious as to how the "cmd /" came about in the output. Please help me fix this error.

Thanks in advance.

For reference, here is my launch.json

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "g++.exe - Build and debug active file",
            "type": "cppdbg",
            "request": "launch",
            "program": "${fileDirname}\\${fileBasenameNoExtension}.exe",
            "args": [],
            "stopAtEntry": false,
            "cwd": "${workspaceFolder}",
            "environment": [],
            "externalConsole": false,
            "MIMode": "gdb",
            "miDebuggerPath": "C:\\MinGW\\bin\\gdb.exe",
            "setupCommands": [
                {
                    "description": "Enable pretty-printing for gdb",
                    "text": "-enable-pretty-printing",
                    "ignoreFailures": true
                }
            ],
            "preLaunchTask": "g++.exe build active file"
        }
    ]
}

Body:
Did you add mingw64/bin to your system path? Here's how to do so:

Control panel -> Edit path -> Environment variables -> Path -> New

You can also find more guidance on
vscode official website.


问:
Convert decimal to string
While converting decimal value 0.00005 to string the code converts it to 5E-05.
The value 0.00005 is from a DataTable row.
How do I restrict converting the same to keep it 0.00005 instead of 5E-05? </p>

答: A decimal doesn't track any notional format internally - it is just the value (although it does include the precision, which can be different for values that evaluate as equal). You should specify the format explicitly when converting to a string; "general" is the shorter of "exponential" and "fixed-point", so you probably want to use "fixed-point" always; as such: try value.ToString("F{some size}") - for example "F5". Alternatively: use a custom format specifier to indicate the places you want explicitly.

Title: Convert decimal to string


问:
Does C++ calls member object 's overloaded operator?
```<code> #include <stdio.h>

 class InnerOne {
     int m_iDummy;
     public:
     InnerOne(int iDummy) {
         m_iDummy=iDummy;
     }

     InnerOne& operator=(InnerOne &obj) {
         printf("In InnerOne Operator=\n");
         m_iDummy = obj.m_iDummy;
         return *this;
     }

 };

 class OuterOne {
     InnerOne m_innerOne;
     public:
     OuterOne(int iVal) : m_innerOne(iVal) {
     }

 };

 int main() {
     OuterOne a(1);
     OuterOne b(2);
     a = b;
     return 1;
 }
</code>```

Will InnerOne 's operator = get called?
If yes then how and why?

答:
Yes. The compiler generated copy-assignment for OuterOne will invoke the operator= for InnerOne.

As a sidenote, its better if you write InnerOne copy-assignment as:

```<code>InnerOne& operator=(const InnerOne &obj)
                  //^^^^ add this!
</code>```

const is necessary, or else your code wouldn't work for the following:

```<code>const InnerOne x(10);
InnerOne y(10);

y = x; //compilation error - if you use your code
</code>```

See the error here : http://www.ideone.com/YMTJS

And once you add const as I suggested, it'll compile. See this : http://www.ideone.com/xj06z

Body:
 #include <stdio.h>

 class InnerOne {
     int m_iDummy;
     public:
     InnerOne(int iDummy) {
         m_iDummy=iDummy;
     }

     InnerOne& operator=(InnerOne &obj) {
         printf("In InnerOne Operator=\n");
         m_iDummy = obj.m_iDummy;
         return *this;
     }

 };

 class OuterOne {
     InnerOne m_innerOne;
     public:
     OuterOne(int iVal) : m_innerOne(iVal) {
     }

 };

 int main() {
     OuterOne a(1);
     OuterOne b(2);
     a = b;
     return 1;
 }

Will InnerOne 's operator = get called?
If yes then how and why?

Body:
Yes. The compiler generated copy-assignment for OuterOne will invoke the operator= for InnerOne.

As a sidenote, its better if you write InnerOne copy-assignment as:

InnerOne& operator=(const InnerOne &obj)
                  //^^^^ add this!

const is necessary, or else your code wouldn't work for the following:

const InnerOne x(10);
InnerOne y(10);

y = x; //compilation error - if you use your code

See the error here : http://www.ideone.com/YMTJS

And once you add const as I suggested, it'll compile. See this : http://www.ideone.com/xj06z


问:
core.js:6237 ERROR TypeError: Cannot set property 'area' of undefined
HTML: Here is my form. When I click the submit button I have got this error. I don't know Where I am getting wrong. Can you please help?

```<code><h3 class="page-header">Operator Form</h3>
<div class="outer-container">
   <form class="form-section" [formGroup]="operatorForm" (ngSubmit)="save()">
        <!-- <mat-form-field>
            <input matInput type="text" placeholder="Drone Type" formControlName="drone_type" required>
        </mat-form-field> -->
        <mat-form-field>
            <input matInput type="text" placeholder="Police Station" formControlName="police" readonly>
        </mat-form-field>
        <mat-form-field>
            <input matInput type="text" placeholder="Area" formControlName="area" required>
        </mat-form-field>
        <!-- <mat-form-field>
            <mat-label>Date and Time</mat-label>
             <input matInput [matDatepicker]="picker" formControlName="date" readonly/>
             <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
             <mat-datepicker #picker disabled="false"></mat-datepicker>
         </mat-form-field> -->
         <mat-form-field>
            <input matInput [ngxMatDatetimePicker]="picker" placeholder="Date and Time"
                formControlName="date"
                [disabled]="disabled">
            <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
            <ngx-mat-datetime-picker #picker [showSpinners]="showSpinners" [showSeconds]="showSeconds"
               [stepHour]="stepHour" [stepMinute]="stepMinute" [stepSecond]="stepSecond"
               [touchUi]="touchUi" [color]="color" [enableMeridian]="enableMeridian">
            </ngx-mat-datetime-picker>
         </mat-form-field>

        <div style="text-align: right">
            <button mat-raised-button type="submit" [disabled]="operatorForm.invalid" >Submit</button>
        </div>
    </form>
</div>
<div class="spinner" [style.display]="showSpinner ? 'flex' : 'none'">
    <mat-spinner [diameter]="30" ></mat-spinner>
</div>

</code>```

component.ts:(Here is my form.. when i click submit button I have got this error. dont know Where i am getting wrong.. can you please help? )

```<code>payload: any;
ngOnInit(){
   this.operatorForm = new FormGroup({
     'police': new FormControl(null, Validators.required),
     'area': new FormControl(null, Validators.required),
     'date': new FormControl(null, Validators.required),
    })
}
save() {
   this.payload.area = this.operatorForm.get('area').value
   this.payload.flightDateTimeStr = this.operatorForm.get('date').value,
   console.log(this.payload)
}
</code>```

答:
Try this :- </p>

```<code>payload ={};
  ngOnInit(){
     this.operatorForm = new FormGroup({

      'police': new FormControl(null, Validators.required),
      'area': new FormControl(null, Validators.required),
      'date': new FormControl(null, Validators.required),

     })
   }
  save(){
        this.payload["area"] = this.operatorForm.get('area').value
        this.payload["flightDateTimeStr"] = this.operatorForm.get('date').value,
      console.log(this.payload)
     }
</code>```

Body:
HTML: Here is my form. When I click the submit button I have got this error. I don't know Where I am getting wrong. Can you please help?

Operator Form

   <form class="form-section" [formGroup]="operatorForm" (ngSubmit)="save()">

        <mat-form-field>
            <input matInput type="text" placeholder="Police Station" formControlName="police" readonly>
        </mat-form-field>
        <mat-form-field>
            <input matInput type="text" placeholder="Area" formControlName="area" required>
        </mat-form-field>

         <mat-form-field>
            <input matInput [ngxMatDatetimePicker]="picker" placeholder="Date and Time"
                formControlName="date"
                [disabled]="disabled">
            <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
            <ngx-mat-datetime-picker #picker [showSpinners]="showSpinners" [showSeconds]="showSeconds"
               [stepHour]="stepHour" [stepMinute]="stepMinute" [stepSecond]="stepSecond"
               [touchUi]="touchUi" [color]="color" [enableMeridian]="enableMeridian">
            </ngx-mat-datetime-picker>
         </mat-form-field>

            <button mat-raised-button type="submit" [disabled]="operatorForm.invalid" >Submit</button>

    </form>

    <mat-spinner [diameter]="30" ></mat-spinner>

component.ts:(Here is my form.. when i click submit button I have got this error. dont know Where i am getting wrong.. can you please help? )

payload: any;
ngOnInit(){
   this.operatorForm = new FormGroup({
     'police': new FormControl(null, Validators.required),
     'area': new FormControl(null, Validators.required),
     'date': new FormControl(null, Validators.required),
    })
}
save() {
   this.payload.area = this.operatorForm.get('area').value
   this.payload.flightDateTimeStr = this.operatorForm.get('date').value,
   console.log(this.payload)
}

Body:
Try this :-

payload ={};
  ngOnInit(){
     this.operatorForm = new FormGroup({

      'police': new FormControl(null, Validators.required),
      'area': new FormControl(null, Validators.required),
      'date': new FormControl(null, Validators.required),

     })
   }
  save(){
        this.payload["area"] = this.operatorForm.get('area').value
        this.payload["flightDateTimeStr"] = this.operatorForm.get('date').value,
      console.log(this.payload)
     }


问:
Parsing a String into List of information KOTLIN
I am an amateur Kotlin programming. And I have one task which I am not sure how to solve.
So any help would come in handy.

More about this task:

I get this message via HTTP post request

AL:OK:XX:XX:XX:XX:XX:YY~~TYPE:3~~FOF:v1.0~~RSSI:-68~~PORT:8215~~TEMP:34.22~~CH1:OK~~CH2:KS~~CH3:PR~~CH4:VL~~CH5:KS~~CH6:OK~~AUX1:OK~~AUX2:KS~~AUX3:OK

And I need to parse this message into following output format.

XX:XX:XX:XX:XX:XY - MAC ADDRESS

3 - Type of device

v1.0 - Version of device

-68 - Signal strenght

8215 - Server Port

34.22 - Processor temperature

I only need to get this output in console

I would be really thankfull for any kind of help or hints about this problem.

Thank you in advance,

答:
You can use regex group for this purpose and get each part with index. also you can Assign name to each group and then select each part you want with name.</p>

```<code>import java.util.regex.Pattern

fun main() {

    val request = "AL:OK:XX:XX:XX:XX:XX:YY~~TYPE:3~~FOF:v1.0~~RSSI:-68~~PORT:8215~~TEMP:34.22" +
            "~~CH1:OK~~CH2:KS~~CH3:PR~~CH4:VL~~CH5:KS~~CH6:OK" +
            "~~AUX1:OK~~AUX2:KS~~AUX3:OK"

    extractValues(request)
}

fun extractValues(request: String) {
    val patternWithName = "AL:OK:(?<macAddress>.+)~~TYPE:(?<type>\\d+)~~FOF:(?<fof>v\\d+.\\d+)~~RSSI:(?<rssi>[-+]\\d+)~~PORT:(?<port>\\d+)~~TEMP:(?<temp>\\d+.\\d+)" +
            "~~CH1:(?<ch1>.+)~~CH2:(?<ch2>.+)~~CH3:(?<ch3>.+)~~CH4:(?<ch4>.+)~~CH5:(?<ch5>.+)~~CH6:(?<ch6>.+)" +
            "~~AUX1:(?<aux1>.+)~~AUX2:(?<aux2>.+)~~AUX3:(?<aux3>.+)"

    val patternWithoutName = "AL:OK:(.+)~~TYPE:(\\d+)~~FOF:(v\\d+.\\d+)~~RSSI:([-+]\\d+)~~PORT:(\\d+)~~TEMP:(\\d+.\\d+)" +
            "~~CH1:(.+)~~CH2:(.+)~~CH3:(.+)~~CH4:(.+)~~CH5:(.+)~~CH6:(.+)" +
            "~~AUX1:(.+)~~AUX2:(.+)~~AUX3:(.+)"

    val matcher = Pattern.compile(patternWithoutName).matcher(request)

    if (matcher.find()) {
        // get with their name --> use [patternWithName]
        // val macAddress = matcher.group("macAddress")
        // val type = matcher.group("type")
        // val fof = matcher.group("fof")

        // or
        // get with index -- use [patternWithName] or [patternWithoutName]
        for (i in 1..matcher.groupCount()) {
            println(matcher.group(i))
        }
    } else {
        error("$request doesn't match.")
    }
}
</code>```

Body:
You can use regex group for this purpose and get each part with index. also you can Assign name to each group and then select each part you want with name.

import java.util.regex.Pattern

fun main() {

    val request = "AL:OK:XX:XX:XX:XX:XX:YY~~TYPE:3~~FOF:v1.0~~RSSI:-68~~PORT:8215~~TEMP:34.22" +
            "~~CH1:OK~~CH2:KS~~CH3:PR~~CH4:VL~~CH5:KS~~CH6:OK" +
            "~~AUX1:OK~~AUX2:KS~~AUX3:OK"

    extractValues(request)
}

fun extractValues(request: String) {
    val patternWithName = "AL:OK:(?<macAddress>.+)~~TYPE:(?<type>\\d+)~~FOF:(?<fof>v\\d+.\\d+)~~RSSI:(?<rssi>[-+]\\d+)~~PORT:(?<port>\\d+)~~TEMP:(?<temp>\\d+.\\d+)" +
            "~~CH1:(?<ch1>.+)~~CH2:(?<ch2>.+)~~CH3:(?<ch3>.+)~~CH4:(?<ch4>.+)~~CH5:(?<ch5>.+)~~CH6:(?<ch6>.+)" +
            "~~AUX1:(?<aux1>.+)~~AUX2:(?<aux2>.+)~~AUX3:(?<aux3>.+)"

    val patternWithoutName = "AL:OK:(.+)~~TYPE:(\\d+)~~FOF:(v\\d+.\\d+)~~RSSI:([-+]\\d+)~~PORT:(\\d+)~~TEMP:(\\d+.\\d+)" +
            "~~CH1:(.+)~~CH2:(.+)~~CH3:(.+)~~CH4:(.+)~~CH5:(.+)~~CH6:(.+)" +
            "~~AUX1:(.+)~~AUX2:(.+)~~AUX3:(.+)"

    val matcher = Pattern.compile(patternWithoutName).matcher(request)

    if (matcher.find()) {
        // get with their name --> use [patternWithName]
        // val macAddress = matcher.group("macAddress")
        // val type = matcher.group("type")
        // val fof = matcher.group("fof")

        // or
        // get with index -- use [patternWithName] or [patternWithoutName]
        for (i in 1..matcher.groupCount()) {
            println(matcher.group(i))
        }
    } else {
        error("$request doesn't match.")
    }
}


问:
JavaScript : Regular expression
The subject exists but I don't understand here: (I am beginner)

Check whether a string matches a regex in JS

In fact, I have a form name, in my validation I would like to avoid that the user enters numbers or symbols.

function validation()
{
    const name = document.getElementById('name').value;

    if(!name){
        document.getElementById('nameError').innerHTML = " ** Empty ! ";
        return false;
    }

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form action="#" onsubmit="return validation()" >
  <br>
  <label>Name </label>
  <br>
  <input type="text" name="name" id="name" placeholder="Your name">
  <br>
  <span id="nameError"></span>
  <br>
  <input type="submit" value="ok">
</form></code>```

Thank you very much for your help.

答:
In your validation function, you can verify if the variable name contains only characters using a regex.

Please check the snippet below:

```<code>function validation() {
    const letters = /^[A-Za-z]+$/;
    const name = document.getElementById('name').value;
    if (name.match(letters)) {
        // contains only characters
    } else {
        // contains non-character values
    }
}
</code>```

Title: JavaScript : Regular expression

Body:
The subject exists but I don't understand here: (I am beginner)

Check whether a string matches a regex in JS

In fact, I have a form name, in my validation I would like to avoid that the user enters numbers or symbols.

function validation()
{
    const name = document.getElementById('name').value;

    if(!name){
        document.getElementById('nameError').innerHTML = " ** Empty ! ";
        return false;
    }

}

<form action="#" onsubmit="return validation()" >

  Name

  <input type="text" name="name" id="name" placeholder="Your name">

  <input type="submit" value="ok">
</form>

Thank you very much for your help.

Body:
In your validation function, you can verify if the variable name contains only characters using a regex.

Please check the snippet below:

function validation() {
    const letters = /^[A-Za-z]+$/;
    const name = document.getElementById('name').value;
    if (name.match(letters)) {
        // contains only characters
    } else {
        // contains non-character values
    }
}


问:
Update script not working and no error shows
I am a newbie updating the database (i have skipped some steps so that i do some things quicker) I have this code but the database does not update and i do not get any error.</p>

```<code><?php
require_once '../includes/configuration.php';

if (isset($_POST['enter']))
{
    $_POST['employee_id_passport'] = $employee_id_passport;
    $_POST['first_name'] = $first_name;
    $_POST['surname'] = $surname;
    $_POST['mobile_number'] = $mobile_number;
    $sql_query_update = "UPDATE employee_master
                             SET first_name = '$first_name',
                             surname = '$surname',
                             mobile_number = '$mobile_number'
                             WHERE employee_id_passport = '$employee_id_passport'";
            $result = mysql_query($sql_query_update, $connection);
    echo "this";

}
else
    {

            //display form with employee details
            if (isset($_GET['idno']))
            {
                $employee_id_passport = $_GET['idno'];

                $sql_get_employee_details_query = "SELECT * FROM employee_master WHERE employee_id_passport = '$employee_id_passport'";
                $result = mysql_query($sql_get_employee_details_query, $connection);
                $row = mysql_fetch_assoc($result);
                echo $row['employee_id_passport'] . "<br /> " . $row['surname'] . "<br /> " . $row['first_name'] . "<br /> " . $row['mobile_number'] . "<br /> ";

                echo "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"";
                echo "\"http:www.w3.org/TR/xhthml1/DTD/xhtml1-transitional.dtd\">";

                echo "<html xmls=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">";

                echo "<head>";
                echo    "<title> </title>";

                echo    "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\" />";
                echo "</head>";

                echo "<body>";
                echo   "<form name=\"view_employee\" method=\"POST\" action=\"" .  $_SERVER['PHP_SELF'] . " \"   />";
                echo        "Employee ID/Passport: <input type=\"text\" name=\"id_passport\" disabled=\"disabled\" value=\" " .  $row['employee_id_passport'] . "\" /> <br />";
                echo        "First Name: <input type=\"text\" name=\"first_name\" value=\" ".  $row['first_name'] .  "\" /> <br />";
                echo        "Surname: <input type=\"text\" name=\"surname\" value=\" " .  $row['surname'] . "\" /> <br />";
                echo        "Mobile Number: <input type=\"text\" name=\"mobile_number\" value=\" " .   $row['mobile_number'] . "\"/> <br />";
                echo        "<input type=\"submit\" value=\"enter\" name=\"submit\" />";
                echo    "</form>";
                echo "</body>";

                echo "<html>";
            }
    }

?>
</code>```

答:
It looks like you've assigned the sql query string to a variable but not actually run it.

```<code>if (isset($_POST['enter']))
{
    $_POST['employee_id_passport'] = $employee_id_passport;
    $_POST['first_name'] = $first_name;
    $_POST['surname'] = $surname;
    $_POST['mobile_number'] = $mobile_number;
    $sql_query_update = "UPDATE employee_master SET first_name = '$first_name', surname = '$surname', mobile_number = '$mobile_number' WHERE employee_id_passport = '$employee_id_passport'";
    mysql_query( $sql_query_update ); // This line will run the update query
    echo "this";

}
</code>```

adding in the 'mysql_query( $sql_query_update );' line should execute the query for you.

Body:
I am a newbie updating the database (i have skipped some steps so that i do some things quicker) I have this code but the database does not update and i do not get any error.

<?php
require_once '../includes/configuration.php';

if (isset($_POST['enter']))
{
    $_POST['employee_id_passport'] = $employee_id_passport;
    $_POST['first_name'] = $first_name;
    $_POST['surname'] = $surname;
    $_POST['mobile_number'] = $mobile_number;
    $sql_query_update = "UPDATE employee_master
                             SET first_name = '$first_name',
                             surname = '$surname',
                             mobile_number = '$mobile_number'
                             WHERE employee_id_passport = '$employee_id_passport'";
            $result = mysql_query($sql_query_update, $connection);
    echo "this";

}
else
    {

            //display form with employee details
            if (isset($_GET['idno']))
            {
                $employee_id_passport = $_GET['idno'];

                $sql_get_employee_details_query = "SELECT * FROM employee_master WHERE employee_id_passport = '$employee_id_passport'";
                $result = mysql_query($sql_get_employee_details_query, $connection);
                $row = mysql_fetch_assoc($result);
                echo $row['employee_id_passport'] . "
 " . $row['surname'] . "
 " . $row['first_name'] . "
 " . $row['mobile_number'] . "
 ";

                echo "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"";
                echo "\"http:www.w3.org/TR/xhthml1/DTD/xhtml1-transitional.dtd\">";

                echo "";

                echo "";
                echo    "<title> </title>";

                echo    "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\" />";
                echo "";

                echo "";
                echo   "<form name=\"view_employee\" method=\"POST\" action=\"" .  $_SERVER['PHP_SELF'] . " \"   />";
                echo        "Employee ID/Passport: <input type=\"text\" name=\"id_passport\" disabled=\"disabled\" value=\" " .  $row['employee_id_passport'] . "\" />
";
                echo        "First Name: <input type=\"text\" name=\"first_name\" value=\" ".  $row['first_name'] .  "\" />
";
                echo        "Surname: <input type=\"text\" name=\"surname\" value=\" " .  $row['surname'] . "\" />
";
                echo        "Mobile Number: <input type=\"text\" name=\"mobile_number\" value=\" " .   $row['mobile_number'] . "\"/>
";
                echo        "<input type=\"submit\" value=\"enter\" name=\"submit\" />";
                echo    "</form>";
                echo "";

                echo "";
            }
    }

?>

Body:
It looks like you've assigned the sql query string to a variable but not actually run it.

if (isset($_POST['enter']))
{
    $_POST['employee_id_passport'] = $employee_id_passport;
    $_POST['first_name'] = $first_name;
    $_POST['surname'] = $surname;
    $_POST['mobile_number'] = $mobile_number;
    $sql_query_update = "UPDATE employee_master SET first_name = '$first_name', surname = '$surname', mobile_number = '$mobile_number' WHERE employee_id_passport = '$employee_id_passport'";
    mysql_query( $sql_query_update ); // This line will run the update query
    echo "this";

}

adding in the 'mysql_query( $sql_query_update );' line should execute the query for you.


问:
PHP randomly assign people to a team
I'm currently building up a little game, where users need to be randomly assigned to teams.

What I got is a table in the database, where the logged in users are listed. Also, each user has a column for the team.

Now in PHP, I got all users stored in a variable, like the following (output of var_export)

```<code>array ( 0 => array ( 'ID' => '3', 'name' => 'olaf', 'team' => NULL, ), 1 => array ( 'ID' => '4', 'name' => 'Peter', 'team' => NULL, ), 2 => array ( 'ID' => '5', 'name' => 'chris', 'team' => NULL, ), 3 => array ( 'ID' => '6', 'name' => 'günther', 'team' => NULL, ), )
</code>```

Now I got two teams, Team Red and Team Blue. My goal is, that every person has randomly been assigned to one of the two teams, however, both teams should have a similar amount of team members (or if an odd number of users is logged in, one team can have one more player).

When assigned, I would then write the information to the database. However, I'd like to always be able to shuffle the teams and then have new teams.

The number of logged in users can vary between 2 and 50 persons.

So far, I thought about multiple ways of doing it, like randomly picking a number between 1 and sizeof(array of users) and then assigning him a team, however, I couldn't get it to work...

Also I this Stackoverflow post, however, using this code, my team Red always had player 1 and 3 or 1 and 4 and my team Blue always had player 2 and 3 or 2 and 4. It never happened, that player 1 was in team red. However, as mentioned, the mix should be completely random.

Can anybody help me out with this or has an idea, how I could manage to do that?

答:
I have managed to solve your problem. You can now easily reset the teams by calling createTeams($playerArray);. The function first checks if there's an even amount of players. If that is the case then every team gets half of total players. Otherwise, a team randomly gets 1 more or less player by rounding the $playersPerTeam up or down. Next it shuffles the player array 4 times to create a random player list.

After that you have two options of return values. The first one picks the asigned number of players from the $players array. Then it returns an array with the teams.

The other, last, way involves the same method as the first but now it sets the [team] variable of the player object as well. Then it returns the $players array but with the assigned team name.

function createTeams($players) {
  $totalPlayers = count($players);

  if($totalPlayers % 2 == 0) { //even amount of players
    $playersRed = $playersBlue = $totalPlayers / 2;
  } else { //odd amount of players
    $randInt = rand(1,100);
    $playersPerTeam = $totalPlayers / 2;
    if($randInt <= 50) { //team red has an advantage of 1 extra player
      $playersRed = round($playersPerTeam, 0, PHP_ROUND_HALF_UP);
      $playersBlue = round($playersPerTeam, 0, PHP_ROUND_HALF_DOWN);
    } else { //team blue has an advantage of 1 extra player
      $playersRed = round($playersPerTeam, 0, PHP_ROUND_HALF_DOWN);
      $playersBlue = round($playersPerTeam, 0, PHP_ROUND_HALF_UP);
    }
  }

  //This should be random enough for this purpose
  for ($i=0; $i < 4; $i++) {
    shuffle($players);
  }

  //One way to return the teams.
  // $teamRed  = array_slice($players, 0, $playersRed);
  // $teamBlue = array_slice($players, $playersRed, $playersBlue);
  // return array('red' => $teamRed , 'blue' => $teamBlue);

  //Other way to return the createTeams
  for ($i=0; $i < $totalPlayers; $i++) {
    if ($i < $playersRed) { //player is gonna be in team red
      $players[$i]['team'] = 'red';
    } else { //player is gonna be in team blue
      $players[$i]['team'] = 'blue';
    }
  }
  return $players;
}

```
<p>Testing it with this player array:</p>
<pre class="lang-php prettyprint-override"><code>$players = array ( 0 => array ( 'ID' => '3', 'name' => 'olaf', 'team' => NULL), 1 => array ( 'ID' => '4', 'name' => 'Peter', 'team' => NULL), 2 => array ( 'ID' => '5', 'name' => 'chris', 'team' => NULL), 3 => array ( 'ID' => '6', 'name' => 'günther', 'team' => NULL), 4 => array ( 'ID' => '7', 'name' => 'Max', 'team' => NULL));

for ($i=0; $i < 5; $i++) {
  print_r(createTeams($players));
  echo "<br><br>";
}

</code>```

Gives the following output:

Array ( [0] => Array ( [ID] => 4 [name] => Peter [team] => red ) [1] => Array ( [ID] => 6 [name] => günther [team] => red ) [2] => Array ( [ID] => 5 [name] => chris [team] => blue ) [3] => Array ( [ID] => 7 [name] => Max [team] => blue ) [4] => Array ( [ID] => 3 [name] => olaf [team] => blue ) )

Array ( [0] => Array ( [ID] => 3 [name] => olaf [team] => red ) [1] => Array ( [ID] => 5 [name] => chris [team] => red ) [2] => Array ( [ID] => 6 [name] => günther [team] => red ) [3] => Array ( [ID] => 4 [name] => Peter [team] => blue ) [4] => Array ( [ID] => 7 [name] => Max [team] => blue ) )

Array ( [0] => Array ( [ID] => 3 [name] => olaf [team] => red ) [1] => Array ( [ID] => 6 [name] => günther [team] => red ) [2] => Array ( [ID] => 5 [name] => chris [team] => blue ) [3] => Array ( [ID] => 4 [name] => Peter [team] => blue ) [4] => Array ( [ID] => 7 [name] => Max [team] => blue ) )

Array ( [0] => Array ( [ID] => 6 [name] => günther [team] => red ) [1] => Array ( [ID] => 7 [name] => Max [team] => red ) [2] => Array ( [ID] => 3 [name] => olaf [team] => blue ) [3] => Array ( [ID] => 5 [name] => chris [team] => blue ) [4] => Array ( [ID] => 4 [name] => Peter [team] => blue ) )

Array ( [0] => Array ( [ID] => 5 [name] => chris [team] => red ) [1] => Array ( [ID] => 6 [name] => günther [team] => red ) [2] => Array ( [ID] => 3 [name] => olaf [team] => red ) [3] => Array ( [ID] => 4 [name] => Peter [team] => blue ) [4] => Array ( [ID] => 7 [name] => Max [team] => blue ) )

Hope this helps! If not, please comment.

Title: PHP randomly assign people to a team

Body:
I'm currently building up a little game, where users need to be randomly assigned to teams.

What I got is a table in the database, where the logged in users are listed. Also, each user has a column for the team.

Now in PHP, I got all users stored in a variable, like the following (output of var_export)

array ( 0 => array ( 'ID' => '3', 'name' => 'olaf', 'team' => NULL, ), 1 => array ( 'ID' => '4', 'name' => 'Peter', 'team' => NULL, ), 2 => array ( 'ID' => '5', 'name' => 'chris', 'team' => NULL, ), 3 => array ( 'ID' => '6', 'name' => 'günther', 'team' => NULL, ), )

Now I got two teams, Team Red and Team Blue. My goal is, that every person has randomly been assigned to one of the two teams, however, both teams should have a similar amount of team members (or if an odd number of users is logged in, one team can have one more player).

When assigned, I would then write the information to the database. However, I'd like to always be able to shuffle the teams and then have new teams.

The number of logged in users can vary between 2 and 50 persons.

So far, I thought about multiple ways of doing it, like randomly picking a number between 1 and sizeof(array of users) and then assigning him a team, however, I couldn't get it to work...

Also I this Stackoverflow post, however, using this code, my team Red always had player 1 and 3 or 1 and 4 and my team Blue always had player 2 and 3 or 2 and 4. It never happened, that player 1 was in team red. However, as mentioned, the mix should be completely random.

Can anybody help me out with this or has an idea, how I could manage to do that?

Body:
I have managed to solve your problem. You can now easily reset the teams by calling createTeams($playerArray);. The function first checks if there's an even amount of players. If that is the case then every team gets half of total players. Otherwise, a team randomly gets 1 more or less player by rounding the $playersPerTeam up or down. Next it shuffles the player array 4 times to create a random player list.

After that you have two options of return values. The first one picks the asigned number of players from the $players array. Then it returns an array with the teams.

The other, last, way involves the same method as the first but now it sets the [team] variable of the player object as well. Then it returns the $players array but with the assigned team name.

function createTeams($players) {
  $totalPlayers = count($players);

  if($totalPlayers % 2 == 0) { //even amount of players
    $playersRed = $playersBlue = $totalPlayers / 2;
  } else { //odd amount of players
    $randInt = rand(1,100);
    $playersPerTeam = $totalPlayers / 2;
    if($randInt <= 50) { //team red has an advantage of 1 extra player
      $playersRed = round($playersPerTeam, 0, PHP_ROUND_HALF_UP);
      $playersBlue = round($playersPerTeam, 0, PHP_ROUND_HALF_DOWN);
    } else { //team blue has an advantage of 1 extra player
      $playersRed = round($playersPerTeam, 0, PHP_ROUND_HALF_DOWN);
      $playersBlue = round($playersPerTeam, 0, PHP_ROUND_HALF_UP);
    }
  }

  //This should be random enough for this purpose
  for ($i=0; $i < 4; $i++) {
    shuffle($players);
  }

  //One way to return the teams.
  // $teamRed  = array_slice($players, 0, $playersRed);
  // $teamBlue = array_slice($players, $playersRed, $playersBlue);
  // return array('red' => $teamRed , 'blue' => $teamBlue);

  //Other way to return the createTeams
  for ($i=0; $i < $totalPlayers; $i++) {
    if ($i < $playersRed) { //player is gonna be in team red
      $players[$i]['team'] = 'red';
    } else { //player is gonna be in team blue
      $players[$i]['team'] = 'blue';
    }
  }
  return $players;
}

Testing it with this player array:

$players = array ( 0 => array ( 'ID' => '3', 'name' => 'olaf', 'team' => NULL), 1 => array ( 'ID' => '4', 'name' => 'Peter', 'team' => NULL), 2 => array ( 'ID' => '5', 'name' => 'chris', 'team' => NULL), 3 => array ( 'ID' => '6', 'name' => 'günther', 'team' => NULL), 4 => array ( 'ID' => '7', 'name' => 'Max', 'team' => NULL));

for ($i=0; $i < 5; $i++) {
  print_r(createTeams($players));
  echo "<br><br>";
}

Gives the following output:

Array ( [0] => Array ( [ID] => 4 [name] => Peter [team] => red ) [1] => Array ( [ID] => 6 [name] => günther [team] => red ) [2] => Array ( [ID] => 5 [name] => chris [team] => blue ) [3] => Array ( [ID] => 7 [name] => Max [team] => blue ) [4] => Array ( [ID] => 3 [name] => olaf [team] => blue ) )

Array ( [0] => Array ( [ID] => 3 [name] => olaf [team] => red ) [1] => Array ( [ID] => 5 [name] => chris [team] => red ) [2] => Array ( [ID] => 6 [name] => günther [team] => red ) [3] => Array ( [ID] => 4 [name] => Peter [team] => blue ) [4] => Array ( [ID] => 7 [name] => Max [team] => blue ) )

Array ( [0] => Array ( [ID] => 3 [name] => olaf [team] => red ) [1] => Array ( [ID] => 6 [name] => günther [team] => red ) [2] => Array ( [ID] => 5 [name] => chris [team] => blue ) [3] => Array ( [ID] => 4 [name] => Peter [team] => blue ) [4] => Array ( [ID] => 7 [name] => Max [team] => blue ) )

Array ( [0] => Array ( [ID] => 6 [name] => günther [team] => red ) [1] => Array ( [ID] => 7 [name] => Max [team] => red ) [2] => Array ( [ID] => 3 [name] => olaf [team] => blue ) [3] => Array ( [ID] => 5 [name] => chris [team] => blue ) [4] => Array ( [ID] => 4 [name] => Peter [team] => blue ) )

Array ( [0] => Array ( [ID] => 5 [name] => chris [team] => red ) [1] => Array ( [ID] => 6 [name] => günther [team] => red ) [2] => Array ( [ID] => 3 [name] => olaf [team] => red ) [3] => Array ( [ID] => 4 [name] => Peter [team] => blue ) [4] => Array ( [ID] => 7 [name] => Max [team] => blue ) )

Hope this helps! If not, please comment.


问:
Vector invalid subscript. SFML
I'm trying to make a snake game and maybe this error is one of possible. So when I'm debugging and stepping over then I getting link to exception in header file of vector and in exception code wrote that vector has invalid subscript. (Error cause can called by vector bodyPart). The compiler message:

Unhandled exception at 0x00007FFA227EA799 in snake.exe: Microsoft C++ exception: std::out_of_range at memory location 0x00000052FA7CDFD0.

```<code>Snake::Snake(RenderWindow& window)
{
    bodyPart.setPosition(window.getSize().x / 4, window.getSize().y / 4);
    bodyPart.setSize(Vector2f(20.f, 20.f));
    bodyPart.setFillColor(Color(0, 0, 0));
    body.push_back(bodyPart);
}
//Sets default parameters
void Game::restart(RenderWindow& window)
{
    for (int i = 0; i < snake.body.size() - 1; i++)
    {
        snake.body.pop_back();
    }
    snake.bodyPart.setPosition(window.getSize().x / 4, window.getSize().y / 4);
    snake.body.push_back(snake.bodyPart);
}
//Updates game
void Game::tick(RenderWindow& window)
{
    if (snake.body.at(0).getPosition().x == fruit.fruitX && snake.body.at(0).getPosition().y == fruit.fruitY)
    {
        fruit.fruitX = fieldLCorn + rand() % fieldX * fieldY;
        fruit.fruitY = fieldLCorn + rand() % fieldY * fieldX;
        ui.score++;
        snake.body.reserve(1);
        snake.body.push_back(snake.bodyPart);
    }
}
void Game::moveSnake()
{
    switch(dir)
    {
    case 1:
        snake.body.push_back(snake.tail);
        snake.body.at(0).move(0, snake.body.at(0).getPosition().y + 10);
        snake.body.pop_back();
    case 2:
        snake.body.push_back(snake.tail);
        snake.body.at(0).move(0, snake.body.at(0).getPosition().y - 10);
        snake.body.pop_back();
    case 3:
        snake.body.push_back(snake.tail);
        snake.body.at(0).move(snake.body.at(0).getPosition().x + 10, 0);
        snake.body.pop_back();
    case 4:
        snake.body.push_back(snake.tail);
        snake.body.at(0).move(snake.body.at(0).getPosition().x - 10, 0);
        snake.body.pop_back();
    }
}
void Game::countCollision(RenderWindow& window)
{
    //Is snake met border
    if (snake.body.at(0).getPosition().x > 300) restart(window);
    if (snake.body.at(0).getPosition().y > 300) restart(window);
    if (snake.body.at(0).getPosition().x < -300) restart(window);
    if (snake.body.at(0).getPosition().y < -300) restart(window);
    //If snake eats itself
    for (int k = 0; k < snake.body.size() - 1; k++)
    {
        if (snake.body.at(0).getPosition().x == snake.body.at(k).getPosition().y && snake.body.at(0).getPosition().y == snake.body.at(k).getPosition().y)
        {
            restart(window);
        }
    }
}
void Game::render(RenderWindow& window)
{
    for (int i = 0; i < snake.body.size() - 1; i++)
    {
        window.draw(snake.body.at(i));
    }
}
</code>```

答:
So I solved problem by adding a head section in body container and using constructor without parameters, also i deleted checking of vector size where it's not needed (no). Here is my new code:</p>

```<code>Snake::Snake()
{
    body.reserve(4);
    head.setPosition(400, 400);
    head.setSize(Vector2f(20.f, 20.f));
    head.setFillColor(Color(0, 0, 0));
    body.push_back(head);
    for (int i = 0; i < 3; i++)
    {
        bodyPart.setPosition(body.at(i).getPosition().x - 20, body.at(i).getPosition().y - 20);
        bodyPart.setSize(Vector2f(20.f, 20.f));
        bodyPart.setFillColor(Color(0, 0, 0));
        body.push_back(bodyPart);
    }
}
void Game::restart()
{
    for (unsigned int i = 0; i < snake.body.size(); i--)
    {
        snake.body.pop_back();
    }
    snake.head.setPosition(400, 400);
}
void Game::tick()
{
    moveSnake();
    if (snake.body.at(0).getPosition().x == fruit.fruitX && snake.body.at(0).getPosition().y == fruit.fruitY)
    {
        snake.body.reserve(1);
        for (unsigned int i = snake.body.size() - 1;i > 0;i--)
        {
            snake.body.at(i).setPosition(snake.body.at(i - 1).getPosition().x - 20, snake.body.at(i - 1).getPosition().y - 20);
        }
    }
    countCollision();
}
void Game::moveSnake()
{
    switch(dir)
    {
    case 1:
        snake.body.push_back(snake.bodyPart);
        snake.body.at(0).move(0, snake.body.at(0).getPosition().y + 10);
        snake.body.pop_back();
    case 2:
        snake.body.push_back(snake.bodyPart);
        snake.body.at(0).move(0, snake.body.at(0).getPosition().y - 10);
        snake.body.pop_back();
    case 3:
        snake.body.push_back(snake.bodyPart);
        snake.body.at(0).move(snake.body.at(0).getPosition().x + 10, 0);
        snake.body.pop_back();
    case 4:
        snake.body.push_back(snake.bodyPart);
        snake.body.at(0).move(snake.body.at(0).getPosition().x - 10, 0);
        snake.body.pop_back();
    }
}
void Game::countCollision()
{
    if (snake.body.size() >= 5)
    {
        //If snake eats itself
        for (unsigned int k = 1; k < snake.body.size(); k++)
        {
            if (snake.body.at(0).getPosition().x == snake.body.at(k).getPosition().y && snake.body.at(0).getPosition().y == snake.body.at(k).getPosition().y)
            {
                restart();
            }
        }
    }
}
void Game::render(RenderWindow& window)
{
    for (int i = 0; i < snake.body.size(); i++)
    {
        window.draw(snake.body.at(i));
    }
}
</code>```

Title: Vector invalid subscript. SFML

Body:
I'm trying to make a snake game and maybe this error is one of possible. So when I'm debugging and stepping over then I getting link to exception in header file of vector and in exception code wrote that vector has invalid subscript. (Error cause can called by vector bodyPart). The compiler message:

Unhandled exception at 0x00007FFA227EA799 in snake.exe: Microsoft C++ exception: std::out_of_range at memory location 0x00000052FA7CDFD0.

Snake::Snake(RenderWindow& window)
{
    bodyPart.setPosition(window.getSize().x / 4, window.getSize().y / 4);
    bodyPart.setSize(Vector2f(20.f, 20.f));
    bodyPart.setFillColor(Color(0, 0, 0));
    body.push_back(bodyPart);
}
//Sets default parameters
void Game::restart(RenderWindow& window)
{
    for (int i = 0; i < snake.body.size() - 1; i++)
    {
        snake.body.pop_back();
    }
    snake.bodyPart.setPosition(window.getSize().x / 4, window.getSize().y / 4);
    snake.body.push_back(snake.bodyPart);
}
//Updates game
void Game::tick(RenderWindow& window)
{
    if (snake.body.at(0).getPosition().x == fruit.fruitX && snake.body.at(0).getPosition().y == fruit.fruitY)
    {
        fruit.fruitX = fieldLCorn + rand() % fieldX * fieldY;
        fruit.fruitY = fieldLCorn + rand() % fieldY * fieldX;
        ui.score++;
        snake.body.reserve(1);
        snake.body.push_back(snake.bodyPart);
    }
}
void Game::moveSnake()
{
    switch(dir)
    {
    case 1:
        snake.body.push_back(snake.tail);
        snake.body.at(0).move(0, snake.body.at(0).getPosition().y + 10);
        snake.body.pop_back();
    case 2:
        snake.body.push_back(snake.tail);
        snake.body.at(0).move(0, snake.body.at(0).getPosition().y - 10);
        snake.body.pop_back();
    case 3:
        snake.body.push_back(snake.tail);
        snake.body.at(0).move(snake.body.at(0).getPosition().x + 10, 0);
        snake.body.pop_back();
    case 4:
        snake.body.push_back(snake.tail);
        snake.body.at(0).move(snake.body.at(0).getPosition().x - 10, 0);
        snake.body.pop_back();
    }
}
void Game::countCollision(RenderWindow& window)
{
    //Is snake met border
    if (snake.body.at(0).getPosition().x > 300) restart(window);
    if (snake.body.at(0).getPosition().y > 300) restart(window);
    if (snake.body.at(0).getPosition().x < -300) restart(window);
    if (snake.body.at(0).getPosition().y < -300) restart(window);
    //If snake eats itself
    for (int k = 0; k < snake.body.size() - 1; k++)
    {
        if (snake.body.at(0).getPosition().x == snake.body.at(k).getPosition().y && snake.body.at(0).getPosition().y == snake.body.at(k).getPosition().y)
        {
            restart(window);
        }
    }
}
void Game::render(RenderWindow& window)
{
    for (int i = 0; i < snake.body.size() - 1; i++)
    {
        window.draw(snake.body.at(i));
    }
}

Body:
So I solved problem by adding a head section in body container and using constructor without parameters, also i deleted checking of vector size where it's not needed (no). Here is my new code:

Snake::Snake()
{
    body.reserve(4);
    head.setPosition(400, 400);
    head.setSize(Vector2f(20.f, 20.f));
    head.setFillColor(Color(0, 0, 0));
    body.push_back(head);
    for (int i = 0; i < 3; i++)
    {
        bodyPart.setPosition(body.at(i).getPosition().x - 20, body.at(i).getPosition().y - 20);
        bodyPart.setSize(Vector2f(20.f, 20.f));
        bodyPart.setFillColor(Color(0, 0, 0));
        body.push_back(bodyPart);
    }
}
void Game::restart()
{
    for (unsigned int i = 0; i < snake.body.size(); i--)
    {
        snake.body.pop_back();
    }
    snake.head.setPosition(400, 400);
}
void Game::tick()
{
    moveSnake();
    if (snake.body.at(0).getPosition().x == fruit.fruitX && snake.body.at(0).getPosition().y == fruit.fruitY)
    {
        snake.body.reserve(1);
        for (unsigned int i = snake.body.size() - 1;i > 0;i--)
        {
            snake.body.at(i).setPosition(snake.body.at(i - 1).getPosition().x - 20, snake.body.at(i - 1).getPosition().y - 20);
        }
    }
    countCollision();
}
void Game::moveSnake()
{
    switch(dir)
    {
    case 1:
        snake.body.push_back(snake.bodyPart);
        snake.body.at(0).move(0, snake.body.at(0).getPosition().y + 10);
        snake.body.pop_back();
    case 2:
        snake.body.push_back(snake.bodyPart);
        snake.body.at(0).move(0, snake.body.at(0).getPosition().y - 10);
        snake.body.pop_back();
    case 3:
        snake.body.push_back(snake.bodyPart);
        snake.body.at(0).move(snake.body.at(0).getPosition().x + 10, 0);
        snake.body.pop_back();
    case 4:
        snake.body.push_back(snake.bodyPart);
        snake.body.at(0).move(snake.body.at(0).getPosition().x - 10, 0);
        snake.body.pop_back();
    }
}
void Game::countCollision()
{
    if (snake.body.size() >= 5)
    {
        //If snake eats itself
        for (unsigned int k = 1; k < snake.body.size(); k++)
        {
            if (snake.body.at(0).getPosition().x == snake.body.at(k).getPosition().y && snake.body.at(0).getPosition().y == snake.body.at(k).getPosition().y)
            {
                restart();
            }
        }
    }
}
void Game::render(RenderWindow& window)
{
    for (int i = 0; i < snake.body.size(); i++)
    {
        window.draw(snake.body.at(i));
    }
}


问:
Why do I get Call to function "file" failed: no file exists?
I've created a straighforward module:

```<code>.
├── inputs.tf
└── main.tf
</code>```

Input variables are declared in inputs.tf:

```<code>variable "workers" {
    type = number
    description = "Amount of spark workers"
}
variable "values_values_path" {}
</code>```

main.tf is:

```<code>resource "helm_release" "spark" {
    name       = "spark"
    repository = "https://charts.bitnami.com/bitnami"
    chart      = "spark"
    version    = "1.2.21"
    namespace  = ...

    set {
        name  = "worker.replicaCount"
        value = var.workers
    }

    values = [
        "${file("${var.custom_values_path}")}"
    ]
}
</code>```

As you can see I'm trying to deploy a helm release. I'd like to set a custom values file parameterized as custom_values_path:

```<code>.
├── main.tf
├── provider.tf
└── spark-values.yaml
</code>```

My main.tf here is:

```<code>module "spark" {
    source = "../modules/spark"

    workers = 1
    custom_values_path = "./spark_values.yaml"
}
</code>```

However, I'm getting:

```<code>Error: Error in function call

  on ../modules/spark/main.tf line 14, in resource "helm_release" "spark":
  14:         "${file("${var.custom_values_path}")}"
    |----------------
    | var.custom_values_path is "./spark_values.yaml"

Call to function "file" failed: no file exists at spark_values.yaml.
</code>```

Complete directory structure is:

```<code>.
├── stash
│   ├── main.tf
│   ├── provider.tf
│   └── spark-values.yaml
└── modules
    └── spark
        ├── inputs.tf
        └── main.tf
</code>```

When I perform terraform plan I'm in ./stash.

So complete commands would be:

$ > cd ./stash
   $ stash > terraform plan
    Error: Error in function call

```<code>  on ../modules/spark/main.tf line 14, in resource "helm_release" "spark":
  14:         "${file("${var.custom_values_path}")}"
    |----------------
    | var.custom_values_path is "./spark_values.yaml"

Call to function "file" failed: no file exists at spark_values.yaml.
</code>```

Why do I get Call to function "file" failed: no file exists?

答:
Since you are referring to a file in the calling module from a child module, you should provide an absolute path based on the calling module's path using path.module as follows:

```<code>module "spark" {
    source = "../modules/spark"

    workers = 1
    custom_values_path = "${path.module}/spark_values.yaml"
}
</code>```

I recommend against referring to files across module boundaries in Terraform. You are better off keeping dependencies between modules to variables only to avoid weird issues like this. An alternative is to provide the entire file as a variable (this is what the file function does anyway).

```<code>module "spark" {
    source = "../modules/spark"

    workers = 1
    custom_values = file("${path.module}/spark_values.yaml")
}
</code>```

And then modify your Spark module to expect custom_values with the content rather than the path of the file:

```<code>resource "helm_release" "spark" {
    name       = "spark"
    repository = "https://charts.bitnami.com/bitnami"
    chart      = "spark"
    version    = "1.2.21"
    namespace  = ...

    set {
        name  = "worker.replicaCount"
        value = var.workers
    }

    values = [
        var.custom_values
    ]
}
</code>```

Looking at that, I suspect the values parameters expects list(string) so you might need to use yamldecode on custom_values.

Body:
I've created a straighforward module:

.
├── inputs.tf
└── main.tf

Input variables are declared in inputs.tf:

variable "workers" {
    type = number
    description = "Amount of spark workers"
}
variable "values_values_path" {}

main.tf is:

resource "helm_release" "spark" {
    name       = "spark"
    repository = "https://charts.bitnami.com/bitnami"
    chart      = "spark"
    version    = "1.2.21"
    namespace  = ...

    set {
        name  = "worker.replicaCount"
        value = var.workers
    }

    values = [
        "${file("${var.custom_values_path}")}"
    ]
}

As you can see I'm trying to deploy a helm release. I'd like to set a custom values file parameterized as custom_values_path:

.
├── main.tf
├── provider.tf
└── spark-values.yaml

My main.tf here is:

module "spark" {
    source = "../modules/spark"

    workers = 1
    custom_values_path = "./spark_values.yaml"
}

However, I'm getting:

Error: Error in function call

  on ../modules/spark/main.tf line 14, in resource "helm_release" "spark":
  14:         "${file("${var.custom_values_path}")}"
    |----------------
    | var.custom_values_path is "./spark_values.yaml"

Call to function "file" failed: no file exists at spark_values.yaml.

Complete directory structure is:

.
├── stash
│   ├── main.tf
│   ├── provider.tf
│   └── spark-values.yaml
└── modules
    └── spark
        ├── inputs.tf
        └── main.tf

When I perform terraform plan I'm in ./stash.

So complete commands would be:

$ > cd ./stash
   $ stash > terraform plan
    Error: Error in function call

  on ../modules/spark/main.tf line 14, in resource "helm_release" "spark":
  14:         "${file("${var.custom_values_path}")}"
    |----------------
    | var.custom_values_path is "./spark_values.yaml"

Call to function "file" failed: no file exists at spark_values.yaml.

Why do I get Call to function "file" failed: no file exists?

Body:
Since you are referring to a file in the calling module from a child module, you should provide an absolute path based on the calling module's path using path.module as follows:

module "spark" {
    source = "../modules/spark"

    workers = 1
    custom_values_path = "${path.module}/spark_values.yaml"
}

I recommend against referring to files across module boundaries in Terraform. You are better off keeping dependencies between modules to variables only to avoid weird issues like this. An alternative is to provide the entire file as a variable (this is what the file function does anyway).

module "spark" {
    source = "../modules/spark"

    workers = 1
    custom_values = file("${path.module}/spark_values.yaml")
}

And then modify your Spark module to expect custom_values with the content rather than the path of the file:

resource "helm_release" "spark" {
    name       = "spark"
    repository = "https://charts.bitnami.com/bitnami"
    chart      = "spark"
    version    = "1.2.21"
    namespace  = ...

    set {
        name  = "worker.replicaCount"
        value = var.workers
    }

    values = [
        var.custom_values
    ]
}

Looking at that, I suspect the values parameters expects list(string) so you might need to use yamldecode on custom_values.


问:
How to add vue-cli to the existing project?
I have a project on Vue.js using Webpack. And I want to add vue-cli features to it so I can work with it like I do with vue-cli generate project. But I don't know how to integrate vue-cli with existing project.

With new project I can do vue create <project-name but I couldn't find the instruction on integrating it with existing projects. Is there an official way to do so? (I suppose I can just create the new project and move all of the sources there, but still probably there's a better way to do it)

答: Inside the Project Folder in the terminal enter vue create .


问:
How to change condition from a while loop
I am trying to create a reading list, using 2 functions - one to add books and another to display books. The add books function need to execute till such time user confirms that the update is completed. Following is the code :

```<code>book_list = []

def add_books(books):
    book_record = {}
    completed = "no"
    while completed == "no":
        title = input("Enter title : ")
        author = input("Enter author : ")
        year = input("Enter year of publication : ")
        book_record.update({"title": title, "author": author, "year_publ": year})
        books.append(book_record)
        print(books)
        completed = input("update completed ? yes/no")
    return books

def display_books(books):
    for book in books:
        title = book["title"]
        author = book["author"]
        year = book["year_publ"]
        print(f"{title}, {author}, {year}")

option = input("Enter 'a' to add and 'd' to display the books or 'q' to quit :")

while option != "q" :
    if option == "a":
        book_list = add_books(book_list)
    elif option == "d":
        display_books(book_list)
    else:
        print("Invalid Option")
        option = input("Enter 'a' to add and 'd' to display the books or 'q' to quit :")
</code>```

When I execute this code, the While loop ignores the completed condition and keeps asking for adding more books even though the user confirms updated completed.

What is wrong ? I understand that I am trying to update completed inside the loop, and that may be the reason. What are the options ?

Appreciate any help.

Thanks and Regards

Sachin

答:
Your code keeps asking because option still is "a" after add_books has finished, and your "main" loop does not get a new value for option from the user.

Always make the "Do you want to continue?" question part of the loop.

I would recommend to use endless loops (while True:) with a conditional break for these kinds of tasks. It's easier to follow (in my opinion):

Like this - I've added a helper function input_letter that returns the trimmed, lower-case first letter of the user's response, for easier management later):

```<code>book_list = []

def input_letter(prompt):
    return input(prompt).strip().lower()[0::1]

def add_books(books):
    while True:
        title = input("Enter title: ")
        author = input("Enter author: ")
        year = input("Enter year of publication: ")
        books.append({"title": title, "author": author, "year_publ": year})
        if input_letter("More? (y)es / (n)o ") == "y":
            break

    return books

def display_books(books):
    for book in books:
        title = book["title"]
        author = book["author"]
        year = book["year_publ"]
        print(f"{title}, {author}, {year}")

while True:
    option = input_letter("(a)dd book, (d)isplay books, (q)uit: ")
    if option == "a":
        add_books(book_list)
    elif option == "d":
        display_books(book_list)
    elif option == "q":
        break
</code>```

Body:
I am trying to create a reading list, using 2 functions - one to add books and another to display books. The add books function need to execute till such time user confirms that the update is completed. Following is the code :

book_list = []

def add_books(books):
    book_record = {}
    completed = "no"
    while completed == "no":
        title = input("Enter title : ")
        author = input("Enter author : ")
        year = input("Enter year of publication : ")
        book_record.update({"title": title, "author": author, "year_publ": year})
        books.append(book_record)
        print(books)
        completed = input("update completed ? yes/no")
    return books

def display_books(books):
    for book in books:
        title = book["title"]
        author = book["author"]
        year = book["year_publ"]
        print(f"{title}, {author}, {year}")

option = input("Enter 'a' to add and 'd' to display the books or 'q' to quit :")

while option != "q" :
    if option == "a":
        book_list = add_books(book_list)
    elif option == "d":
        display_books(book_list)
    else:
        print("Invalid Option")
        option = input("Enter 'a' to add and 'd' to display the books or 'q' to quit :")

When I execute this code, the While loop ignores the completed condition and keeps asking for adding more books even though the user confirms updated completed.

What is wrong ? I understand that I am trying to update completed inside the loop, and that may be the reason. What are the options ?

Appreciate any help.

Thanks and Regards

Sachin

Body:
Your code keeps asking because option still is "a" after add_books has finished, and your "main" loop does not get a new value for option from the user.

Always make the "Do you want to continue?" question part of the loop.

I would recommend to use endless loops (while True:) with a conditional break for these kinds of tasks. It's easier to follow (in my opinion):

Like this - I've added a helper function input_letter that returns the trimmed, lower-case first letter of the user's response, for easier management later):

book_list = []

def input_letter(prompt):
    return input(prompt).strip().lower()[0::1]

def add_books(books):
    while True:
        title = input("Enter title: ")
        author = input("Enter author: ")
        year = input("Enter year of publication: ")
        books.append({"title": title, "author": author, "year_publ": year})
        if input_letter("More? (y)es / (n)o ") == "y":
            break

    return books

def display_books(books):
    for book in books:
        title = book["title"]
        author = book["author"]
        year = book["year_publ"]
        print(f"{title}, {author}, {year}")

while True:
    option = input_letter("(a)dd book, (d)isplay books, (q)uit: ")
    if option == "a":
        add_books(book_list)
    elif option == "d":
        display_books(book_list)
    elif option == "q":
        break


问:
How to stop the execution of test cases fails in Java selenium
I have a scenario where I need to stop the execution once it reaches one of the condition in else part.
Below is my code.Once the condition reaches else,i want to stop the execution.How do I use assert condition for this?</p>

```<code>So once I reach last condition ,that is if any employee reaches Exception,I want to stop the execution

If a condition reaches,HR department,variable counter will be incremented by 1 and if it reaches Finance department ,variable i will be decremented by 1

for (int i=0;i<EmployeeID.size();i++) {
//while(i++<=EmployeeID.size()) {
    if(counter==EmployeeID.size())break;
    stmt = con.prepareStatement("select * from Employee where EmployeeID=?");
    stmt.setInt(1,EmployeeID.get(i));
    //System.out.println(EmployeeID.get(i));
    rs3= stmt.executeQuery();
//  while(counter!=EmployeeID.size()) {
        while(rs3.next()) {
        getCurrentQueueID= rs3.getString("CurrentQueueID");
        if(getCurrentQueueID.equals("1")) {
        log.info(+EmployeeID.get(i) + " is in HR Department");
        counter++;
        //System.out.println("Count is"+counter);
        }

        else if(getCurrentQueueID.equals("7")) {
        log.info(+EmployeeID.get(i) + " is in Finance Department");
        --i;
        System.out.println("Value of i is" +i);
        Thread.sleep(10000);

        }

        else if(getCurrentQueueID.equals("3")) {
            log.info(+EmployeeID.get(i) + " is in Exception");
        }
}   //End of While rs loop
</code>```

答:
If you want to stop test so that it is not considered failed then just use return; statement.

If you need to stop test as failed then you either:

Throw an exception if you do not use any test framework

OR use assert false; statement if you do not use any test framework

OR use org.junit.Assert.fail(); if you use JUnit

OR use org.testng.Assert.fail() if you use TestNG

Body:
I have a scenario where I need to stop the execution once it reaches one of the condition in else part.
Below is my code.Once the condition reaches else,i want to stop the execution.How do I use assert condition for this?

So once I reach last condition ,that is if any employee reaches Exception,I want to stop the execution

If a condition reaches,HR department,variable counter will be incremented by 1 and if it reaches Finance department ,variable i will be decremented by 1

for (int i=0;i<EmployeeID.size();i++) {
//while(i++<=EmployeeID.size()) {
    if(counter==EmployeeID.size())break;
    stmt = con.prepareStatement("select * from Employee where EmployeeID=?");
    stmt.setInt(1,EmployeeID.get(i));
    //System.out.println(EmployeeID.get(i));
    rs3= stmt.executeQuery();
//  while(counter!=EmployeeID.size()) {
        while(rs3.next()) {
        getCurrentQueueID= rs3.getString("CurrentQueueID");
        if(getCurrentQueueID.equals("1")) {
        log.info(+EmployeeID.get(i) + " is in HR Department");
        counter++;
        //System.out.println("Count is"+counter);
        }

        else if(getCurrentQueueID.equals("7")) {
        log.info(+EmployeeID.get(i) + " is in Finance Department");
        --i;
        System.out.println("Value of i is" +i);
        Thread.sleep(10000);

        }

        else if(getCurrentQueueID.equals("3")) {
            log.info(+EmployeeID.get(i) + " is in Exception");
        }
}   //End of While rs loop


问:
Gatsby not building but working fine in develop
I'm creating a site using Gatysby and prismic. Everything seems to work fine in development. But when I try to build I get an "undefined" error.

Building static HTML failed for path "/preview/page"
```

<pre class="lang-sh prettyprint-override"><code>  48 | const Page = (props) => {
  49 |  console.log(props);
> 50 |  const pageTitle = props.data.prismic.allPages.edges[0].node.page_title;
     |                                                         ^
  51 |  const content = props.data.prismic.allPages.edges[0].node.page_content;
  52 |  return (
  53 |          <>

  WebpackError: TypeError: Cannot read property 'node' of undefined
</code>```

I'm not sure where the /preview/ is coming from because that is not the paths I have specified in the config file, and apparently previews are supposed to be disabled by default if I understand the documentation correctly - documentation.

I tried setting them to false anyway but no luck.

This is my config atm

        {
            resolve : 'gatsby-source-prismic-graphql',
            options : {
                repositoryName : 'XXXXX',
                pages          : [
                    {
                        type      : 'Page',
                        match     : '/:uid',
                        path      : '/',
                        component : require.resolve('./src/templates/page.js')
                    },
                    {
                        type      : 'Blog_post',
                        match     : '/blog/:uid',
                        path      : '/blog/',
                        component : require.resolve('./src/templates/blogPost.js')
                    }
                ]
            }
        },
```

Any help would be appreciated thanks.

答:
I think the problem here is that you need to add a validation check on your content. The documentation page you were looking at needs to be updated. I'll look into that.

By adding a validation check for content, the preview route can be generated without error. This page explains how to setup the validation check:
https://prismic.io/docs/gatsby/rendering/retrieve-the-document-object#21_0-adding-a-validation-check

Body:
I'm creating a site using Gatysby and prismic. Everything seems to work fine in development. But when I try to build I get an "undefined" error.

Building static HTML failed for path "/preview/page"

  48 | const Page = (props) => {
  49 |  console.log(props);
> 50 |  const pageTitle = props.data.prismic.allPages.edges[0].node.page_title;
     |                                                         ^
  51 |  const content = props.data.prismic.allPages.edges[0].node.page_content;
  52 |  return (
  53 |          <>

  WebpackError: TypeError: Cannot read property 'node' of undefined

I'm not sure where the /preview/ is coming from because that is not the paths I have specified in the config file, and apparently previews are supposed to be disabled by default if I understand the documentation correctly - documentation.

I tried setting them to false anyway but no luck.

This is my config atm

        {
            resolve : 'gatsby-source-prismic-graphql',
            options : {
                repositoryName : 'XXXXX',
                pages          : [
                    {
                        type      : 'Page',
                        match     : '/:uid',
                        path      : '/',
                        component : require.resolve('./src/templates/page.js')
                    },
                    {
                        type      : 'Blog_post',
                        match     : '/blog/:uid',
                        path      : '/blog/',
                        component : require.resolve('./src/templates/blogPost.js')
                    }
                ]
            }
        },

Any help would be appreciated thanks.


问:
How to insert a specific text at the end of exisitng data in a specific column?
I am using SQL Server 2014. Assume I have a table called T1 with 2 columns, IdNumber and Notes. Table T1 contains around 300,000 records.

The Notes column is a free text column, meaning users have entered therein free text. Some records have this column empty (no text entered).

I now have a list of IdNumbers where I need to add this specific text "(TOC)" in the Notes column of T1, ideally at the end of any text already present therein. I have created a table called tempID which contains the list of all these IdNumbers.

Here is how table T1 looks (extract):

```<code>IdNumber        Notes
--------------------------------------------------------------------
   101          Guest does not like beer
   154          wedding anniversary - to prepare a cake - 03052020
   160
</code>```

IdNumber = 160 has a blank/empty Notes column.

Here is what I want to achieve (assuming "(TOC)" need to be added to these 3 IdNumbers):

```<code>IdNumber        Notes
------------------------------------------------------------------------
  101           Guest does not like beer (TOC)
  154           wedding anniversary - to prepare a cake - 03052020 (TOC)
  160           (TOC)
</code>```

How can I do this (I have a list of around 1500 IdNumbers)?

This is where I am stuck with my SQL query:

```<code>UPDATE T1
INSERT INTO [Notes]
VALUE ('(TOC)') ----stuck here!
WHERE [IdNumber] in (Select [IdNumber] from [tempID]
</code>```

I think it should be done differently since my above query will simply overwrite the existing content of the Notes column with "(TOC)".

答:
Actually, concat() does exactly what you want -- ignoring NULL values:

```<code>UPDATE dbo.T1
    SET Notes = CONCAT(Notes, ' (TOC)')
    WHERE IdNumber IN (SELECT t.IdNumber FROM dbo.tempID t);
</code>```

The only caveat is that you seem to want ltrim() to remove the leading space when notes is NULL:

```<code>UPDATE dbo.T1
    SET Notes = LTRIM(CONCAT(Notes, ' (TOC)'))
    WHERE IdNumber IN (SELECT t.IdNumber FROM dbo.tempID t);
</code>```

This will remove the leading space for NULL values -- and any leading NULLs in notes.

You can do this with COALESCE() and + as well:

```<code>UPDATE dbo.T1
    SET Notes = COALESCE(Notes + ' ', '') + '(TOC)'
    WHERE IdNumber IN (SELECT t.IdNumber FROM dbo.tempID t);
</code>```

Body:
I am using SQL Server 2014. Assume I have a table called T1 with 2 columns, IdNumber and Notes. Table T1 contains around 300,000 records.

The Notes column is a free text column, meaning users have entered therein free text. Some records have this column empty (no text entered).

I now have a list of IdNumbers where I need to add this specific text "(TOC)" in the Notes column of T1, ideally at the end of any text already present therein. I have created a table called tempID which contains the list of all these IdNumbers.

Here is how table T1 looks (extract):

IdNumber        Notes
--------------------------------------------------------------------
   101          Guest does not like beer
   154          wedding anniversary - to prepare a cake - 03052020
   160

IdNumber = 160 has a blank/empty Notes column.

Here is what I want to achieve (assuming "(TOC)" need to be added to these 3 IdNumbers):

IdNumber        Notes
------------------------------------------------------------------------
  101           Guest does not like beer (TOC)
  154           wedding anniversary - to prepare a cake - 03052020 (TOC)
  160           (TOC)

How can I do this (I have a list of around 1500 IdNumbers)?

This is where I am stuck with my SQL query:

UPDATE T1
INSERT INTO [Notes]
VALUE ('(TOC)') ----stuck here!
WHERE [IdNumber] in (Select [IdNumber] from [tempID]

I think it should be done differently since my above query will simply overwrite the existing content of the Notes column with "(TOC)".

Body:
Actually, concat() does exactly what you want -- ignoring NULL values:

UPDATE dbo.T1
    SET Notes = CONCAT(Notes, ' (TOC)')
    WHERE IdNumber IN (SELECT t.IdNumber FROM dbo.tempID t);

The only caveat is that you seem to want ltrim() to remove the leading space when notes is NULL:

UPDATE dbo.T1
    SET Notes = LTRIM(CONCAT(Notes, ' (TOC)'))
    WHERE IdNumber IN (SELECT t.IdNumber FROM dbo.tempID t);

This will remove the leading space for NULL values -- and any leading NULLs in notes.

You can do this with COALESCE() and + as well:

UPDATE dbo.T1
    SET Notes = COALESCE(Notes + ' ', '') + '(TOC)'
    WHERE IdNumber IN (SELECT t.IdNumber FROM dbo.tempID t);


问:
Force screen redraw after drawing to screen's DC C++
I'm creating a Windows Mobile custom SIP and as the user presses or "hovers" over a button on the keyboard I draw it's corresponding selected image (iPhone-esque) to the screen's DC using ::GetDC(NULL).  It is developed in Win32 C++.

My problem is that I can never get the screen to repaint itself, erasing the previously drawn key.  I've tried everything I could think of to force it, ::RedrawWindow() with all different combos of params using NULL or any of the Get..Window functions as the HWND, and all combo of flags (INVALIDATE | UPDATENOW | ERASENOW | ALLCHILDREN etc).  I've also tried invalidating the rect and forcing a repaint of the underlying app using ::GetActiveWindow and ::GetForegroundWindow, variations using ::GetDesktopWindow, etc.  I've essentially run out of ideas and it's the last thing holding me up from using it on my Windows Mobile device.  Does anyone have any ideas? Any help would be greatly appreciated.

I've included some screenshots to illustrate my dilemma.

Before Screenshot

After Screenshot

Before http://img13.imageshack.us/img13/9861/cezoom1.png After http://img3.imageshack.us/img3/7481/cezoom2.png

Thanks in advance!

答: Have you tried InvalidateRect on the screen hWnd?</p>

OwnerDisplayName: MrPerphekt

LastEditorDisplayName: MrPerphekt

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Chris Hynes


问:
function inside a function in android
what is this technique in java and android?
please give basics about this technique

```<code>    objlistview.setOnItemClickListener(new OnItemClickListener()
    {
        public void onItemClick(AdapterView<?> parent, View v, int position,long id)
        {
            Cursor cr=(Cursor)parent.getItemAtPosition(position);
            int _id=cr.getInt(cr.getColumnIndex("_id"));
            callview(_id);
        }

    });
</code>```

thank you...

答:
This techinque is known as anonymous inner classes

Thanks
Deepak

Title: function inside a function in android

Body:
what is this technique in java and android?
please give basics about this technique

    objlistview.setOnItemClickListener(new OnItemClickListener()
    {
        public void onItemClick(AdapterView<?> parent, View v, int position,long id)
        {
            Cursor cr=(Cursor)parent.getItemAtPosition(position);
            int _id=cr.getInt(cr.getColumnIndex("_id"));
            callview(_id);
        }

    });

thank you...


问:
Batch delete items for a dynamodb table with hash and range key
I am trying to perform a batch write item for a dynamodb table using boto3 python library. The table has both hash and range key. When I performed the same with another table with only hash key it worked well. I am wondering how to add both hash and range key when performing batch write item operation.</p>

```<code>import boto3
from boto3.dynamodb.conditions import Attr,Key

dynamodb = boto3.resource('dynamodb', 'us-east-2')
table = dynamodb.Table('edc_test')

scan = table.scan(
    #ProjectionExpression='#k',
    ProjectionExpression='resource_id',
    #ProjectionExpression='version_id',
    FilterExpression=Attr('Health.New version - Veracity unavailable').eq("A new dataset is available but IDQ rules are not generated yet")
)
items=scan['Items']
print('length',str(len(items)))
print(items)

def lambda_handler(event, context):
    with table.batch_writer() as batch:
        for each in scan['Items']:
            batch.delete_item(Key=each)
</code>```

答:
```<code>    ProjectionExpression='version_id,resource_id',
    FilterExpression=Attr('Health.New version - Veracity unavailable').eq("A new dataset is available but IDQ rules are not generated yet")
#ExpressionAttributeNames={
#    '#k': 'name'
#}
    )
items=scan['Items']
print('length',str(len(items)))
print(items)

#response = table.table.delete_item(Key={resource_id:1})

with table.batch_writer() as batch:
    #for each in scan['Items']:
     #   batch.delete_item(Key=each)
    for each in scan['Items']:
            #batch.delete_item(Key={'version_id': each['version_id']})
            batch.delete_item(Key={'resource_id': each['resource_id'], 'version_id': each['version_id']})
</code>```

Included sort key in scan projection expression and included the same in delete batch item , it worked.

Body:
I am trying to perform a batch write item for a dynamodb table using boto3 python library. The table has both hash and range key. When I performed the same with another table with only hash key it worked well. I am wondering how to add both hash and range key when performing batch write item operation.

import boto3
from boto3.dynamodb.conditions import Attr,Key

dynamodb = boto3.resource('dynamodb', 'us-east-2')
table = dynamodb.Table('edc_test')

scan = table.scan(
    #ProjectionExpression='#k',
    ProjectionExpression='resource_id',
    #ProjectionExpression='version_id',
    FilterExpression=Attr('Health.New version - Veracity unavailable').eq("A new dataset is available but IDQ rules are not generated yet")
)
items=scan['Items']
print('length',str(len(items)))
print(items)

def lambda_handler(event, context):
    with table.batch_writer() as batch:
        for each in scan['Items']:
            batch.delete_item(Key=each)

Body:
    ProjectionExpression='version_id,resource_id',
    FilterExpression=Attr('Health.New version - Veracity unavailable').eq("A new dataset is available but IDQ rules are not generated yet")
#ExpressionAttributeNames={
#    '#k': 'name'
#}
    )
items=scan['Items']
print('length',str(len(items)))
print(items)

#response = table.table.delete_item(Key={resource_id:1})

with table.batch_writer() as batch:
    #for each in scan['Items']:
     #   batch.delete_item(Key=each)
    for each in scan['Items']:
            #batch.delete_item(Key={'version_id': each['version_id']})
            batch.delete_item(Key={'resource_id': each['resource_id'], 'version_id': each['version_id']})

Included sort key in scan projection expression and included the same in delete batch item , it worked.


问:
Igor Pro 8, functions for comparing strings
Hi I'm pretty new to using Igor Pro. I'm looking for some help on writing a procedure for a task.

I have 4 waves, two are text waves and two are numeric waves(one of which has no data yet). I need to write a function that will compare the two text waves and if they are equal, have igor pull data from one of the numeric waves and put it in the correct point to match the text wave it's coupled with.

To make it visually conceptually

```<code>twave1                           twave2

nwave1                           nwave2
</code>```

twave1 is a list of all isotopes up to neptunium but they're not in order, and nwave1 is their corresponding mass values. (both on table1)

twave2 is the same list of isotopes but ordered properly (i.e. 1H, 2H, 3H, 4H...3He, 4He...ect) and nwave2 is empty (both on table2)

so the goal is to create a function that will sort through twave1 and twave2, and if they match, pull the data from nwave1 into nwave2, so that the masses match with the correct isotopes on table2. So table2 will have the correctly ordered isotopes and now the mass data as well, in the correct places.

Any help would be greatly appreciated; this is where I've gotten so far

```<code>function assignMEf()
    wave ME, ME_FRIB
    wave isotope_FRIB, isotope
    variable len = numpnts(ME)
    variable i, j
    variable ME_current, iso_current

    for(i=0; i<len; i+=1)
     ME_current = ME[i]
     iso_current = isotope[i]
   for(j=0; j<4254; j+=1)
    if(iso_current == isotope_frib[j])
        ME_frib = ME[i]
    endif
   endfor
  endfor

end
</code>```

答: I don't think stringmatch is the right choice here. It uses wildcard matching but the OP AFAIU wants match/no-match so !cmpstr is a better choice.

Body:
Hi I'm pretty new to using Igor Pro. I'm looking for some help on writing a procedure for a task.

I have 4 waves, two are text waves and two are numeric waves(one of which has no data yet). I need to write a function that will compare the two text waves and if they are equal, have igor pull data from one of the numeric waves and put it in the correct point to match the text wave it's coupled with.

To make it visually conceptually

twave1                           twave2

nwave1                           nwave2

twave1 is a list of all isotopes up to neptunium but they're not in order, and nwave1 is their corresponding mass values. (both on table1)

twave2 is the same list of isotopes but ordered properly (i.e. 1H, 2H, 3H, 4H...3He, 4He...ect) and nwave2 is empty (both on table2)

so the goal is to create a function that will sort through twave1 and twave2, and if they match, pull the data from nwave1 into nwave2, so that the masses match with the correct isotopes on table2. So table2 will have the correctly ordered isotopes and now the mass data as well, in the correct places.

Any help would be greatly appreciated; this is where I've gotten so far

function assignMEf()
    wave ME, ME_FRIB
    wave isotope_FRIB, isotope
    variable len = numpnts(ME)
    variable i, j
    variable ME_current, iso_current

    for(i=0; i<len; i+=1)
     ME_current = ME[i]
     iso_current = isotope[i]
   for(j=0; j<4254; j+=1)
    if(iso_current == isotope_frib[j])
        ME_frib = ME[i]
    endif
   endfor
  endfor

end


问:
C# Get answer from HTTP POST Request
I am making mail.ru autoregistration. To do this, I am sending this POST-Request in C#:

```<code>using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;

namespace MailCheck
{
    class Program
    {
        static void Main(string[] args)
        {
            ///creating a client
            HttpClient webclient = new HttpClient();

            ///sending a POST request
            var response = webclient.PostAsync("https://account.mail.ru/api/v1/user/signup", new FormUrlEncodedContent(new Dictionary<string, string>{
                {"extented", "true"},
                { "more_password_strength", "1" },
                { "context", "signup" },
                { "from", "main" },
                { "sent_me_ads", "true" },
                { "name", Convert.ToString(new Dictionary<string, string> { { "first", "John" }, {"last", "Genry"} }) },
                { "birthday", Convert.ToString(new Dictionary<string, int> { { "day", 4 }, {"month", 5}, {"year", 1995} }) },
                { "login", "pointlesst23" },
                { "domain", "mail.ru" },
                { "password", "Tim147890" },
            }));

            ///getting a Result
            var responseString = response.Result;
            Console.WriteLine(responseString);

        }
    }
}
</code>```

The problem is, that i get this answer:

```<code>StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: System.Net.Http.HttpConnectionResponseContent, Headers:
{
  Server: nginx
  Date: Mon, 01 Jun 2020 11:12:11 GMT
  Transfer-Encoding: chunked
  Connection: close
  X-XSS-Protection: 1; mode=block; report=https://cspreport.mail.ru/xxssprotection
  X-Host: fau37.m.smailru.net
  X-Host: fau37.m.smailru.net
  X-Content-Type-Options: nosniff
  X-Content-Type-Options: nosniff
  X-ComScore: pageview_candidate
  Strict-Transport-Security: max-age=31536000; includeSubDomains; preload
  Strict-Transport-Security: max-age=15768000; includeSubDomains; preload
  X-Frame-Options: DENY
  Vary: Referer
  Content-Type: application/json; charset=utf-8
  Expires: Thu, 01 Jan 1970 00:00:01 GMT
}
</code>```

However, I need another site answer(that i've got sending this POST-request but in python). Because in it there is a captcha ID {"body":"mOlWAphGRBZWAIv7"}Full needed answer is:

```<code>{"body":"mOlWAphGRBZWAIv7","email":null,"status":200,"htmlencoded":true}
</code>```

Can someone solve this problem?)

答:
use this code

```<code> var responseString = response.Result.Content.ReadAsStringAsync().Result;
</code>```

as

```<code>var responseString = response.Result;
</code>```

but i suggest use await/async pattern

```<code> var responseString =await response;
 var bodyResponseString =await responseString.Content.ReadAsStringAsync() ;
</code>```

Title: C# Get answer from HTTP POST Request

Body:
I am making mail.ru autoregistration. To do this, I am sending this POST-Request in C#:

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;

namespace MailCheck
{
    class Program
    {
        static void Main(string[] args)
        {
            ///creating a client
            HttpClient webclient = new HttpClient();

            ///sending a POST request
            var response = webclient.PostAsync("https://account.mail.ru/api/v1/user/signup", new FormUrlEncodedContent(new Dictionary<string, string>{
                {"extented", "true"},
                { "more_password_strength", "1" },
                { "context", "signup" },
                { "from", "main" },
                { "sent_me_ads", "true" },
                { "name", Convert.ToString(new Dictionary<string, string> { { "first", "John" }, {"last", "Genry"} }) },
                { "birthday", Convert.ToString(new Dictionary<string, int> { { "day", 4 }, {"month", 5}, {"year", 1995} }) },
                { "login", "pointlesst23" },
                { "domain", "mail.ru" },
                { "password", "Tim147890" },
            }));

            ///getting a Result
            var responseString = response.Result;
            Console.WriteLine(responseString);

        }
    }
}

The problem is, that i get this answer:

StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: System.Net.Http.HttpConnectionResponseContent, Headers:
{
  Server: nginx
  Date: Mon, 01 Jun 2020 11:12:11 GMT
  Transfer-Encoding: chunked
  Connection: close
  X-XSS-Protection: 1; mode=block; report=https://cspreport.mail.ru/xxssprotection
  X-Host: fau37.m.smailru.net
  X-Host: fau37.m.smailru.net
  X-Content-Type-Options: nosniff
  X-Content-Type-Options: nosniff
  X-ComScore: pageview_candidate
  Strict-Transport-Security: max-age=31536000; includeSubDomains; preload
  Strict-Transport-Security: max-age=15768000; includeSubDomains; preload
  X-Frame-Options: DENY
  Vary: Referer
  Content-Type: application/json; charset=utf-8
  Expires: Thu, 01 Jan 1970 00:00:01 GMT
}

However, I need another site answer(that i've got sending this POST-request but in python). Because in it there is a captcha ID {"body":"mOlWAphGRBZWAIv7"}Full needed answer is:

{"body":"mOlWAphGRBZWAIv7","email":null,"status":200,"htmlencoded":true}

Can someone solve this problem?)

Body:
use this code

 var responseString = response.Result.Content.ReadAsStringAsync().Result;

as

var responseString = response.Result;

but i suggest use await/async pattern

 var responseString =await response;
 var bodyResponseString =await responseString.Content.ReadAsStringAsync() ;