问:
How to make a string from separate int values
I'm trying to make a string out of 3 elements with the following format '0/5'.

int start = 0;
int finish = 5;

I've tried doing this:

```<code>    char string[20];

    string[0] = (char) start;
    string[1] = '/';
    string[2] = (char) finish;

    string[strlen(string)] = '\0';

</code>```

But when I printf I get nothing.

```<code>    char buffer[10];
    char aux[5] = {'/', '\0'};
    char aux2[5];
    sprintf(buffer, "%d", start);
    strcat(buffer, aux);
    sprintf(aux2, "%d", finish);
    strcat(buffer, aux2);
</code>```

This is what is working but seems very inefficient.

答:
```<code>char *tosomething(char *buff, int start, int end)
{
    sprintf(buff, "%d/%d", start, end);
    return buff;
}
</code>```

Body:
I'm trying to make a string out of 3 elements with the following format '0/5'.

int start = 0;
int finish = 5;

I've tried doing this:

    char string[20];

    string[0] = (char) start;
    string[1] = '/';
    string[2] = (char) finish;

    string[strlen(string)] = '\0';

But when I printf I get nothing.

    char buffer[10];
    char aux[5] = {'/', '\0'};
    char aux2[5];
    sprintf(buffer, "%d", start);
    strcat(buffer, aux);
    sprintf(aux2, "%d", finish);
    strcat(buffer, aux2);

This is what is working but seems very inefficient.


来源: stackexchange

问:
How to parse string fragment between two others using "sed" or other linux terminal utilities?
I need to parse the passphrase using ssid like trigger from android file (data/misc/wifi/wpa_supplicant.conf)(need root)  using android terminal utilities, which will calling in java function. fragment of file  looks like the next:

```<code>network={
    ssid="12345678"
    psk="87654321"
    key_mgmt=WPA-PSK
</code>```

I need to parse psk phrase. I am trying to use this:

```<code>sed -n '/ssid=""+ssid+""psk"/,/"key_mgmt/p'
</code>```

but it can't work, please help.

答:
Using the first example file from https://www.systutorials.com/docs/linux/man/5-wpa_supplicant.conf/:

```<code>$ cat file
# allow frontend (e.g., wpa_cli) to be used by all users in 'wheel' group
ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=wheel
#
# home network; allow all valid ciphers
network={
        ssid="home"
        scan_ssid=1
        key_mgmt=WPA-PSK
        psk="very secret passphrase"
}
#
# work network; use EAP-TLS with WPA; allow only CCMP and TKIP ciphers
network={
        ssid="work"
        scan_ssid=1
        key_mgmt=WPA-EAP
        pairwise=CCMP TKIP
        group=CCMP TKIP
        eap=TLS
        identity="user [at] example.com"
        ca_cert="/etc/cert/ca.pem"
        client_cert="/etc/cert/user.pem"
        private_key="/etc/cert/user.prv"
        private_key_passwd="password"
}
</code>```

Here's how to find a tag with a given value and print the value of some other tag using a standard UNIX tool:

```<code>$ cat tst.awk
{ gsub(/^[[:space:]]+|[[:space:]]+$/,"") }
/^network[[:space:]]*=/ {
    inNw = 1
    next
}
inNw {
    if ( /^[[:alnum:]_]+[[:space:]]*=/ ) {
        tag = val = $0
        sub(/[[:space:]]*=.*/,"",tag)
        sub(/[^=]+=[[:space:]]*/,"",val)
        f[tag] = val
    }
    else if ( /^}/ ) {
        if ( ( f[fndTag] == fndVal ) ||
             ( f[fndTag] == "\"" fndVal "\"" ) ) {
            print f[prtTag]
        }
        delete f
        inNw = 0
    }
}
</code>```

.

```<code>$ awk -v fndTag='ssid' -v fndVal='home' -v prtTag='psk' -f tst.awk file
"very secret passphrase"

$ awk -v fndTag='ssid' -v fndVal='work' -v prtTag='key_mgmt' -f tst.awk file
WPA-EAP

$ awk -v fndTag='key_mgmt' -v fndVal='WPA-EAP' -v prtTag='identity' -f tst.awk file
"user [at] example.com"
</code>```

The above will work using any awk in any shell on any UNIX box.

ContentLicense: CC BY-SA 4.0

Body:
I need to parse the passphrase using ssid like trigger from android file (data/misc/wifi/wpa_supplicant.conf)(need root)  using android terminal utilities, which will calling in java function. fragment of file  looks like the next:

network={
    ssid="12345678"
    psk="87654321"
    key_mgmt=WPA-PSK

I need to parse psk phrase. I am trying to use this:

sed -n '/ssid=""+ssid+""psk"/,/"key_mgmt/p'

but it can't work, please help.

Body:
Using the first example file from https://www.systutorials.com/docs/linux/man/5-wpa_supplicant.conf/:

$ cat file
# allow frontend (e.g., wpa_cli) to be used by all users in 'wheel' group
ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=wheel
#
# home network; allow all valid ciphers
network={
        ssid="home"
        scan_ssid=1
        key_mgmt=WPA-PSK
        psk="very secret passphrase"
}
#
# work network; use EAP-TLS with WPA; allow only CCMP and TKIP ciphers
network={
        ssid="work"
        scan_ssid=1
        key_mgmt=WPA-EAP
        pairwise=CCMP TKIP
        group=CCMP TKIP
        eap=TLS
        identity="user [at] example.com"
        ca_cert="/etc/cert/ca.pem"
        client_cert="/etc/cert/user.pem"
        private_key="/etc/cert/user.prv"
        private_key_passwd="password"
}

Here's how to find a tag with a given value and print the value of some other tag using a standard UNIX tool:

$ cat tst.awk
{ gsub(/^[[:space:]]+|[[:space:]]+$/,"") }
/^network[[:space:]]*=/ {
    inNw = 1
    next
}
inNw {
    if ( /^[[:alnum:]_]+[[:space:]]*=/ ) {
        tag = val = $0
        sub(/[[:space:]]*=.*/,"",tag)
        sub(/[^=]+=[[:space:]]*/,"",val)
        f[tag] = val
    }
    else if ( /^}/ ) {
        if ( ( f[fndTag] == fndVal ) ||
             ( f[fndTag] == "\"" fndVal "\"" ) ) {
            print f[prtTag]
        }
        delete f
        inNw = 0
    }
}

.

$ awk -v fndTag='ssid' -v fndVal='home' -v prtTag='psk' -f tst.awk file
"very secret passphrase"

$ awk -v fndTag='ssid' -v fndVal='work' -v prtTag='key_mgmt' -f tst.awk file
WPA-EAP

$ awk -v fndTag='key_mgmt' -v fndVal='WPA-EAP' -v prtTag='identity' -f tst.awk file
"user [at] example.com"

The above will work using any awk in any shell on any UNIX box.


问:
Override index array from API result
Having a problem overriding the index of array in redux state :/

I am receiving a data from an endpoint and the results are:

e.g.

```<code>data:
 [{
    0: {id: 123, name: test1 },
    1: {id: 456, name: test2 },
    3: {id: 789, name: test3 },
 }]
</code>```

But I want to change the index of the array based on the result object.

```<code>data:
 [{
    123: {id: 123, name: test1 },
    456: {id: 456, name: test2 },
    789: {id: 789, name: test3 },
 }]
</code>```

Then save these to reducer.

This is the exact data that returned from an endpoint.

I have tried

```<code>let data = action.payload.data.map(item => {
    return {
        [item.id]: item
    }
})
</code>```

and got the result of

```<code>[
0: {123: {id: 123, name: 'test1'}},
1: {456: {id: 456, name: 'test2'}}
]
</code>```

Any help is much appreciated!

答:
A combination of Array.map(), Object.values() and Array.reduce() must do the trick:

const data = [{

0: {id: 123, name: "test1" },

1: {id: 456, name: "test2" },

3: {id: 789, name: "test3" },

}];

const output = data.map(obj => Object.values(obj).reduce((acc, a) => ({ ...acc, [a.id]: a }), {}));

console.log(output);```

Title: Override index array from API result

Body:
Having a problem overriding the index of array in redux state :/

I am receiving a data from an endpoint and the results are:

e.g.

data:
 [{
    0: {id: 123, name: test1 },
    1: {id: 456, name: test2 },
    3: {id: 789, name: test3 },
 }]

But I want to change the index of the array based on the result object.

data:
 [{
    123: {id: 123, name: test1 },
    456: {id: 456, name: test2 },
    789: {id: 789, name: test3 },
 }]

Then save these to reducer.

This is the exact data that returned from an endpoint.

I have tried

let data = action.payload.data.map(item => {
    return {
        [item.id]: item
    }
})

and got the result of

[
0: {123: {id: 123, name: 'test1'}},
1: {456: {id: 456, name: 'test2'}}
]

Any help is much appreciated!


问:
sample UART code to read from UART2 on ELB-REV4
I need sample c code to read from UART2 with baudrate of 3Mbps on ELB-REV4 device.

i tried some example code but did not work

I expect the Data baud or UART2 to be 3Mbps which i can see using oscilloscope.

issue is as soon as i set UART2 baudrate to 3000000. And on oscilloscope i see the baudrate still is 115200.

答:
On ELB-REV4 /dev/ttyS2 represents UART2 and use /dev/ttyS0 for UART0 use the below code which outputs 101010 you can see on oscilloscope and measure the baudrate.</p>

```<code> #include <stdio.h>
 #include <string.h>
 #include <stdlib.h>
 #include <unistd.h>
 #include <fcntl.h>
 #include <termios.h>
 #include <ctype.h>
 #include <errno.h>

 struct termios options;
 int fd;
 int status;
 char buf[10];
 unsigned char rx_buffer[10];
 int main(void)
        {
           fd = open("/dev/ttyS2", O_RDWR | O_NOCTTY | O_NDELAY);

      if (fd < 0)
        {
           printf("Error opening serial port\n");
           exit(1);
        }

      bzero( & options, sizeof(options));
        options.c_cflag = B3000000 | CS8 | CLOCAL | CREAD | IGNPAR | PARODD | PARENB; //8bit, Odd parity,
        tcflush(fd, TCIFLUSH);
        tcsetattr(fd, TCSANOW, & options);

    while (1)
    {
buf[0] = 0x55; //pattern
status = write(fd, & buf[0], 1);

    if (status < 0)
    {

     printf("Write error - %s \n", strerror(errno));
        exit(1);
    }

     usleep(1000000);
        printf("Sending 0x55 to /dev/ttyS2 port\n");
    }

    }
</code>```

Body:
On ELB-REV4 /dev/ttyS2 represents UART2 and use /dev/ttyS0 for UART0 use the below code which outputs 101010 you can see on oscilloscope and measure the baudrate.

 #include <stdio.h>
 #include <string.h>
 #include <stdlib.h>
 #include <unistd.h>
 #include <fcntl.h>
 #include <termios.h>
 #include <ctype.h>
 #include <errno.h>

 struct termios options;
 int fd;
 int status;
 char buf[10];
 unsigned char rx_buffer[10];
 int main(void)
        {
           fd = open("/dev/ttyS2", O_RDWR | O_NOCTTY | O_NDELAY);

      if (fd < 0)
        {
           printf("Error opening serial port\n");
           exit(1);
        }

      bzero( & options, sizeof(options));
        options.c_cflag = B3000000 | CS8 | CLOCAL | CREAD | IGNPAR | PARODD | PARENB; //8bit, Odd parity,
        tcflush(fd, TCIFLUSH);
        tcsetattr(fd, TCSANOW, & options);

    while (1)
    {
buf[0] = 0x55; //pattern
status = write(fd, & buf[0], 1);

    if (status < 0)
    {

     printf("Write error - %s \n", strerror(errno));
        exit(1);
    }

     usleep(1000000);
        printf("Sending 0x55 to /dev/ttyS2 port\n");
    }

    }


问:
How to define empty variable in python or pass value from a function to global variable?
I am making some kind of basic image filter app. I have a function to open and initialize image but variables stay just in function and I can't get them from another function, so I need to define variables global?

I tried to define variables globally and initialize them with example image, then in function I assigned new data to that variables (or not?) But it seems function that opens the file does not rewrite global variable, so my filter functions applies to my example image, not target image I opened.

image = Image.open("test.jpg")
draw = ImageDraw.Draw(image)
width = image.size[0]
height = image.size[1]
pix = image.load()

class ExampleApp(QtWidgets.QMainWindow, design.Ui_MainWindow):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.load_file.triggered.connect(self.load_image) #Can I here call load_image with arguments? How?
        self.grayscale.triggered.connect(self.Grayscale)
    def browse_file(self):
        file_name = QtWidgets.QFileDialog.getOpenFileName(self, 'Pick a picture',"","JPEG (*.jpg;*.jpeg);;PNG (*.png);;All Files (*)")[0]
        if file_name:
            print (file_name)
            return file_name
        else:
            print("File couldn't be open")
            return 0
    def load_image(self):
        file_name = self.browse_file()
        pixmap = QPixmap(file_name)
        self.pic_box.setPixmap(pixmap)
        self.pic_box.resize(pixmap.width(), pixmap.height())
        print(pixmap.width(), pixmap.height())
        self.resize(pixmap.width(), pixmap.height())
        image = Image.open(file_name) #Here I'm trying assign new image and it's properties to variables I defined on the first lines
        draw = ImageDraw.Draw(image)
        width = image.size[0]
        height = image.size[1]
        pix = image.load()
        self.show()
    def Grayscale(self): #Function works with test.jpg, not with file I'm trying to load
        for i in range(width):
            for j in range(height):
                a = pix[i, j][0]
                b = pix[i, j][1]
                c = pix[i, j][2]
                S = (a + b + c) // 3
                draw.point((i, j), (S, S, S))
        image.save("Grayscale.jpg", "JPEG")
```

My goal is to somehow pass string with file name to the global variable, so every function could access it.
There is other design.py file, I made from .ui file of QtDesigner but I think problem does not depends on it

答:
To override a global variable from a function, you need to have a line above it explicitly stating you are trying to change the global variable, not create local one. In your function change:

```<code>image = Image.open(file_name)
</code>```

to:

```<code>global image
image = Image.open(file_name)
</code>```

Python function global variables?

Body:
I am making some kind of basic image filter app. I have a function to open and initialize image but variables stay just in function and I can't get them from another function, so I need to define variables global?

I tried to define variables globally and initialize them with example image, then in function I assigned new data to that variables (or not?) But it seems function that opens the file does not rewrite global variable, so my filter functions applies to my example image, not target image I opened.

image = Image.open("test.jpg")
draw = ImageDraw.Draw(image)
width = image.size[0]
height = image.size[1]
pix = image.load()

class ExampleApp(QtWidgets.QMainWindow, design.Ui_MainWindow):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.load_file.triggered.connect(self.load_image) #Can I here call load_image with arguments? How?
        self.grayscale.triggered.connect(self.Grayscale)
    def browse_file(self):
        file_name = QtWidgets.QFileDialog.getOpenFileName(self, 'Pick a picture',"","JPEG (*.jpg;*.jpeg);;PNG (*.png);;All Files (*)")[0]
        if file_name:
            print (file_name)
            return file_name
        else:
            print("File couldn't be open")
            return 0
    def load_image(self):
        file_name = self.browse_file()
        pixmap = QPixmap(file_name)
        self.pic_box.setPixmap(pixmap)
        self.pic_box.resize(pixmap.width(), pixmap.height())
        print(pixmap.width(), pixmap.height())
        self.resize(pixmap.width(), pixmap.height())
        image = Image.open(file_name) #Here I'm trying assign new image and it's properties to variables I defined on the first lines
        draw = ImageDraw.Draw(image)
        width = image.size[0]
        height = image.size[1]
        pix = image.load()
        self.show()
    def Grayscale(self): #Function works with test.jpg, not with file I'm trying to load
        for i in range(width):
            for j in range(height):
                a = pix[i, j][0]
                b = pix[i, j][1]
                c = pix[i, j][2]
                S = (a + b + c) // 3
                draw.point((i, j), (S, S, S))
        image.save("Grayscale.jpg", "JPEG")

My goal is to somehow pass string with file name to the global variable, so every function could access it.
There is other design.py file, I made from .ui file of QtDesigner but I think problem does not depends on it

Body:
To override a global variable from a function, you need to have a line above it explicitly stating you are trying to change the global variable, not create local one. In your function change:

image = Image.open(file_name)

to:

global image
image = Image.open(file_name)

Python function global variables?


问:
laravel 5.8 Auth/RegisterController custom redirect on validation failure
I'm using Laravel 5.8, I have a single page that has both the Registration and Login forms (2 separate forms posting to the respective endpoints/controllers)

My Registration Form posts to the Auth/RegistrationController as provided by Lavarel Auth.

I would like to change the behaviour so that on an unsuccessful registration attempt it will add an additional parameter to redirect url so I know which form to apply to validation feedback too.

I'm already aware of the redirectTo variable this appears to be for successful requests though

答:
You can simply overwrite parent function to create new user in same

Auth/RegistrationController create new method as

```<code>  /**
 * Create a new user instance after a valid registration.
 *
 * @param  array  $data
 * @return \App\User
 */
protected function create(array $data)
{
    return User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'password' => Hash::make($data['password']),
    ]);
}
</code>```

Here, in '$data' variable you will get all of the parameters which you have passed through form.

For error checking you can just check for,

Laravel global error variable $errors is null or not

```<code>  /**
 * Create a new user instance after a valid registration.
 *
 * @param  array  $data
 * @return \App\User
 */
protected function create(array $data)
{
    if(!empty($errors)){
        if($data['form'] == 'form_1'){
            $redirectTo = 'fitst_form'
        }
        else if($data['form'] == 'form_2'){
            $redirectTo = 'second_form'
        }
    }
    return User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'password' => Hash::make($data['password']),
    ]);
}
</code>```

I hope this will solve your problem

Body:
You can simply overwrite parent function to create new user in same

Auth/RegistrationController create new method as

  /**
 * Create a new user instance after a valid registration.
 *
 * @param  array  $data
 * @return \App\User
 */
protected function create(array $data)
{
    return User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'password' => Hash::make($data['password']),
    ]);
}

Here, in '$data' variable you will get all of the parameters which you have passed through form.

For error checking you can just check for,

Laravel global error variable $errors is null or not

  /**
 * Create a new user instance after a valid registration.
 *
 * @param  array  $data
 * @return \App\User
 */
protected function create(array $data)
{
    if(!empty($errors)){
        if($data['form'] == 'form_1'){
            $redirectTo = 'fitst_form'
        }
        else if($data['form'] == 'form_2'){
            $redirectTo = 'second_form'
        }
    }
    return User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'password' => Hash::make($data['password']),
    ]);
}

I hope this will solve your problem


问:
Is there a way to calculate an average using JS code?
I’m trying to calculate an average using Javascript, and have following code to show you. I am building an application where I need to calculate an average score.

I have been trying to build a calculator using JavaScript in which you click on two radio buttons and trying to get an average after you click a button. You can find the HTML code for the radio buttons below:

```<code><div class="container">
    <div class="row">
        <div style = "text-align:center">
            APS Calculator
            <form action=""  id="calculator" onsubmit="fn1 ()>
            Maths
            <p>
            <input type = "radio" name = "APS Maths" value="9">9<br>
            <input type = "radio" name = "APS Maths" value="8">8<br>
            <input type = "radio" name = "APS Maths" value="7">7<br>
            <input type = "radio" name = "APS Maths" value="6">6<br>
            <input type = "radio" name = "APS Maths" value="5">5<br>
            <input type = "radio" name = "APS Maths" value="4">4<br>
            <input type = "radio" name = "APS Maths" value="3">3<br>
            <input type = "radio" name = "APS Maths" value="2">2<br>
            <input type = "radio" name = "APS Maths" value="1">1<br>
            <input type = "radio" name = "APS Maths" value="0">0<br>
            </p>
            English
            <p>
            <input type = "radio" name = "APS English" value="9">9<br>
            <input type = "radio" name = "APS English" value="8">8<br>
            <input type = "radio" name = "APS English" value="7">7<br>
            <input type = "radio" name = "APS English" value="6">6<br>
            <input type = "radio" name = "APS English" value="5">5<br>
            <input type = "radio" name = "APS English" value="4">4<br>
            <input type = "radio" name = "APS English" value="3">3<br>
            <input type = "radio" name = "APS English" value="2">2<br>
            <input type = "radio" name = "APS English" value="1">1<br>
            <input type = "radio" name = "APS English" value="0">0<br>

            <br>
                <button onclick="fn1 ()" id = "btn1"> Click Me</button>

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

Whenever I click the button after choosing two radio buttons, the output comes out as either "Your APS is : NaN" or there is no output at all. Can I find a way to output an average based on the buttons that i have clicked?

Here is the JavaScript code:

var EnglishStudent = parseInt(document.getElementsByName('APS English'));
var MathsStudent = parseInt(document.getElementsByName('APS Maths'));
var avg = (EnglishStudent + MathsStudent) / 2;

function fn1(EnglishStudent, MathsStudent)

{
  var EnglishStudent = parseInt(document.getElementsByName('APS English'));
  var MathsStudent = parseInt(document.getElementsByName('APS Maths'));
  var avg = (EnglishStudent + MathsStudent) / 2;
  return avg;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
    <div class="row">
        <div style = "text-align:center">
            APS Calculator
            <form action=""  id="calculator" onsubmit="fn1 ()>
            Maths
            <p>
            <input type = "radio" name = "APS Maths" value="9">9<br>
            <input type = "radio" name = "APS Maths" value="8">8<br>
            <input type = "radio" name = "APS Maths" value="7">7<br>
            <input type = "radio" name = "APS Maths" value="6">6<br>
            <input type = "radio" name = "APS Maths" value="5">5<br>
            <input type = "radio" name = "APS Maths" value="4">4<br>
            <input type = "radio" name = "APS Maths" value="3">3<br>
            <input type = "radio" name = "APS Maths" value="2">2<br>
            <input type = "radio" name = "APS Maths" value="1">1<br>
            <input type = "radio" name = "APS Maths" value="0">0<br>
            </p>
            English
            <p>
            <input type = "radio" name = "APS English" value="9">9<br>
            <input type = "radio" name = "APS English" value="8">8<br>
            <input type = "radio" name = "APS English" value="7">7<br>
            <input type = "radio" name = "APS English" value="6">6<br>
            <input type = "radio" name = "APS English" value="5">5<br>
            <input type = "radio" name = "APS English" value="4">4<br>
            <input type = "radio" name = "APS English" value="3">3<br>
            <input type = "radio" name = "APS English" value="2">2<br>
            <input type = "radio" name = "APS English" value="1">1<br>
            <input type = "radio" name = "APS English" value="0">0<br>

            <br>
                <button onclick="fn1 ()" id = "btn1"> Click Me</button>

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

Thank you for your help.

答:
So there is a lot of issues here:

Firstoff - doing this with radio buttons is just not really cool (lets say it this way)

Second: You can't have and unclosed onsubmit="fn1 () attribute. it needs to be onsubmit="fn1 ()" with a closing ".

Next thing is, you can't just access the selected radio button with document.getElementsByName('APS English'), because this will give you all the elements with name="APS English" - also this is why I would suggest getting rid of the radio buttons. Radio buttons don`t have any active state or any kind of that, so that you could access them in js, unless you set an anttribute on each and every one of them, whenever they change. I would much rather do something like this:

function fn1(EnglishStudent, MathsStudent){
var EnglishStudent = parseInt(document.getElementById("math").value);
var MathsStudent = parseInt(document.getElementById("english").value);
var avg = (EnglishStudent + MathsStudent) / 2;
  alert(avg);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
    <div class="row">
        <div style = "text-align:center">
            APS Calculator
            <form action=""  id="calculator" onsubmit="fn1()">
            Maths
            <p>
            <input id="math" type = "text" name = "APS Maths"><br>
            </p>
            English
            <p>
            <input id="english" type = "text" name = "APS English"><br>
            <br>
                <button id = "btn1"> Click Me</button>

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

P.S.: And don't call your function fn1() twice.

Right now you are calling it once, on the form submit, and once when the button is clicked, wich will fire it twice, and we don`t want that.

Body:
I’m trying to calculate an average using Javascript, and have following code to show you. I am building an application where I need to calculate an average score.

I have been trying to build a calculator using JavaScript in which you click on two radio buttons and trying to get an average after you click a button. You can find the HTML code for the radio buttons below:

            APS Calculator
            <form action=""  id="calculator" onsubmit="fn1 ()>
            Maths

            <input type = "radio" name = "APS Maths" value="9">9

            <input type = "radio" name = "APS Maths" value="8">8

            <input type = "radio" name = "APS Maths" value="7">7

            <input type = "radio" name = "APS Maths" value="6">6

            <input type = "radio" name = "APS Maths" value="5">5

            <input type = "radio" name = "APS Maths" value="4">4

            <input type = "radio" name = "APS Maths" value="3">3

            <input type = "radio" name = "APS Maths" value="2">2

            <input type = "radio" name = "APS Maths" value="1">1

            <input type = "radio" name = "APS Maths" value="0">0

            English

            <input type = "radio" name = "APS English" value="9">9

            <input type = "radio" name = "APS English" value="8">8

            <input type = "radio" name = "APS English" value="7">7

            <input type = "radio" name = "APS English" value="6">6

            <input type = "radio" name = "APS English" value="5">5

            <input type = "radio" name = "APS English" value="4">4

            <input type = "radio" name = "APS English" value="3">3

            <input type = "radio" name = "APS English" value="2">2

            <input type = "radio" name = "APS English" value="1">1

            <input type = "radio" name = "APS English" value="0">0

                <button onclick="fn1 ()" id = "btn1"> Click Me</button>

            </form>

Whenever I click the button after choosing two radio buttons, the output comes out as either "Your APS is : NaN" or there is no output at all. Can I find a way to output an average based on the buttons that i have clicked?

Here is the JavaScript code:

var EnglishStudent = parseInt(document.getElementsByName('APS English'));
var MathsStudent = parseInt(document.getElementsByName('APS Maths'));
var avg = (EnglishStudent + MathsStudent) / 2;

function fn1(EnglishStudent, MathsStudent)

{
  var EnglishStudent = parseInt(document.getElementsByName('APS English'));
  var MathsStudent = parseInt(document.getElementsByName('APS Maths'));
  var avg = (EnglishStudent + MathsStudent) / 2;
  return avg;
}

            APS Calculator
            <form action=""  id="calculator" onsubmit="fn1 ()>
            Maths

            <input type = "radio" name = "APS Maths" value="9">9

            <input type = "radio" name = "APS Maths" value="8">8

            <input type = "radio" name = "APS Maths" value="7">7

            <input type = "radio" name = "APS Maths" value="6">6

            <input type = "radio" name = "APS Maths" value="5">5

            <input type = "radio" name = "APS Maths" value="4">4

            <input type = "radio" name = "APS Maths" value="3">3

            <input type = "radio" name = "APS Maths" value="2">2

            <input type = "radio" name = "APS Maths" value="1">1

            <input type = "radio" name = "APS Maths" value="0">0

            English

            <input type = "radio" name = "APS English" value="9">9

            <input type = "radio" name = "APS English" value="8">8

            <input type = "radio" name = "APS English" value="7">7

            <input type = "radio" name = "APS English" value="6">6

            <input type = "radio" name = "APS English" value="5">5

            <input type = "radio" name = "APS English" value="4">4

            <input type = "radio" name = "APS English" value="3">3

            <input type = "radio" name = "APS English" value="2">2

            <input type = "radio" name = "APS English" value="1">1

            <input type = "radio" name = "APS English" value="0">0

                <button onclick="fn1 ()" id = "btn1"> Click Me</button>

            </form>

Thank you for your help.

Body:
So there is a lot of issues here:

Firstoff - doing this with radio buttons is just not really cool (lets say it this way)

Second: You can't have and unclosed onsubmit="fn1 () attribute. it needs to be onsubmit="fn1 ()" with a closing ".

Next thing is, you can't just access the selected radio button with document.getElementsByName('APS English'), because this will give you all the elements with name="APS English" - also this is why I would suggest getting rid of the radio buttons. Radio buttons don`t have any active state or any kind of that, so that you could access them in js, unless you set an anttribute on each and every one of them, whenever they change. I would much rather do something like this:

function fn1(EnglishStudent, MathsStudent){
var EnglishStudent = parseInt(document.getElementById("math").value);
var MathsStudent = parseInt(document.getElementById("english").value);
var avg = (EnglishStudent + MathsStudent) / 2;
  alert(avg);
}

<div class="container">
    <div class="row">
        <div style = "text-align:center">
            APS Calculator
            <form action=""  id="calculator" onsubmit="fn1()">
            Maths
            <p>
            <input id="math" type = "text" name = "APS Maths"><br>
            </p>
            English
            <p>
            <input id="english" type = "text" name = "APS English"><br>
            <br>
                <button id = "btn1"> Click Me</button>

            </p>
            </form>
        </div>
        </div>
    </div>

P.S.: And don't call your function fn1() twice.

Right now you are calling it once, on the form submit, and once when the button is clicked, wich will fire it twice, and we don`t want that.


问:
How to get properties of an object stored in a List
I retrieve data from a firebase realtime database which I then store into a List, so that I can display the data.

My Problem is, that the displayed data doesn't show the stored object with its properties, but the so called name/label or something simliar to this.

What is being displayed:

com.example.husiapp2.Homework@1abbfc6

What should be displayed (Object with properties):

```<code>Homework
-Title,
-Class
</code>```

My code:

```<code>public class Homework {
    public String Title;
    public String Class;
    public String ExpireDate;

    public Homework(){}

    public Homework(String title, String aClass,String expireDate) {
        Title = title;
        Class = aClass;
        ExpireDate = expireDate;
    }

}
</code>```

```<code> DatabaseReference ref;
 Homework homework;
 final List<Homework> hw = new ArrayList<>();

 ListView hwlist;

 protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view_hw);
        Log.d("HWAC122",hw.toString());
        hwlist = findViewById(R.id.hwlist);
        ref = FirebaseDatabase.getInstance().getReference("User").child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child("Homework");

        ref.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                for(DataSnapshot ds:dataSnapshot.getChildren()){
                    homework = new Homework();
                    homework.Title = ds.getValue(Homework.class).Title;
                    homework.Class = ds.getValue(Homework.class).Class;
                    homework.ExpireDate = ds.getValue(Homework.class).ExpireDate;
                    Log.d("test123",homework.toString());
                    hw.add(homework);
                }
                SetAdapter();
            }

        });

    }
 public void SetAdapter(){
        ArrayAdapter adapter = new ArrayAdapter<Homework>(this,android.R.layout.simple_list_item_1,hw);
        hwlist.setAdapter(adapter);
    }
</code>```

答: Implement getter and setter methods in java class which you have created. Press alt+insert and select implement getter and setter for all the variables which you have declared. Through this,you can insert data into firebase and retrieve data from firebase</p>

Body:
I retrieve data from a firebase realtime database which I then store into a List, so that I can display the data.

My Problem is, that the displayed data doesn't show the stored object with its properties, but the so called name/label or something simliar to this.

What is being displayed:

com.example.husiapp2.Homework@1abbfc6

What should be displayed (Object with properties):

Homework
-Title,
-Class

My code:

public class Homework {
    public String Title;
    public String Class;
    public String ExpireDate;

    public Homework(){}

    public Homework(String title, String aClass,String expireDate) {
        Title = title;
        Class = aClass;
        ExpireDate = expireDate;
    }

}

 DatabaseReference ref;
 Homework homework;
 final List<Homework> hw = new ArrayList<>();

 ListView hwlist;

 protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view_hw);
        Log.d("HWAC122",hw.toString());
        hwlist = findViewById(R.id.hwlist);
        ref = FirebaseDatabase.getInstance().getReference("User").child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child("Homework");

        ref.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                for(DataSnapshot ds:dataSnapshot.getChildren()){
                    homework = new Homework();
                    homework.Title = ds.getValue(Homework.class).Title;
                    homework.Class = ds.getValue(Homework.class).Class;
                    homework.ExpireDate = ds.getValue(Homework.class).ExpireDate;
                    Log.d("test123",homework.toString());
                    hw.add(homework);
                }
                SetAdapter();
            }

        });

    }
 public void SetAdapter(){
        ArrayAdapter adapter = new ArrayAdapter<Homework>(this,android.R.layout.simple_list_item_1,hw);
        hwlist.setAdapter(adapter);
    }


问:
Select rows of a matrix that meet a condition
In R with a matrix:

```<code>     one two three four
 [1,]   1   6    11   16
 [2,]   2   7    12   17
 [3,]   3   8    11   18
 [4,]   4   9    11   19
 [5,]   5  10    15   20
</code>```

I want to extract the submatrix whose rows have column three = 11. That is:

```<code>      one two three four
 [1,]   1   6    11   16
 [3,]   3   8    11   18
 [4,]   4   9    11   19
</code>```

I want to do this without looping. I am new to R so this is probably very obvious but the
documentation is often somewhat terse.

答:
If the dataset is called data, then all the rows meeting a condition where value of column 'pm2.5' > 300 can be received by -

data[data['pm2.5'] >300,]

Body:
In R with a matrix:

     one two three four
 [1,]   1   6    11   16
 [2,]   2   7    12   17
 [3,]   3   8    11   18
 [4,]   4   9    11   19
 [5,]   5  10    15   20

I want to extract the submatrix whose rows have column three = 11. That is:

      one two three four
 [1,]   1   6    11   16
 [3,]   3   8    11   18
 [4,]   4   9    11   19

I want to do this without looping. I am new to R so this is probably very obvious but the
documentation is often somewhat terse.


问:
Can't get custom object from NSMutableArray (IPHONE SDK)
I have a problem with a NSMutableArray... After I fill the NSMutableArray in my function (readRoutes) I can't extract the objects.... Inside the readRoutes function I can... I can't figure where is the problem..

First the NSMutableArray is fill with Route objects in the readRoutes method...(Inside RoutesListView file) (I need to fill after TableView cells with these Route objects...)

This is the Route.h file :

```<code>@interface Route : NSObject {
    NSString *routeId;
    NSString *routeDirection;
    NSString *routeName;
    NSString *routeCode;
}
@property (nonatomic,retain) NSString *routeId;
@property (nonatomic,retain) NSString *routeDirection;
@property (nonatomic,retain) NSString *routeName;
@property (nonatomic,retain) NSString *routeCode;

-(id)initWithName:(NSString *)name direction:(NSString *)d routeId:(NSString *)rid code:(NSString *)c;
@end
</code>```

The Route.m file:

```<code>#import "Route.h"

@implementation Route
@synthesize routeId;
@synthesize routeDirection;
@synthesize routeName;
@synthesize routeCode;

-(id)initWithName:(NSString *)name direction:(NSString *)d routeId:(NSString *)rid code:(NSString *)c{
    self.routeId=rid;
    self.routeName=name;
    self.routeDirection=d;
    self.routeCode=c;
    return self;
}
@end
</code>```

Now this is the RoutesListView.h file (a UITableViewController)

```<code>#import <UIKit/UIKit.h>
#import "Route.h"

@interface RoutesListView : UITableViewController  <UITableViewDelegate,UITableViewDataSource> {
    NSMutableArray *routeArray;
    NSString *dbName;
    NSString *dbPath;
}
@property (nonatomic,retain) NSMutableArray *routeArray;
@property (nonatomic,retain) NSString *dbName;
@property (nonatomic,retain) NSString *dbPath;

-(void)readRoutes;
@end
</code>```

Inside the RoutesListView.m file :

```<code>#import "RoutesListView.h"
#import "Route.h"
#import <sqlite3.h>

@implementation RoutesListView

@synthesize routeArray;
@synthesize dbName,dbPath;

#pragma mark -
#pragma mark View lifecycle

- (void)viewDidLoad {
    dbName = @"data.db";
    NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDir = [documentPaths objectAtIndex:0];
    dbPath = [documentsDir stringByAppendingPathComponent:dbName];
    routeId =[[NSMutableArray alloc] init];

    //routeArray

        NSMutableArray * array = [[NSMutableArray alloc] init];
    self.routeArray = array;

    [array release];
    [self readRoutes];
    [super viewDidLoad];
}
</code>```

INSIDE THE readRoutes method when I fill the NSMutableArray (The method work fine...):

```<code>while(sqlite3_step(compiledStatement) == SQLITE_ROW) {

                // Read the data from the result row
                NSString *aId = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 0)];
                NSString *aDirection =[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];
                NSString *aName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)];
                NSString *aCode = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 3)];

                Route *maRoute = [[Route alloc] initWithName:aName direction:aDirection routeId:aId code:aCode];

                                // I fill the NSMutableArray here...
                [routeArray addObject:maRoute];

                                [maRoute release];
                [aId release];
                [aDirection release];
                [aName release];
                [aCode release];
            }
</code>```

FINALLY WHEN I SET THE CELL TEXTLABEL...IT CRASH! :

```<code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }

    // Configure the cell...
    NSUInteger row = [indexPath row];
    Route *myRoute = (Route *)[routeArray objectAtIndex:row];
    cell.textLabel.text = myRoute.routeName;
    [myRoute release];
    return cell;
}
</code>```

Help me to understand... I lost my hair on that...

Thanks

Maxime

答:
You are over releasing several objects which will usually cause your application to crash. Also your init function is not properly implemented inside of your Route.m file. Make the following changes.

```<code>#import "Route.h"

@implementation Route
@synthesize routeId;
@synthesize routeDirection;
@synthesize routeName;
@synthesize routeCode;

-(id)initWithName:(NSString *)name direction:(NSString *)d routeId:(NSString *)rid code:(NSString *)c{
    //Must call supers implementation of init
    self = [super init];
    if(self)
    {
        self.routeId=rid;
        self.routeName=name;
        self.routeDirection=d;
        self.routeCode=c;
    }
    return self;
}
@end
</code>```

Next you are over releasing objects inside of readRoutes

```<code>while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
    // Read the data from the result row
    NSString *aId = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 0)];
    NSString *aDirection =[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];
    NSString *aName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)];
    NSString *aCode = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 3)];

    Route *maRoute = [[Route alloc] initWithName:aName direction:aDirection routeId:aId code:aCode];

    // I fill the NSMutableArray here...
    [routeArray addObject:maRoute];

    [maRoute release]; //This is right you called alloc/init
    [aId release];       //This is wrong never retained,copy or alloc/init
    [aDirection release];//Dont release here either
    [aName release];     //Dont release
    [aCode release];     //Dont release
}
</code>```

And finally you are over releasing the route inside of the following code

```<code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }

    // Configure the cell...
    NSUInteger row = [indexPath row];
    Route *myRoute = (Route *)[routeArray objectAtIndex:row];
    cell.textLabel.text = myRoute.routeName;

    [myRoute release]; //Do not release route here

    return cell;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a problem with a NSMutableArray... After I fill the NSMutableArray in my function (readRoutes) I can't extract the objects.... Inside the readRoutes function I can... I can't figure where is the problem..

First the NSMutableArray is fill with Route objects in the readRoutes method...(Inside RoutesListView file) (I need to fill after TableView cells with these Route objects...)

This is the Route.h file :

@interface Route : NSObject {
    NSString *routeId;
    NSString *routeDirection;
    NSString *routeName;
    NSString *routeCode;
}
@property (nonatomic,retain) NSString *routeId;
@property (nonatomic,retain) NSString *routeDirection;
@property (nonatomic,retain) NSString *routeName;
@property (nonatomic,retain) NSString *routeCode;

-(id)initWithName:(NSString *)name direction:(NSString *)d routeId:(NSString *)rid code:(NSString *)c;
@end

The Route.m file:

#import "Route.h"

@implementation Route
@synthesize routeId;
@synthesize routeDirection;
@synthesize routeName;
@synthesize routeCode;

-(id)initWithName:(NSString *)name direction:(NSString *)d routeId:(NSString *)rid code:(NSString *)c{
    self.routeId=rid;
    self.routeName=name;
    self.routeDirection=d;
    self.routeCode=c;
    return self;
}
@end

Now this is the RoutesListView.h file (a UITableViewController)

#import <UIKit/UIKit.h>
#import "Route.h"

@interface RoutesListView : UITableViewController  <UITableViewDelegate,UITableViewDataSource> {
    NSMutableArray *routeArray;
    NSString *dbName;
    NSString *dbPath;
}
@property (nonatomic,retain) NSMutableArray *routeArray;
@property (nonatomic,retain) NSString *dbName;
@property (nonatomic,retain) NSString *dbPath;

-(void)readRoutes;
@end

Inside the RoutesListView.m file :

#import "RoutesListView.h"
#import "Route.h"
#import <sqlite3.h>

@implementation RoutesListView

@synthesize routeArray;
@synthesize dbName,dbPath;

#pragma mark -
#pragma mark View lifecycle

- (void)viewDidLoad {
    dbName = @"data.db";
    NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDir = [documentPaths objectAtIndex:0];
    dbPath = [documentsDir stringByAppendingPathComponent:dbName];
    routeId =[[NSMutableArray alloc] init];

    //routeArray

        NSMutableArray * array = [[NSMutableArray alloc] init];
    self.routeArray = array;

    [array release];
    [self readRoutes];
    [super viewDidLoad];
}

INSIDE THE readRoutes method when I fill the NSMutableArray (The method work fine...):

while(sqlite3_step(compiledStatement) == SQLITE_ROW) {

                // Read the data from the result row
                NSString *aId = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 0)];
                NSString *aDirection =[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];
                NSString *aName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)];
                NSString *aCode = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 3)];

                Route *maRoute = [[Route alloc] initWithName:aName direction:aDirection routeId:aId code:aCode];

                                // I fill the NSMutableArray here...
                [routeArray addObject:maRoute];

                                [maRoute release];
                [aId release];
                [aDirection release];
                [aName release];
                [aCode release];
            }

FINALLY WHEN I SET THE CELL TEXTLABEL...IT CRASH! :

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }

    // Configure the cell...
    NSUInteger row = [indexPath row];
    Route *myRoute = (Route *)[routeArray objectAtIndex:row];
    cell.textLabel.text = myRoute.routeName;
    [myRoute release];
    return cell;
}

Help me to understand... I lost my hair on that...

Thanks

Maxime

Body:
You are over releasing several objects which will usually cause your application to crash. Also your init function is not properly implemented inside of your Route.m file. Make the following changes.

#import "Route.h"

@implementation Route
@synthesize routeId;
@synthesize routeDirection;
@synthesize routeName;
@synthesize routeCode;

-(id)initWithName:(NSString *)name direction:(NSString *)d routeId:(NSString *)rid code:(NSString *)c{
    //Must call supers implementation of init
    self = [super init];
    if(self)
    {
        self.routeId=rid;
        self.routeName=name;
        self.routeDirection=d;
        self.routeCode=c;
    }
    return self;
}
@end

Next you are over releasing objects inside of readRoutes

while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
    // Read the data from the result row
    NSString *aId = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 0)];
    NSString *aDirection =[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];
    NSString *aName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)];
    NSString *aCode = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 3)];

    Route *maRoute = [[Route alloc] initWithName:aName direction:aDirection routeId:aId code:aCode];

    // I fill the NSMutableArray here...
    [routeArray addObject:maRoute];

    [maRoute release]; //This is right you called alloc/init
    [aId release];       //This is wrong never retained,copy or alloc/init
    [aDirection release];//Dont release here either
    [aName release];     //Dont release
    [aCode release];     //Dont release
}

And finally you are over releasing the route inside of the following code

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }

    // Configure the cell...
    NSUInteger row = [indexPath row];
    Route *myRoute = (Route *)[routeArray objectAtIndex:row];
    cell.textLabel.text = myRoute.routeName;

    [myRoute release]; //Do not release route here

    return cell;
}


问:
Append Array To UserDefaults Without Removing Original UserDefault Info
So I am making an array of appended objects. My problem is that I want to add the objects without removing the original objects. Once I append the objects, I see them. But when I add new objects, the old objects are gone, and replaced by the older objects. How can I keep both through NSUserDefaults?

So far, I have done lots of research, and haven't found anything.

```<code>case 0:
            self.array.append("Instagram")
            UserDefaults.standard.set(self.array, forKey: "addedAccounts")
        case 1:
            self.array.append("Snapchat")
            UserDefaults.standard.set(self.array, forKey: "addedAccounts")
        case 2:
            self.array.append("VSCO")
            UserDefaults.standard.set(self.array, forKey: "addedAccounts")
        case 3:
            self.array.append("Pinterest")
            UserDefaults.standard.set(self.array, forKey: "addedAccounts")
        case 4:
            self.array.append("Tiktok")
            UserDefaults.standard.set(self.array, forKey: "addedAccounts")
        case 5:
            self.array.append("Twitter")
            UserDefaults.standard.set(self.array, forKey: "addedAccounts")
        case 6:
            self.array.append("Facebook")
            UserDefaults.standard.set(self.array, forKey: "addedAccounts")
        case 7:
            self.array.append("Google")
            UserDefaults.standard.set(self.array, forKey: "addedAccounts")
        case 8:
            self.array.append("Flickr")
            UserDefaults.standard.set(self.array, forKey: "addedAccounts")
        case 9:
            self.array.append("iFunny")
            UserDefaults.standard.set(self.array, forKey: "addedAccounts")
        case 10:
            self.array.append("Tumblr")
            UserDefaults.standard.set(self.array, forKey: "addedAccounts")
        case 11:
            self.array.append("Viber")
            UserDefaults.standard.set(self.array, forKey: "addedAccounts")
        case 12:
            self.array.append("Vine")
            UserDefaults.standard.set(self.array, forKey: "addedAccounts")
        case 13:
            self.array.append("WhatsApp")
            UserDefaults.standard.set(self.array, forKey: "addedAccounts")
        default:
            print("Error")
            print(self.array)
</code>```

No Error Messages

答:
Make sure you load self.array with the current values from UserDefaults. Then you can update the array and then update UserDefaults with the updated array.

During some appropriate initialization:

```<code>self.array = UserDefaults.standard.array(forKey: "addedAccounts") as? [String] ?? []
</code>```

Then your switch:

```<code>var newVal: String?
switch whatever {
case 0: newVal = "Instagram"
case 1: newVal = "Snapchat"
// and the rest
}
if let newVal = newVal {
    self.array.append(newVal)
    UserDefaults.standard.set(self.array, forKey: "addedAccounts")
}
</code>```

BTW - It would be a lot simpler to replace that switch with an array of accounts names.

Body:
So I am making an array of appended objects. My problem is that I want to add the objects without removing the original objects. Once I append the objects, I see them. But when I add new objects, the old objects are gone, and replaced by the older objects. How can I keep both through NSUserDefaults?

So far, I have done lots of research, and haven't found anything.

case 0:
            self.array.append("Instagram")
            UserDefaults.standard.set(self.array, forKey: "addedAccounts")
        case 1:
            self.array.append("Snapchat")
            UserDefaults.standard.set(self.array, forKey: "addedAccounts")
        case 2:
            self.array.append("VSCO")
            UserDefaults.standard.set(self.array, forKey: "addedAccounts")
        case 3:
            self.array.append("Pinterest")
            UserDefaults.standard.set(self.array, forKey: "addedAccounts")
        case 4:
            self.array.append("Tiktok")
            UserDefaults.standard.set(self.array, forKey: "addedAccounts")
        case 5:
            self.array.append("Twitter")
            UserDefaults.standard.set(self.array, forKey: "addedAccounts")
        case 6:
            self.array.append("Facebook")
            UserDefaults.standard.set(self.array, forKey: "addedAccounts")
        case 7:
            self.array.append("Google")
            UserDefaults.standard.set(self.array, forKey: "addedAccounts")
        case 8:
            self.array.append("Flickr")
            UserDefaults.standard.set(self.array, forKey: "addedAccounts")
        case 9:
            self.array.append("iFunny")
            UserDefaults.standard.set(self.array, forKey: "addedAccounts")
        case 10:
            self.array.append("Tumblr")
            UserDefaults.standard.set(self.array, forKey: "addedAccounts")
        case 11:
            self.array.append("Viber")
            UserDefaults.standard.set(self.array, forKey: "addedAccounts")
        case 12:
            self.array.append("Vine")
            UserDefaults.standard.set(self.array, forKey: "addedAccounts")
        case 13:
            self.array.append("WhatsApp")
            UserDefaults.standard.set(self.array, forKey: "addedAccounts")
        default:
            print("Error")
            print(self.array)

No Error Messages

Body:
Make sure you load self.array with the current values from UserDefaults. Then you can update the array and then update UserDefaults with the updated array.

During some appropriate initialization:

self.array = UserDefaults.standard.array(forKey: "addedAccounts") as? [String] ?? []

Then your switch:

var newVal: String?
switch whatever {
case 0: newVal = "Instagram"
case 1: newVal = "Snapchat"
// and the rest
}
if let newVal = newVal {
    self.array.append(newVal)
    UserDefaults.standard.set(self.array, forKey: "addedAccounts")
}

BTW - It would be a lot simpler to replace that switch with an array of accounts names.


问:
Ctrl+Click on a function name in Atom editor and jump into it
I've been trying to think of a better way to title this question, but unfortunately I have no idea how to explain it. Also I haven't found this on stack overflow (for the same reason stated above).

In Eclipse, I used to Ctrl+Click in the name of a method call (in java). And my cursor would jump in to the definition of my method function.

Question 1: Does anyone know the name of this behavior? I mean, maybe it's called function jumping or something like that.

Also I was searching for a plugin like this in Atom editor. Because I've tried to use this a lot of times (bad habits) and didn't work.

Question 2: Name of the plugin to do this in Atom?

Don't know if it helps, but I'm coding in JavaScript at the moment in Atom editor.

答:
To answer your first question this 'behavior' is knows as 'go to definition', or 'jump to definition'.

To answer your second question some packages you could perhaps take a look at would be,

'goto-definition'

'code-peek'

I find these help a bit but still don't achieve the standards that I would fully like. I wanted something similar to the Intellij IDEA ctrl + click.

I find myself using the ctrl + shift + f to search the entire project for the related files of the thing I'm searching for. Then I find the particular file i'm looking for and shazam! I've got what I came to get. This particular method works best for me.

I know its not exactly what your looking for but this is the best thing I've found so far to achieve something similar to what we both seem to be looking for. Hope this helps a bit,
happy coding...


问:
How to show ONLY the max value of a inner join table column?
I used INNER JOIN on two tables :

```<code>Transactions
 - transaction_id (PK)
 -ticket_id (FK) reference to ticketsforsale

Ticketsforsale :
 - ticket_id (PK)
 - type
 - price
</code>```

(there are more columns in each table but serve no purpose for this question)

The query i tried is the following :

```<code>SELECT ticketsforsale.type , SUM(ticketsforsale.price) AS TotalProfit
   FROM ticketsforsale INNER JOIN transactions
   ON ticketsforsale.ticket_id = transactions.ticket_id
GROUP BY ticketsforsale.type

The result is :
  Sports | 300
  Cruise | 600
  Theater| 100
</code>```

I tried using this line in the query

```<code>WHERE TotalProfit = SELECT(MAX(TotalProfit)
</code>```

But I can't figure out the right place for this line.

What i want the query to do is to show only the ROW containing the max value of "TotalProfit" . I am just missing the right MAX function usage on this query , thanks !

答:
You can use CTE and pick only one row based on TotalProfit values.

```<code>with cte as (
SELECT ticketsforsale.type , SUM(ticketsforsale.price) AS TotalProfit
   FROM ticketsforsale INNER JOIN transactions
   ON ticketsforsale.ticket_id = transactions.ticket_id
GROUP BY ticketsforsale.type
)
select *
from cte
order by TotalProfit desc
limit 1
</code>```

If you want to use max(), you can do something like this:

```<code>with cte as (
SELECT ticketsforsale.type , SUM(ticketsforsale.price) AS TotalProfit
   FROM ticketsforsale INNER JOIN transactions
   ON ticketsforsale.ticket_id = transactions.ticket_id
GROUP BY ticketsforsale.type
)
select *
from cte
where TotalProfit = (select max(TotalProfit) from cte)
</code>```

Body:
I used INNER JOIN on two tables :

Transactions
 - transaction_id (PK)
 -ticket_id (FK) reference to ticketsforsale

Ticketsforsale :
 - ticket_id (PK)
 - type
 - price

(there are more columns in each table but serve no purpose for this question)

The query i tried is the following :

SELECT ticketsforsale.type , SUM(ticketsforsale.price) AS TotalProfit
   FROM ticketsforsale INNER JOIN transactions
   ON ticketsforsale.ticket_id = transactions.ticket_id
GROUP BY ticketsforsale.type

The result is :
  Sports | 300
  Cruise | 600
  Theater| 100

I tried using this line in the query

WHERE TotalProfit = SELECT(MAX(TotalProfit)

But I can't figure out the right place for this line.

What i want the query to do is to show only the ROW containing the max value of "TotalProfit" . I am just missing the right MAX function usage on this query , thanks !

Body:
You can use CTE and pick only one row based on TotalProfit values.

with cte as (
SELECT ticketsforsale.type , SUM(ticketsforsale.price) AS TotalProfit
   FROM ticketsforsale INNER JOIN transactions
   ON ticketsforsale.ticket_id = transactions.ticket_id
GROUP BY ticketsforsale.type
)
select *
from cte
order by TotalProfit desc
limit 1

If you want to use max(), you can do something like this:

with cte as (
SELECT ticketsforsale.type , SUM(ticketsforsale.price) AS TotalProfit
   FROM ticketsforsale INNER JOIN transactions
   ON ticketsforsale.ticket_id = transactions.ticket_id
GROUP BY ticketsforsale.type
)
select *
from cte
where TotalProfit = (select max(TotalProfit) from cte)


问:
How to make a simple JavaScript call from a PHP function?
I have a simple PHP function that is being called when a form is submitted:

```<code>function uc_paypal_ec_submit_form($form, &$form_state) {
  $form['actions'] = array('#type' => 'actions');
  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit order'),
  );
  return $form;
}
</code>```

What I need is to be able to do a simple Google Analytics call like this:

```<code>_gaq.push(['_trackPageview', 'virtual/formSubmit']);
</code>```

I've tried a few options, but nothing works. I don't see the call being made to Google Analytics...

How can I fix this problem?

答:
```<code>echo " <script type='text/javascript'>_gaq.push(['_trackPageview', 'virtual/formSubmit']); </script> ";
</code>```

Body:
I have a simple PHP function that is being called when a form is submitted:

function uc_paypal_ec_submit_form($form, &$form_state) {
  $form['actions'] = array('#type' => 'actions');
  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit order'),
  );
  return $form;
}

What I need is to be able to do a simple Google Analytics call like this:

_gaq.push(['_trackPageview', 'virtual/formSubmit']);

I've tried a few options, but nothing works. I don't see the call being made to Google Analytics...

How can I fix this problem?


问:
Can I customize a CustomInput button from reactstrap?
I'm using reactstrap in my project, however when I try to use a custom input to upload a picture, the component  shows a button with the name "Browse", since I am creating a project in a different language, I need to change that "Browse" to "Another Word", I've reading the docs but did not find any solution

答:
Change the css property of content for input type:

```<code>.custom-file-label::after {
    content:"another word" !important;
}
</code>```

Body:
Change the css property of content for input type:

.custom-file-label::after {
    content:"another word" !important;
}


问:
Neural Network doesn't learn - simple classification problem
I am currently trying to learn simple neural network recognize 4 different outputs. There are 2-value-inputs which are actually something like this:

output + uniform(-0.2,0.2) + 1

There are only 200 records of that data - but that's important for me to stay with as little data as possible.

Example of input and output next to it:

```<code>0.9936288071867917,1.0163870658585894  -  0

2.0133450399223953,1.9965272907556022  -  1

3.013918319917813,3.018102735071009  -  2

3.9935640040186025,4.00379069782054  -  3
</code>```

I tried to set different number of epochs, hidden neurons and activation functions. The thing is I want to keep neural network very simple - that means only two hidden layers with max number of about 20 hidden neurons per layer.
No matter what I do it still doesn't learn or learns very poorly.

Here's code

import keras
import numpy as np
from sklearn.model_selection import train_test_split
#import pandas as pd
#import tensorflow as tf
from sklearn.utils import shuffle
from sklearn import metrics

seed = 10
np.random.seed(seed)

dataset = np.loadtxt("dataset.csv",delimiter=',')
#dataset = shuffle(dataset)

X = dataset[:,:2]
Y = dataset[:,2]

#print(X)
#print(Y)

(X_train,X_test,Y_train,Y_test) = train_test_split(X, Y, test_size=0.10, random_state=seed)
input_shape = (2,)

model = keras.models.Sequential()
model.add(keras.layers.InputLayer(input_shape))
model.add(keras.layers.core.Dense(8, activation='sigmoid'))
model.add(keras.layers.core.Dense(4, activation='sigmoid'))

model.compile(optimizer='adam',loss='sparse_categorical_crossentropy',metrics=['accuracy'])
history = model.fit(X_train,Y_train,validation_split=0.10,epochs=30)

val_loss, val_acc = model.evaluate(X_test,Y_test)
print('\nCost = ',val_loss,'\nAccuracy = ',val_acc,'\n')

```

<p>I still get results looking like this through epochs(almost the same) and evaluation:</p>

<pre class="lang-py prettyprint-override"><code>Cost =  1.40975821018219
Accuracy =  0.20000000298023224
</code>```

What can I do to improve that neural network?

答:
There might be more to it, but the first thing that comes to mind is normalizing your data. as you can see in this plot:

 the value of sigmoid does not differ greatly for 1, 2,3 and 4. if, however, you're values were between -1 to 1, you would get much better results.

Body:
I am currently trying to learn simple neural network recognize 4 different outputs. There are 2-value-inputs which are actually something like this:

output + uniform(-0.2,0.2) + 1

There are only 200 records of that data - but that's important for me to stay with as little data as possible.

Example of input and output next to it:

0.9936288071867917,1.0163870658585894  -  0

2.0133450399223953,1.9965272907556022  -  1

3.013918319917813,3.018102735071009  -  2

3.9935640040186025,4.00379069782054  -  3

I tried to set different number of epochs, hidden neurons and activation functions. The thing is I want to keep neural network very simple - that means only two hidden layers with max number of about 20 hidden neurons per layer.
No matter what I do it still doesn't learn or learns very poorly.

Here's code

import keras
import numpy as np
from sklearn.model_selection import train_test_split
#import pandas as pd
#import tensorflow as tf
from sklearn.utils import shuffle
from sklearn import metrics

seed = 10
np.random.seed(seed)

dataset = np.loadtxt("dataset.csv",delimiter=',')
#dataset = shuffle(dataset)

X = dataset[:,:2]
Y = dataset[:,2]

#print(X)
#print(Y)

(X_train,X_test,Y_train,Y_test) = train_test_split(X, Y, test_size=0.10, random_state=seed)
input_shape = (2,)

model = keras.models.Sequential()
model.add(keras.layers.InputLayer(input_shape))
model.add(keras.layers.core.Dense(8, activation='sigmoid'))
model.add(keras.layers.core.Dense(4, activation='sigmoid'))

model.compile(optimizer='adam',loss='sparse_categorical_crossentropy',metrics=['accuracy'])
history = model.fit(X_train,Y_train,validation_split=0.10,epochs=30)

val_loss, val_acc = model.evaluate(X_test,Y_test)
print('\nCost = ',val_loss,'\nAccuracy = ',val_acc,'\n')

I still get results looking like this through epochs(almost the same) and evaluation:

Cost =  1.40975821018219
Accuracy =  0.20000000298023224

What can I do to improve that neural network?


问:
IIS 8.5 URL rewrite change TLD
I want to create a rewrite rule in IIS 8.5 so that the TLD in the url gets changed from .com to .net.

example:

from: http://sub.domain.com/index.aspx?test=123

to: http://sub.domain.net/index.aspx?test=123

At the moment I got something like this in my web.config but is doesn't seem to work:

```<code>   <rule name="TLD" enabled="false">
       <match url="(.*)" />
       <conditions>
           <add input="{HTTP_HOST}" pattern="^(www.)?([a-z]*.)(domain)(.com)(/?.*)$" />
       </conditions>
       <action type="Rewrite" url="http://{C:2}{C:3}.net/{C:5}" />
   </rule>
</code>```

Any suggestions?

答:
I was looking for the exact same problem and found this

```<code> <rule name="WWW" enabled="true" stopProcessing="true">
     <match url=" (.*)"/>
     <conditions >
        <add input="{HTTP_HOST}" pattern="^(www\.)?example\.old$"/>
     </conditions>
     <action type="Redirect" url="h++p://example.com/{R:1}" redirectType="Permanent" />
 </rule>
</code>```

Found it here: ReWrite top-level domain (TLD)

Title: IIS 8.5 URL rewrite change TLD

Body:
I want to create a rewrite rule in IIS 8.5 so that the TLD in the url gets changed from .com to .net.

example:

from: http://sub.domain.com/index.aspx?test=123

to: http://sub.domain.net/index.aspx?test=123

At the moment I got something like this in my web.config but is doesn't seem to work:

   <rule name="TLD" enabled="false">
       <match url="(.*)" />
       <conditions>
           <add input="{HTTP_HOST}" pattern="^(www.)?([a-z]*.)(domain)(.com)(/?.*)$" />
       </conditions>
       <action type="Rewrite" url="http://{C:2}{C:3}.net/{C:5}" />
   </rule>

Any suggestions?

Body:
I was looking for the exact same problem and found this

 <rule name="WWW" enabled="true" stopProcessing="true">
     <match url=" (.*)"/>
     <conditions >
        <add input="{HTTP_HOST}" pattern="^(www\.)?example\.old$"/>
     </conditions>
     <action type="Redirect" url="h++p://example.com/{R:1}" redirectType="Permanent" />
 </rule>

Found it here: ReWrite top-level domain (TLD)


问:
celery max retries on signature set isn't updated
Hey :)

So I encountered a bug in my code and while trying to solve it -  I wrote this little celery task:

```<code>@shared_task(bind=True, name='sometask', autoretry_for=(Exception,), default_retry_delay=1)
def sometask(self, items, *args, **kwargs):
    print(self.max_retries)
    raise Exception
</code>```

and I tried to override the retries by envoking set() on the signature :

```<code>s = sometask.s(items=[]).set(max_retries=200, countdown=1)
s()
</code>```

when I checked the output I could see that what was printed is 3 - the default max retries in celery. and not my 200..

Can anyone tell me what it is that I'm doing wrong?

I need to override the max retries and that seemed to be my only option , but it doesn't work as I expected.

Thanks!

答:
Although the docs say that retry_policy is a valid option to pass to apply_async, it appears to be the retry policy to publish a task, not for the task itself to retry.

In addition, max_retries for the task does not appear to be mutable at runtime. However, it can be set in the decorator: @shared_task(bind=True, name='sometask', autoretry_for=(Exception,), default_retry_delay=1, max_retries=200).

I can upon this when trying to change the max_retries at run time which doesn't seem possible, this issue, non-withstanding. One workaround:

@shared_task(bind=True, max_retries=200)
def sometask(self, items, *args, **kwargs):
    print(self.max_retries)
    raise Exception

# only want to retry normal 3 times here
sometask.apply_async(retries=sometask.max_retries - 3)
```

Body:
Hey :)

So I encountered a bug in my code and while trying to solve it -  I wrote this little celery task:

@shared_task(bind=True, name='sometask', autoretry_for=(Exception,), default_retry_delay=1)
def sometask(self, items, *args, **kwargs):
    print(self.max_retries)
    raise Exception

and I tried to override the retries by envoking set() on the signature :

s = sometask.s(items=[]).set(max_retries=200, countdown=1)
s()

when I checked the output I could see that what was printed is 3 - the default max retries in celery. and not my 200..

Can anyone tell me what it is that I'm doing wrong?

I need to override the max retries and that seemed to be my only option , but it doesn't work as I expected.

Thanks!


问:
Set a form's action attribute when submitting?
How do I change a form's action attribute right after clicking the submit button?  </p>

答:
```<code><input type='submit' value='Submit' onclick='this.form.action="somethingelse";' />
</code>```

Or you can modify it from outside the form, with javascript the normal way:

```<code> document.getElementById('form_id').action = 'somethingelse';
</code>```

Body:
<input type='submit' value='Submit' onclick='this.form.action="somethingelse";' />

Or you can modify it from outside the form, with javascript the normal way:

 document.getElementById('form_id').action = 'somethingelse';


问:
How do I remove the padding inside a div that has a propery of display and a value of inline-block
How do I remove the padding from inside of a div with the display set to "inline-block".

Below is the html and css.

.showExpCusWrap {
  background-color: #A8D3FF;
  display: inline-block;
  border: 1px solid #004F9D;
  padding: 0px 10px;
  font-family: Tahoma;
}

.showExpCusWrap label {
  font-size: 0.9em;
  margin: 0px;
  padding: 0px;
}

.showExpCusWrap input[type="date"] {
  margin: 0px;
  padding: 0px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="showExpCusWrap">
  <label for="showExpFrom">From</label>
  <input type="date" name="showExpFrom" id="showExpFrom">
  <label for="showExpTo">To</label>
  <input type="date" name="showExpTo" id="showExpTo">
  <input type="button" name="showExpCus" id="showExpCus" value="Show" class="exp-button-small">
</div></code>```

This is how it looks. Notice the top and bottom padding inside.

I have checked the broswer default styling. It does not set any padding. So, how to remove those? I want all the elements inside the div to appear without any spacing from top or bottom.

答:
You may use line-height increase or decrease it  , this is to be check through different browsers of course .. (form elements are also part of the browser not only html tags).

.showExpCusWrap {
  background-color: #A8D3FF;
  display: inline-block;
  border: 1px solid #004F9D;
  padding:  10px;
  font-family: Tahoma;
}

.showExpCusWrap label {
  font-size: 0.9em;
  margin: 0px;
  padding: 0px;
}

.showExpCusWrap input[type="date"] {
  margin: 0px;
  padding: 0px;
}

/* increase all
label, input:not([type="button"]) {
line-height:1.4em;
}
*/

label,
input {
  vertical-align: middle;
  box-sizing:border-box;
}
/* or decrease the one
[type="button"] {
  line-height: 1em;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="showExpCusWrap">
  <label for="showExpFrom">From</label>
  <input type="date" name="showExpFrom" id="showExpFrom">
  <label for="showExpTo">To</label>
  <input type="date" name="showExpTo" id="showExpTo">
  <input type="button" name="showExpCus" id="showExpCus" value="Show" class="exp-button-small">
</div></code>```

Body:
How do I remove the padding from inside of a div with the display set to "inline-block".

Below is the html and css.

.showExpCusWrap {
  background-color: #A8D3FF;
  display: inline-block;
  border: 1px solid #004F9D;
  padding: 0px 10px;
  font-family: Tahoma;
}

.showExpCusWrap label {
  font-size: 0.9em;
  margin: 0px;
  padding: 0px;
}

.showExpCusWrap input[type="date"] {
  margin: 0px;
  padding: 0px;
}

  From
  <input type="date" name="showExpFrom" id="showExpFrom">
  To
  <input type="date" name="showExpTo" id="showExpTo">
  <input type="button" name="showExpCus" id="showExpCus" value="Show" class="exp-button-small">

This is how it looks. Notice the top and bottom padding inside.

I have checked the broswer default styling. It does not set any padding. So, how to remove those? I want all the elements inside the div to appear without any spacing from top or bottom.

Body:
You may use line-height increase or decrease it  , this is to be check through different browsers of course .. (form elements are also part of the browser not only html tags).

.showExpCusWrap {
  background-color: #A8D3FF;
  display: inline-block;
  border: 1px solid #004F9D;
  padding:  10px;
  font-family: Tahoma;
}

.showExpCusWrap label {
  font-size: 0.9em;
  margin: 0px;
  padding: 0px;
}

.showExpCusWrap input[type="date"] {
  margin: 0px;
  padding: 0px;
}

/* increase all
label, input:not([type="button"]) {
line-height:1.4em;
}
*/

label,
input {
  vertical-align: middle;
  box-sizing:border-box;
}
/* or decrease the one
[type="button"] {
  line-height: 1em;
}

<div class="showExpCusWrap">
  <label for="showExpFrom">From</label>
  <input type="date" name="showExpFrom" id="showExpFrom">
  <label for="showExpTo">To</label>
  <input type="date" name="showExpTo" id="showExpTo">
  <input type="button" name="showExpCus" id="showExpCus" value="Show" class="exp-button-small">
</div>


问:
How to parse YAML file to a Java class
I have a class Recipe that represents this YAML block:

```<code>id: Ex1
  uses:
    - Database: ["D1", "D2"]
    - MetaFeature: ["M1", "M2"]
    - Algorithm: ["A1", "A2"]
    - Config: ["C1", "C4"]
</code>```

public class Recipe {
    private String id;
    private HashMap<String, HashSet<String>> uses;
}
```

Is there a way to parse this YAML to Recipe class without creating other classes or doing some tricks?

答:
Firs of all, you have to include SnakeYML as dependency in maven pom.xml. I provide below the maven dependency for snakeyml.

```<code><dependency>
    <groupId>org.yaml</groupId>
    <artifactId>snakeyaml</artifactId>
    <version>1.21</version>
</dependency>
</code>```

If you are not using Maven, you can download the jar file from the following link.
http://central.maven.org/maven2/org/yaml/snakeyaml/1.21/snakeyaml-1.21.jar

I modified your yml file bit to make it work. Find below the structure of yml file.

```<code>id: Ex1
uses:
  Database: ["D1", "D2"]
  MetaFeature: ["M1", "M2"]
  Algorithm: ["A1", "A2"]
  Config: ["C1", "C4"]
</code>```

Let me provide you the code which is working.

```<code>import java.util.HashMap;
import java.util.HashSet;

public class Recipe {
  private String id;
  private HashMap<String, HashSet<String>> uses;

  public String getId() {
    return id;
  }

  public void setId(String id) {
    this.id = id;
  }

  public HashMap<String, HashSet<String>> getUses() {
    return uses;
  }

  public void setUses(HashMap<String, HashSet<String>> uses) {
    this.uses = uses;
  }

  @Override
  public String toString() {
    return "Recipe{" + "id='" + id + '\'' + ", uses=" + uses + '}';
  }
}
</code>```

Test code as per your Recipe class.

```<code>import org.yaml.snakeyaml.Yaml;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Map;

public class TestYml {
  public static void main(String[] args) throws Exception {
    Yaml yaml = new Yaml();
    InputStream inputStream =
        new FileInputStream("your location\\yml-file-name.yml");

    Recipe recipe = yaml.loadAs(inputStream,Recipe.class);
    System.out.println("recipe = " + recipe);
  }
}
</code>```

Title: How to parse YAML file to a Java class

Body:
I have a class Recipe that represents this YAML block:

id: Ex1
  uses:
    - Database: ["D1", "D2"]
    - MetaFeature: ["M1", "M2"]
    - Algorithm: ["A1", "A2"]
    - Config: ["C1", "C4"]

public class Recipe {
    private String id;
    private HashMap<String, HashSet<String>> uses;
}

Is there a way to parse this YAML to Recipe class without creating other classes or doing some tricks?

Body:
Firs of all, you have to include SnakeYML as dependency in maven pom.xml. I provide below the maven dependency for snakeyml.

<dependency>
    <groupId>org.yaml</groupId>
    <artifactId>snakeyaml</artifactId>
    <version>1.21</version>
</dependency>

If you are not using Maven, you can download the jar file from the following link.
http://central.maven.org/maven2/org/yaml/snakeyaml/1.21/snakeyaml-1.21.jar

I modified your yml file bit to make it work. Find below the structure of yml file.

id: Ex1
uses:
  Database: ["D1", "D2"]
  MetaFeature: ["M1", "M2"]
  Algorithm: ["A1", "A2"]
  Config: ["C1", "C4"]

Let me provide you the code which is working.

import java.util.HashMap;
import java.util.HashSet;

public class Recipe {
  private String id;
  private HashMap<String, HashSet<String>> uses;

  public String getId() {
    return id;
  }

  public void setId(String id) {
    this.id = id;
  }

  public HashMap<String, HashSet<String>> getUses() {
    return uses;
  }

  public void setUses(HashMap<String, HashSet<String>> uses) {
    this.uses = uses;
  }

  @Override
  public String toString() {
    return "Recipe{" + "id='" + id + '\'' + ", uses=" + uses + '}';
  }
}

Test code as per your Recipe class.

import org.yaml.snakeyaml.Yaml;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Map;

public class TestYml {
  public static void main(String[] args) throws Exception {
    Yaml yaml = new Yaml();
    InputStream inputStream =
        new FileInputStream("your location\\yml-file-name.yml");

    Recipe recipe = yaml.loadAs(inputStream,Recipe.class);
    System.out.println("recipe = " + recipe);
  }
}


问:
Creating APIs with nested class methods (Typescript)
I'm trying to create a typescript class that wraps a REST api, and i'd like to organize the various methods into sub objects for better expressibility of the code. any way of doing so and still maintaining access to the class instance via 'this' from whithin the methods?

for example consider the following class:

```<code>class ApiService {
  constructor() {....}

  getMedia() {}

  uploadMedia() {}

  sendMassage() {}

  recieveMessage() {}

}
</code>```

I'd like to organize the above methods so that i'd be able to call them like so:

```<code>const service = new ApiService();
//to call getMedia()
service.media.get();
//to call sendMessage()
service.messages.send();
// and so on
</code>```

答:
I think to achieve what you're asking for exactly as stated, you should use arrow functions so that the apiService.media and apiService.message objects don't have their own this context to get in the way.  For example:

```<code>class ApiService {

    constructor(public name: string) { }

    private getMedia() {
        console.log(this.name+" getMedia");
    }

    private uploadMedia() {
        console.log(this.name+" uploadMedia");
    }

    private sendMassage() {
        console.log(this.name+" sendMessage");
    }

    private recieveMessage() {
        console.log(this.name+" receiveMessage");
    }

    // instance methods
    public media = {
        get: () => this.getMedia(),
        upload: () => this.uploadMedia()
    }

    // instance methods
    public message = {
        send: () => this.sendMassage(),
        receive: () => this.recieveMessage()
    }

}
</code>```

Note that this means that each instance of ApiService will have its own copy of the function-valued properties message.send etc.  They will not sit on the ApiService.prototype like normal methods.  This shouldn't matter much unless you are spawning many instances of ApiService.

Let's make sure it works and is bound correctly:

```<code>const api1 = new ApiService("One");
const api2 = new ApiService("Two");

api1.message.receive(); // One recieveMessage
api2.message.receive(); // Two receiveMessage

api1.media.get(); // One getMedia
api2.media.get(); // Two getMedia
</code>```

Looks good.  Hope that helps; good luck!

Link to code

Body:
I'm trying to create a typescript class that wraps a REST api, and i'd like to organize the various methods into sub objects for better expressibility of the code. any way of doing so and still maintaining access to the class instance via 'this' from whithin the methods?

for example consider the following class:

class ApiService {
  constructor() {....}

  getMedia() {}

  uploadMedia() {}

  sendMassage() {}

  recieveMessage() {}

}

I'd like to organize the above methods so that i'd be able to call them like so:

const service = new ApiService();
//to call getMedia()
service.media.get();
//to call sendMessage()
service.messages.send();
// and so on

Body:
I think to achieve what you're asking for exactly as stated, you should use arrow functions so that the apiService.media and apiService.message objects don't have their own this context to get in the way.  For example:

class ApiService {

    constructor(public name: string) { }

    private getMedia() {
        console.log(this.name+" getMedia");
    }

    private uploadMedia() {
        console.log(this.name+" uploadMedia");
    }

    private sendMassage() {
        console.log(this.name+" sendMessage");
    }

    private recieveMessage() {
        console.log(this.name+" receiveMessage");
    }

    // instance methods
    public media = {
        get: () => this.getMedia(),
        upload: () => this.uploadMedia()
    }

    // instance methods
    public message = {
        send: () => this.sendMassage(),
        receive: () => this.recieveMessage()
    }

}

Note that this means that each instance of ApiService will have its own copy of the function-valued properties message.send etc.  They will not sit on the ApiService.prototype like normal methods.  This shouldn't matter much unless you are spawning many instances of ApiService.

Let's make sure it works and is bound correctly:

const api1 = new ApiService("One");
const api2 = new ApiService("Two");

api1.message.receive(); // One recieveMessage
api2.message.receive(); // Two receiveMessage

api1.media.get(); // One getMedia
api2.media.get(); // Two getMedia

Looks good.  Hope that helps; good luck!

<a href="https://typescript-play.js.org/#code/MYGwhgzhAECCAOBLAygUwE4DdHFdA3gFDTTAD2AdhAC7oCuw1Z6AFPHQEYg7QVgC2qAFzQa6RBQDmASgIBfQsWjxxmMNTyTU1ALKoAJojAtZREiXJUyIVADoQZSS2oALRBFt9B0ANTQARNBaugZG-tIA3EoKSiqIahrQdPAOYPp6hsamShaUENZ2Dk6u7p4CeH6ByanpoWDhUSQxJHEJeBCoFOmQEGBaJgQ5pHkF9o7Obh5eFQGinbVQfagN0Yotqup46KjAiKiYqHqL-dnmw1Y2Y8WTZd6V0Nu48Yeox8uRq0oA9F-QEjRgCi4aCCVxkfQQWKcbjAEF1aAAXkGZ2CIgGCIAfNASh5ghkjCYADRDapkNJo2SY7E3UlpfFZaJRb6-f7UQHA0EucGQlrQniCN6I5HmDpdCmIrE42yi7pvIlDR6oZ7iqlSx57A5HXonRmEGKWGjQMBIACMQooqAA7nAkGgsDhUCx-AB5C0rA3UI1IABM5qtNpQGGwuCdABVLWQVoRjYgTbYBdq7IrniYItAftBXVsdhqXm9oz7469E7ZkwdU+nfuGyA8dkrNcWlooY3HBJlbMEKxms0FtPSC4hvUX253IpXoNXeyFMoQgA" rel="nofollow noreferrer">Link to code


问:
Domain Driven Design: Domain Service, Application Service
Can someone explain the difference between domain and application services by providing some examples? And, if a service is a domain service, would I put the actual implementation of this service within the domain assembly and if so, would I also inject repositories into that domain service? Some info would be really helpful.</p>

答:
Domain Services: A service that expresses a business logic that is not part of any Aggregate Root.

You have 2 Aggregate:

Product which contains name and price.

Purchase which contains purchase date, list of products ordered with quantity and product price at that time, and payment method.

Checkout is not part of either of these two models and is concept in your business.

Checkout can be created as a Domain Service which fetches all product and compute the total price, pay the total by calling another Domain Service PaymentService with an implementation part of Infrastructure, and convert it into Purchase.

Application Services: A service that "orchestrates" or exercises Domain methods. This can be as simple as just your Controller.

This is the place where you usually do:

```<code>public String createProduct(...some attributes) {
  if (productRepo.getByName(name) != null) {
    throw new Exception();
  }

  productId = productRepository.nextIdentity();

  product = new Product(productId, ...some attributes);

  productRepository.save(product);

  return productId.value();
  // or Product itself
  // or just void if you dont care about result
}

public void renameProduct(productId, newName) {
  product = productRepo.getById(productId);

  product.rename(newName);

  productRepo.save(product);
}

</code>```

You can do validations here like checking if a Product is unique. Unless a Product being unique is an invariant then that should be part of Domain Service that might be called UniqueProductChecker because it can't be part of Product class and it interacts with multiple Aggregates.

Here is full-blown example of DDD project: https://github.com/VaughnVernon/IDDD_Samples

You can find lots of examples of Application Service and a couple of Domain Service

ContentLicense: CC BY-SA 2.5

Body:
Domain Services: A service that expresses a business logic that is not part of any Aggregate Root.

You have 2 Aggregate:

Product which contains name and price.

Purchase which contains purchase date, list of products ordered with quantity and product price at that time, and payment method.

Checkout is not part of either of these two models and is concept in your business.

Checkout can be created as a Domain Service which fetches all product and compute the total price, pay the total by calling another Domain Service PaymentService with an implementation part of Infrastructure, and convert it into Purchase.

Application Services: A service that "orchestrates" or exercises Domain methods. This can be as simple as just your Controller.

This is the place where you usually do:

public String createProduct(...some attributes) {
  if (productRepo.getByName(name) != null) {
    throw new Exception();
  }

  productId = productRepository.nextIdentity();

  product = new Product(productId, ...some attributes);

  productRepository.save(product);

  return productId.value();
  // or Product itself
  // or just void if you dont care about result
}

public void renameProduct(productId, newName) {
  product = productRepo.getById(productId);

  product.rename(newName);

  productRepo.save(product);
}

You can do validations here like checking if a Product is unique. Unless a Product being unique is an invariant then that should be part of Domain Service that might be called UniqueProductChecker because it can't be part of Product class and it interacts with multiple Aggregates.

Here is full-blown example of DDD project: https://github.com/VaughnVernon/IDDD_Samples

You can find lots of examples of Application Service and a couple of Domain Service


问:
Returning multiple recipients names in MySQL (messaging system)
I'm creating a multiple-recipient threaded messaging system similar to the iPhone SMS system (where both inbox and outbox are combined into one display, and only one thread can exist between two users).

Messages are stored using a senderid column (e.g. "11") and a recipients column (e.g. ",13,10,15,20,").  In order to store multiple recipients, I seperate them out with commas and query the field with a "%" + ",$userid," + "#" call.  The problem with this is that it messes up the LEFT JOIN which connects the recipientsid to the users table (which has the name of the users).

Here's my current query:

```<code>$sql =
  "SELECT DISTINCT CASE
   WHEN $userid != senderid THEN senderid ELSE recipients END someid,
   CASE WHEN 13 != senderid THEN senders.username ELSE receivers.username END somename,
   messages.body,
   messages.time
   FROM messages
   LEFT JOIN users AS senders ON messages.senderid = senders.id
   LEFT JOIN users AS receivers ON messages.recipients = receivers.id
   WHERE messages.recipients = '#' + ',$userid,' + '#'
   OR messages.senderid = $userid
   ORDER BY messages.time";
</code>```

Here's what I'd like to do:

If there is only one recipient id in recipients (the content looks like ",id,", then remove the commas surrounding the id to find the sendername (LEFT JOIN users AS receivers ON messages.recipients(WITHOUT COMMAS) = receivers.id.

If there is more than one recipient id in recipients (the content looks like ",id,id2,id3," etc.), somehow pull all the names which correspond to the IDs and store the result similar to the following: sendername = "Name1, Name2, Name3";.

Anyone have any idea how I would approach this?  A subquery maybe?  I'd really appreciate the help.

答:
1st. Instead of:

```<code>WHERE messages.recipients = '#' + ',$userid,' + '#'
</code>```

you can drop the starting and ending commas and use :

```<code>WHERE FIND_IN_SET($userid, messages.recipients) > 0
</code>```

So you could also have this condition for the LEFT JOIN:

```<code>LEFT JOIN users AS receivers
  ON FIND_IN_SET(receivers.id, messages.recipients) > 0
</code>```

and then group by message and concat the names with GROUP_CONCAT().

Something like this:

```<code>  SELECT senders.name AS senderName
       , messages.body
       , messages.time
       , GROUP_CONCAT( receivers.name
                       ORDER BY receivers.id
                       SEPARATOR ','
                     )
         AS receiversNames
  FROM messages
    LEFT JOIN users AS senders
      ON messages.senderid = senders.id
    LEFT JOIN users AS receivers
      ON FIND_IN_SET(receivers.id, messages.recipients) > 0
  GROUP BY messages.id
  ORDER BY messages.time
</code>```

will give you all messages with sender's name and receivers' names concatenated.

I guess that every message has exactly 1 (or zero) senders. If not, and some messages have more than 1 senders, then you'll probably need to edit the GROUP BY.

Warning: This type of queries may be slow (or even terribly slow) when there will be many rows in the tables. No index can be used on messages.recipients and thus slow down the query. So, you better consider now the option of normalizing your structure with a MessageRecipient intermediate table.

Body:
I'm creating a multiple-recipient threaded messaging system similar to the iPhone SMS system (where both inbox and outbox are combined into one display, and only one thread can exist between two users).

Messages are stored using a senderid column (e.g. "11") and a recipients column (e.g. ",13,10,15,20,").  In order to store multiple recipients, I seperate them out with commas and query the field with a "%" + ",$userid," + "#" call.  The problem with this is that it messes up the LEFT JOIN which connects the recipientsid to the users table (which has the name of the users).

Here's my current query:

$sql =
  "SELECT DISTINCT CASE
   WHEN $userid != senderid THEN senderid ELSE recipients END someid,
   CASE WHEN 13 != senderid THEN senders.username ELSE receivers.username END somename,
   messages.body,
   messages.time
   FROM messages
   LEFT JOIN users AS senders ON messages.senderid = senders.id
   LEFT JOIN users AS receivers ON messages.recipients = receivers.id
   WHERE messages.recipients = '#' + ',$userid,' + '#'
   OR messages.senderid = $userid
   ORDER BY messages.time";

Here's what I'd like to do:

If there is only one recipient id in recipients (the content looks like ",id,", then remove the commas surrounding the id to find the sendername (LEFT JOIN users AS receivers ON messages.recipients(WITHOUT COMMAS) = receivers.id.

If there is more than one recipient id in recipients (the content looks like ",id,id2,id3," etc.), somehow pull all the names which correspond to the IDs and store the result similar to the following: sendername = "Name1, Name2, Name3";.

Anyone have any idea how I would approach this?  A subquery maybe?  I'd really appreciate the help.

Body:
1st. Instead of:

WHERE messages.recipients = '#' + ',$userid,' + '#'

you can drop the starting and ending commas and use :

WHERE FIND_IN_SET($userid, messages.recipients) > 0

So you could also have this condition for the LEFT JOIN:

LEFT JOIN users AS receivers
  ON FIND_IN_SET(receivers.id, messages.recipients) > 0

and then group by message and concat the names with GROUP_CONCAT().

Something like this:

  SELECT senders.name AS senderName
       , messages.body
       , messages.time
       , GROUP_CONCAT( receivers.name
                       ORDER BY receivers.id
                       SEPARATOR ','
                     )
         AS receiversNames
  FROM messages
    LEFT JOIN users AS senders
      ON messages.senderid = senders.id
    LEFT JOIN users AS receivers
      ON FIND_IN_SET(receivers.id, messages.recipients) > 0
  GROUP BY messages.id
  ORDER BY messages.time

will give you all messages with sender's name and receivers' names concatenated.

I guess that every message has exactly 1 (or zero) senders. If not, and some messages have more than 1 senders, then you'll probably need to edit the GROUP BY.

Warning: This type of queries may be slow (or even terribly slow) when there will be many rows in the tables. No index can be used on messages.recipients and thus slow down the query. So, you better consider now the option of normalizing your structure with a MessageRecipient intermediate table.