问:
What is a working method for extracting numeric values with associated data from open text?
I tried to look for a solution but nothing was giving me quite what I needed. I'm not sure regex can do what I need.

I need to process a large amount of data where license information is provided. I just need to grab the number of licenses and the name for each license then group and tally the license counts for each company.

Here's an example of the data pulled:

```<code>L00129A578-E105C1D138   1 Centralized Recording

$42.00
L00129A677-213DC6D60E   1 Centralized Recording

$42.00
1005272AE2-C1D6CACEC8   5 Station

$45.00
100525B658-3AC4D2C93A   5 Station

$45.00
</code>```

I would need to grab the license count and license name then add like objects so it would grab (1 Centralized Recording, 1 Centralized Recording, 5 Station, 5 Station) then add license counts and output (2 Centralized Recording, 10 Station)

What would be the easiest way to implement this?

答:
Pandas is a good tool for jobs like this. You might have to play around with it a bit. You will also need to export your excel file as a .csv file. In the interpreter,try:

```<code>import pandas
raw = pandas.read_csv('myfile.csv')
print(raw.columns)
</code>```

That will give you the column headings for the csv file. If you have headers name and nums, then you can extract those as a list of tuples as follows:

```<code>extract = list(zip(raw.name, raw.nums))
</code>```

You can then sort this list by name:

```<code>extract = sorted(extract)
</code>```

Pandas probably has a method for compressing this easily, but I can't recall it so:

```<code>def accum(c):
    nm = c[0][0]
    count = 0
    result = []
    for x in c:
        if x[0] == nm:
            count += x[1]
        else:
            result.append((nm, count))
            nm = x[0]
            count = x[1]
    result.append((nm, count))
    return result

done = accum(extract)
</code>```

Now you can write this to a text file as follows(fstrings require Python 3.6+)

```<code>with open("myjob.txt", "w+") as fout:
      for x in done:
          line = f"name: {x[0]}    count: {x[1]} \n"
          fout.write(line)
</code>```

Body:
I tried to look for a solution but nothing was giving me quite what I needed. I'm not sure regex can do what I need.

I need to process a large amount of data where license information is provided. I just need to grab the number of licenses and the name for each license then group and tally the license counts for each company.

Here's an example of the data pulled:

L00129A578-E105C1D138   1 Centralized Recording

$42.00
L00129A677-213DC6D60E   1 Centralized Recording

$42.00
1005272AE2-C1D6CACEC8   5 Station

$45.00
100525B658-3AC4D2C93A   5 Station

$45.00

I would need to grab the license count and license name then add like objects so it would grab (1 Centralized Recording, 1 Centralized Recording, 5 Station, 5 Station) then add license counts and output (2 Centralized Recording, 10 Station)

What would be the easiest way to implement this?

Body:
Pandas is a good tool for jobs like this. You might have to play around with it a bit. You will also need to export your excel file as a .csv file. In the interpreter,try:

import pandas
raw = pandas.read_csv('myfile.csv')
print(raw.columns)

That will give you the column headings for the csv file. If you have headers name and nums, then you can extract those as a list of tuples as follows:

extract = list(zip(raw.name, raw.nums))

You can then sort this list by name:

extract = sorted(extract)

Pandas probably has a method for compressing this easily, but I can't recall it so:

def accum(c):
    nm = c[0][0]
    count = 0
    result = []
    for x in c:
        if x[0] == nm:
            count += x[1]
        else:
            result.append((nm, count))
            nm = x[0]
            count = x[1]
    result.append((nm, count))
    return result

done = accum(extract)

Now you can write this to a text file as follows(fstrings require Python 3.6+)

with open("myjob.txt", "w+") as fout:
      for x in done:
          line = f"name: {x[0]}    count: {x[1]} \n"
          fout.write(line)


来源: stackexchange

问:
pd.get_dummies() for DataFrames with multi-index columns
Using get_dummies(), it is possible to create one-hot encoded dummy variables for categorical data. For example:

```<code>import pandas as pd
df = pd.DataFrame({'A': ['a', 'b', 'a'],
                   'B': ['b', 'a', 'c']})
print(pd.get_dummies(df))

#    A_a  A_b  B_a  B_b  B_c
# 0    1    0    0    1    0
# 1    0    1    1    0    0
# 2    1    0    0    0    1
</code>```

So far, so good. But how can I use get_dummies() in combination with multi-index columns? The default behavior is not very practical: The multi-index tuple is converted into a string and the same suffix mechanism applies as with the simple-index columns.

```<code>df = pd.DataFrame({('i','A'): ['a', 'b', 'a'],
                   ('ii','B'): ['b', 'a', 'c']})
ret = pd.get_dummies(df)
print(ret)
print(type(ret.columns[0]))

#    ('i','A')_a  ('i','A')_b  ('ii','B')_a  ('ii','B')_b  ('ii','B')_c
# 0            1            0             0             1             0
# 1            0            1             1             0             0
# 2            1            0             0             0             1
#
# str
</code>```

What I would like to get, however, is that the dummies create a new column level:

```<code>ret = pd.get_dummies(df, ???)
print(ret)
print(type(ret.columns[0]))

#    i    ii
#    A     B
#    a  b  a  b  c
# 0  1  0  0  1  0
# 1  0  1  1  0  0
# 2  1  0  0  0  1
#
# tuple
#

# Note that the ret would be equivalent to the following:
#   ('i','A','a') ('i','A','b') ('ii','B','a') ('ii','B','b') ('ii','B','c')
# 0            1             0              0              1              0
# 1            0             1              1              0              0
# 2            1             0              0              0              1
</code>```

How could this be achieved?

Update: I placed a feature request for better support of multi-index data-frames in get_dummies: https://github.com/pandas-dev/pandas/issues/26560

答:
You can parse the column names and rename them:

```<code>import ast
def parse_dummy(x):
    parts = x.split('_')
    return ast.literal_eval(parts[0]) + (parts[1],)

ret.columns = pd.Series(ret.columns).apply(parse_dummy)
#   (i, A, a)  (i, A, b)  (ii, B, a)  (ii, B, b)  (ii, B, c)
#0          1          0           0           1           0
#1          0          1           1           0           0
#2          1          0           0           0           1
</code>```

Note that this DataFrame is not the same as a DataFrame with three-level multiindex column names.

ContentLicense: CC BY-SA 4.0

Body:
Using get_dummies(), it is possible to create one-hot encoded dummy variables for categorical data. For example:

import pandas as pd
df = pd.DataFrame({'A': ['a', 'b', 'a'],
                   'B': ['b', 'a', 'c']})
print(pd.get_dummies(df))

#    A_a  A_b  B_a  B_b  B_c
# 0    1    0    0    1    0
# 1    0    1    1    0    0
# 2    1    0    0    0    1

So far, so good. But how can I use get_dummies() in combination with multi-index columns? The default behavior is not very practical: The multi-index tuple is converted into a string and the same suffix mechanism applies as with the simple-index columns.

df = pd.DataFrame({('i','A'): ['a', 'b', 'a'],
                   ('ii','B'): ['b', 'a', 'c']})
ret = pd.get_dummies(df)
print(ret)
print(type(ret.columns[0]))

#    ('i','A')_a  ('i','A')_b  ('ii','B')_a  ('ii','B')_b  ('ii','B')_c
# 0            1            0             0             1             0
# 1            0            1             1             0             0
# 2            1            0             0             0             1
#
# str

What I would like to get, however, is that the dummies create a new column level:

ret = pd.get_dummies(df, ???)
print(ret)
print(type(ret.columns[0]))

#    i    ii
#    A     B
#    a  b  a  b  c
# 0  1  0  0  1  0
# 1  0  1  1  0  0
# 2  1  0  0  0  1
#
# tuple
#

# Note that the ret would be equivalent to the following:
#   ('i','A','a') ('i','A','b') ('ii','B','a') ('ii','B','b') ('ii','B','c')
# 0            1             0              0              1              0
# 1            0             1              1              0              0
# 2            1             0              0              0              1

How could this be achieved?

Update: I placed a feature request for better support of multi-index data-frames in get_dummies: https://github.com/pandas-dev/pandas/issues/26560

Body:
You can parse the column names and rename them:

import ast
def parse_dummy(x):
    parts = x.split('_')
    return ast.literal_eval(parts[0]) + (parts[1],)

ret.columns = pd.Series(ret.columns).apply(parse_dummy)
#   (i, A, a)  (i, A, b)  (ii, B, a)  (ii, B, b)  (ii, B, c)
#0          1          0           0           1           0
#1          0          1           1           0           0
#2          1          0           0           0           1

Note that this DataFrame is not the same as a DataFrame with three-level multiindex column names.


问:
Count across dataframe columns based on str.contains (or similar)
I would like to count the number of cells within each row that contain a particular character string, cells which have the particular string more than once should be counted once only.

I can count the number of cells across a row which equal a given value, but when I expand this logic to use str.contains, I have issues, as shown below

d = {'col1': ["a#", "b","c#"], 'col2': ["a", "b","c#"]}
df = pd.DataFrame(d)

#can correctly count across rows using equality
thisworks =( df =="a#" ).sum(axis=1)

#can count across  a column using str.contains
thisworks1=df['col1'].str.contains('#').sum()

#but cannot use str.contains with a dataframe so what is the alternative
thisdoesnt =( df.str.contains('#') ).sum(axis=1)
```

Output should be a series showing the number of cells in each row that contain the given character string.

答:
str.contains is a series method. To apply it to whole dataframe you need either agg or apply such as:

```<code>df.agg(lambda x: x.str.contains('#')).sum(1)

Out[2358]:
0    1
1    0
2    2
dtype: int64
</code>```

If you don't like agg nor apply, you may use np.char.find to work directly on underlying numpy array of df

```<code>(np.char.find(df.values.tolist(), '#') + 1).astype(bool).sum(1)

Out[2360]: array([1, 0, 2])
</code>```

Passing it to series or a columns of df

```<code>pd.Series((np.char.find(df.values.tolist(), '#') + 1).astype(bool).sum(1), index=df.index)

Out[2361]:
0    1
1    0
2    2
dtype: int32
</code>```

Body:
I would like to count the number of cells within each row that contain a particular character string, cells which have the particular string more than once should be counted once only.

I can count the number of cells across a row which equal a given value, but when I expand this logic to use str.contains, I have issues, as shown below

d = {'col1': ["a#", "b","c#"], 'col2': ["a", "b","c#"]}
df = pd.DataFrame(d)

#can correctly count across rows using equality
thisworks =( df =="a#" ).sum(axis=1)

#can count across  a column using str.contains
thisworks1=df['col1'].str.contains('#').sum()

#but cannot use str.contains with a dataframe so what is the alternative
thisdoesnt =( df.str.contains('#') ).sum(axis=1)

Output should be a series showing the number of cells in each row that contain the given character string.

Body:
str.contains is a series method. To apply it to whole dataframe you need either agg or apply such as:

df.agg(lambda x: x.str.contains('#')).sum(1)

Out[2358]:
0    1
1    0
2    2
dtype: int64

If you don't like agg nor apply, you may use np.char.find to work directly on underlying numpy array of df

(np.char.find(df.values.tolist(), '#') + 1).astype(bool).sum(1)

Out[2360]: array([1, 0, 2])

Passing it to series or a columns of df

pd.Series((np.char.find(df.values.tolist(), '#') + 1).astype(bool).sum(1), index=df.index)

Out[2361]:
0    1
1    0
2    2
dtype: int32


问:
How can I hover over a image where it uses Gradient
I place some communication icons on my website. One of them is the Instagram icon where I got it from Font Awesome and I gave approximately of the same color as is the logo of Instagram using Gradient. The problem is now that If i want to :hover it not working. I do not know how I can fix it.

footer {
  background-color: black;
  height: 120px;
}

footer a {
  display: flex;
  justify-content: center;
  font-size: 70px;
  padding: 20px;
  text-decoration: none !important;
}

.fa-instagram {
  background: #f09433;
  background: -moz-linear-gradient(45deg, #f09433 0%, #e6683c 25%, #dc2743 50%, #cc2366 75%, #bc1888 100%);
  background: -webkit-linear-gradient(45deg, #f09433 0%, #e6683c 25%, #dc2743 50%, #cc2366 75%, #bc1888 100%);
  background: linear-gradient(45deg, #f09433 0%, #e6683c 25%, #dc2743 50%, #cc2366 75%, #bc1888 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.fa-instagram:hover {
  color: hsla(181, 6%, 67%, 0.5);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>

<html>

<head>
  <link rel="stylesheet" type="text/css" href="main.css">

  <title>Website Title</title>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.4.1/css/all.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>

</head>

<body>
  <footer>

      <i class="fab fa-instagram"></i>

  </footer>
</body>

</html></code>```

答:
You have to change the background, not the color. Pay attention to change only the background-image to not override the background-clip property:

footer {
  background-color: black;
  height: 120px;
}

footer a {
  display: flex;
  justify-content: center;
  font-size: 70px;
  padding: 20px;
  text-decoration: none !important;
}

.fa-instagram {
  background-image: linear-gradient(45deg, #f09433 0%, #e6683c 25%, #dc2743 50%, #cc2366 75%, #bc1888 100%);
  -webkit-background-clip: text;
  background-clip: text;
  -webkit-text-fill-color: transparent;
}

.fa-instagram:hover {
  background-image: linear-gradient(hsla(181, 6%, 67%, 0.5), hsla(181, 6%, 67%, 0.5));
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.4.1/css/all.css">
<footer>

    <i class="fab fa-instagram"></i>

</footer></code>```

Body:
I place some communication icons on my website. One of them is the Instagram icon where I got it from Font Awesome and I gave approximately of the same color as is the logo of Instagram using Gradient. The problem is now that If i want to :hover it not working. I do not know how I can fix it.

footer {
  background-color: black;
  height: 120px;
}

footer a {
  display: flex;
  justify-content: center;
  font-size: 70px;
  padding: 20px;
  text-decoration: none !important;
}

.fa-instagram {
  background: #f09433;
  background: -moz-linear-gradient(45deg, #f09433 0%, #e6683c 25%, #dc2743 50%, #cc2366 75%, #bc1888 100%);
  background: -webkit-linear-gradient(45deg, #f09433 0%, #e6683c 25%, #dc2743 50%, #cc2366 75%, #bc1888 100%);
  background: linear-gradient(45deg, #f09433 0%, #e6683c 25%, #dc2743 50%, #cc2366 75%, #bc1888 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.fa-instagram:hover {
  color: hsla(181, 6%, 67%, 0.5);
}

<!DOCTYPE html>

  <link rel="stylesheet" type="text/css" href="main.css">

  <title>Website Title</title>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.4.1/css/all.css">

Body:
You have to change the background, not the color. Pay attention to change only the background-image to not override the background-clip property:

footer {
  background-color: black;
  height: 120px;
}

footer a {
  display: flex;
  justify-content: center;
  font-size: 70px;
  padding: 20px;
  text-decoration: none !important;
}

.fa-instagram {
  background-image: linear-gradient(45deg, #f09433 0%, #e6683c 25%, #dc2743 50%, #cc2366 75%, #bc1888 100%);
  -webkit-background-clip: text;
  background-clip: text;
  -webkit-text-fill-color: transparent;
}

.fa-instagram:hover {
  background-image: linear-gradient(hsla(181, 6%, 67%, 0.5), hsla(181, 6%, 67%, 0.5));
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.4.1/css/all.css">
<footer>
  <a href="#" target="_blank">
    <i class="fab fa-instagram"></i>
  </a>
</footer>


问:
Store Image into bitmap in vb.net
I have this problem where I want to store an image into bitmap using Open File Dialog in vb.net. How to achieve this?

I have this code:

```<code>Dim image1 As Bitmap
Private Sub add_image_LinkClicked(ByVal sender As System.Object, ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles add_image.LinkClicked

    With OpenFileDialog1
        .Filter = ("Images | *.png; *.bmp; *.jpg;")
        .FilterIndex = 2
    End With
    OpenFileDialog1.FileName = "Select Image"
    If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
       image1 = OpenFileDialog1.FileName
    End If
End Sub
</code>```

I receive an error in image1 = OpenFileDialog1.FileName, I know this is wrong. Is there a way to store the selected image in OpenFileDialog1 to image1?

答:
Try this:</p>

```<code>image1 = Image.FromFile(OpenFileDialog1.FileName)
</code>```

Title: Store Image into bitmap in vb.net

Body:
I have this problem where I want to store an image into bitmap using Open File Dialog in vb.net. How to achieve this?

I have this code:

Dim image1 As Bitmap
Private Sub add_image_LinkClicked(ByVal sender As System.Object, ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles add_image.LinkClicked

    With OpenFileDialog1
        .Filter = ("Images | *.png; *.bmp; *.jpg;")
        .FilterIndex = 2
    End With
    OpenFileDialog1.FileName = "Select Image"
    If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
       image1 = OpenFileDialog1.FileName
    End If
End Sub

I receive an error in image1 = OpenFileDialog1.FileName, I know this is wrong. Is there a way to store the selected image in OpenFileDialog1 to image1?

Body:
Try this:

image1 = Image.FromFile(OpenFileDialog1.FileName)


问:
Java TCP client/server sockets
I am working on a problem that will create a TCP server and client using sockets.  For the client code, my objective is to repeatedly prompt the user to enter a sentence S, send the sentence S to the server, receive the response from the server, and display the message received and the round trip time expressed in milliseconds.  On the server, my objective is to create a TCP server socket, wait for a client to connect, receive a message, display it with the IP address and port # of the client, capitalize the message, display the message, and echo back the "capitalized" message.

I am trying to use a while (!(input.equals("done"){ ...do something }, however, whatever I do is getting stuck in an infinite loop.  I hope its something simple I am just overlooking, but I don't see it.

TCPServer.java

```<code>import java.net.*;
import java.io.*;

public class myFirstTCPServer {
    public static void main(String[] args) throws IOException {

        int servPort = 4999;
        ServerSocket Sy = new ServerSocket(servPort);
        Socket servSocket = Sy.accept();

        InputStreamReader in = new InputStreamReader(servSocket.getInputStream());
        BufferedReader bf = new BufferedReader(in);
        String str = bf.readLine();

        while (!(str.equals("done"))){

            System.out.println("client connected");

            InetAddress address = InetAddress.getLocalHost();
            String ip = address.getHostAddress();
            System.out.println("IP: " + ip);
            System.out.println("Port: " + servPort);

            System.out.println("Message from client: " + str.toUpperCase());

            PrintWriter pr = new PrintWriter(servSocket.getOutputStream());
            pr.println(str);
            pr.flush();
        }
        servSocket.close();
    }
}
</code>```

TCPClient.java

```<code>import java.net.*;
import java.io.*;
import java.util.Scanner;

public class myFirstTCPClient {
    public static void main(String[] args) throws IOException {
        String S;
        Scanner input = new Scanner(System.in);
        System.out.println("Enter a sentence");
        S = input.nextLine();
        Socket clntSocket = new Socket(InetAddress.getLocalHost(), 4999);

        while (!(S.equals("done"))){
            double sent = System.nanoTime();
            PrintWriter pr = new PrintWriter(clntSocket.getOutputStream());
            pr.println(S);
            pr.flush();

            InputStreamReader in = new InputStreamReader(clntSocket.getInputStream());
            BufferedReader bf = new BufferedReader(in);

            String str = bf.readLine();
            System.out.println("Message from server: " + str);
            double received = System.nanoTime();
            double total = received - sent;
            System.out.println("Round Trip Time: " + (total/1000000.0));
        }
        clntSocket.close();
    }
}
</code>```

答:
you need to move reader into the while loop. Because this is where server waits for reading clients input.

```<code>    public class myFirstTCPServer {
    public static void main(String[] args) throws IOException {

        int servPort = 4999;
        ServerSocket Sy = new ServerSocket(servPort);
        Socket servSocket = Sy.accept();
        System.out.println("client connected");

        InputStreamReader in = new InputStreamReader(servSocket.getInputStream());
        BufferedReader bf = new BufferedReader(in);

        String str ="";
        while (true)){

            str = bf.readLine();

            if(str.equals("done")) break;

            InetAddress address = servSocket.getInetAddress();
            String ip = address.getHostAddress();
            System.out.println("IP: " + ip);
            System.out.println("Port: " + servPort);

            System.out.println("Message from client: " + str);

            PrintWriter pr = new PrintWriter(servSocket.getOutputStream());
            pr.println(str.toUpperCase());
            pr.flush();
        }
        servSocket.close();
    }
    }
</code>```

And then change client side:

```<code>public class myFirstTCPClient {
    public static void main(String[] args) throws IOException {
        String S="";
        Scanner input = new Scanner(System.in);

        // you need to provide your server ip/domain
        // InetAddress.getLocalHost() , still works but only works when
        // your client is in the same machine.
        Socket clntSocket = new Socket("127.0.0.1", 4999);

        while (!(S.equals("done"))){
            System.out.println("Enter a sentence");
            S = input.nextLine();
            double sent = System.nanoTime();
            PrintWriter pr = new PrintWriter(clntSocket.getOutputStream());
            pr.println(S);
            pr.flush();

            InputStreamReader in = new InputStreamReader(clntSocket.getInputStream());
            BufferedReader bf = new BufferedReader(in);

            String str = bf.readLine();
            System.out.println("Message from server: " + str);
            double received = System.nanoTime();
            double total = received - sent;
            System.out.println("Round Trip Time: " + (total/1000000.0));
        }
        clntSocket.close();
    }
}
</code>```

Title: Java TCP client/server sockets

Body:
I am working on a problem that will create a TCP server and client using sockets.  For the client code, my objective is to repeatedly prompt the user to enter a sentence S, send the sentence S to the server, receive the response from the server, and display the message received and the round trip time expressed in milliseconds.  On the server, my objective is to create a TCP server socket, wait for a client to connect, receive a message, display it with the IP address and port # of the client, capitalize the message, display the message, and echo back the "capitalized" message.

I am trying to use a while (!(input.equals("done"){ ...do something }, however, whatever I do is getting stuck in an infinite loop.  I hope its something simple I am just overlooking, but I don't see it.

TCPServer.java

import java.net.*;
import java.io.*;

public class myFirstTCPServer {
    public static void main(String[] args) throws IOException {

        int servPort = 4999;
        ServerSocket Sy = new ServerSocket(servPort);
        Socket servSocket = Sy.accept();

        InputStreamReader in = new InputStreamReader(servSocket.getInputStream());
        BufferedReader bf = new BufferedReader(in);
        String str = bf.readLine();

        while (!(str.equals("done"))){

            System.out.println("client connected");

            InetAddress address = InetAddress.getLocalHost();
            String ip = address.getHostAddress();
            System.out.println("IP: " + ip);
            System.out.println("Port: " + servPort);

            System.out.println("Message from client: " + str.toUpperCase());

            PrintWriter pr = new PrintWriter(servSocket.getOutputStream());
            pr.println(str);
            pr.flush();
        }
        servSocket.close();
    }
}

TCPClient.java

import java.net.*;
import java.io.*;
import java.util.Scanner;

public class myFirstTCPClient {
    public static void main(String[] args) throws IOException {
        String S;
        Scanner input = new Scanner(System.in);
        System.out.println("Enter a sentence");
        S = input.nextLine();
        Socket clntSocket = new Socket(InetAddress.getLocalHost(), 4999);

        while (!(S.equals("done"))){
            double sent = System.nanoTime();
            PrintWriter pr = new PrintWriter(clntSocket.getOutputStream());
            pr.println(S);
            pr.flush();

            InputStreamReader in = new InputStreamReader(clntSocket.getInputStream());
            BufferedReader bf = new BufferedReader(in);

            String str = bf.readLine();
            System.out.println("Message from server: " + str);
            double received = System.nanoTime();
            double total = received - sent;
            System.out.println("Round Trip Time: " + (total/1000000.0));
        }
        clntSocket.close();
    }
}

Body:
you need to move reader into the while loop. Because this is where server waits for reading clients input.

    public class myFirstTCPServer {
    public static void main(String[] args) throws IOException {

        int servPort = 4999;
        ServerSocket Sy = new ServerSocket(servPort);
        Socket servSocket = Sy.accept();
        System.out.println("client connected");

        InputStreamReader in = new InputStreamReader(servSocket.getInputStream());
        BufferedReader bf = new BufferedReader(in);

        String str ="";
        while (true)){

            str = bf.readLine();

            if(str.equals("done")) break;

            InetAddress address = servSocket.getInetAddress();
            String ip = address.getHostAddress();
            System.out.println("IP: " + ip);
            System.out.println("Port: " + servPort);

            System.out.println("Message from client: " + str);

            PrintWriter pr = new PrintWriter(servSocket.getOutputStream());
            pr.println(str.toUpperCase());
            pr.flush();
        }
        servSocket.close();
    }
    }

And then change client side:

public class myFirstTCPClient {
    public static void main(String[] args) throws IOException {
        String S="";
        Scanner input = new Scanner(System.in);

        // you need to provide your server ip/domain
        // InetAddress.getLocalHost() , still works but only works when
        // your client is in the same machine.
        Socket clntSocket = new Socket("127.0.0.1", 4999);

        while (!(S.equals("done"))){
            System.out.println("Enter a sentence");
            S = input.nextLine();
            double sent = System.nanoTime();
            PrintWriter pr = new PrintWriter(clntSocket.getOutputStream());
            pr.println(S);
            pr.flush();

            InputStreamReader in = new InputStreamReader(clntSocket.getInputStream());
            BufferedReader bf = new BufferedReader(in);

            String str = bf.readLine();
            System.out.println("Message from server: " + str);
            double received = System.nanoTime();
            double total = received - sent;
            System.out.println("Round Trip Time: " + (total/1000000.0));
        }
        clntSocket.close();
    }
}


问:
Soap server return string
When i sending request by __doRequest (xml) method on return from soap server i get string

```<code>string(490) "
0Message0000
"
</code>```

when i pass array by __soapCall i get exactly that i want, xml object

```<code>object(stdClass)#2 (2) {
  ["Headers"]=>
  object(stdClass)#3 (2) {
    ["Code"]=>
    int(0)
    ["Message"]=>
    string(7) "Message"
  }
  ["Item"]=>
  object(stdClass)#4 (9) {
    ["LocalID"]=>
    int(991)
    ["ItemID"]=>
    int(0)
    ["SItemID"]=>
    int(0)
    ["UOM"]=>
    string(3) "UOM"
    ["ItemName"]=>
    string(8) "ItemName"
    ["ItemDescription"]=>
    string(15) "ItemDescription"
    ["Local"]=>
    string(5) "Local"
    ["Synonyms"]=>
    object(stdClass)#5 (1) {
      ["Synonym"]=>
      object(stdClass)#6 (2) {
        ["SynonymValue"]=>
        string(12) "SynonymValue"
        ["Contractor"]=>
        int(0)
      }
    }
    ["Properites"]=>
    object(stdClass)#7 (1) {
      ["Property"]=>
      object(stdClass)#8 (2) {
        ["PropertyKey"]=>
        string(11) "PropertyKey"
        ["PropertyValue"]=>
        string(13) "PropertyValue"
      }
    }
  }
}
</code>```

My server method for this request:

```<code>public function GetItemData($parametersIn) {
    srand((double) microtime() * 1234567);
    $xml = 'XML'; // my response in xml
    $parametersOut = simplexml_load_string($xml);
    return $parametersOut;
}
</code>```

Why when i using __doRequest i get this strange string ? how i can convert it to array or object?

答: You are looking at the output in a browser which "hides" the XML tags. Use "view source" on the page to see what's really there.</p>

ContentLicense: CC BY-SA 2.5

Title: Soap server return string

Body:
When i sending request by __doRequest (xml) method on return from soap server i get string

string(490) "
0Message0000
"

when i pass array by __soapCall i get exactly that i want, xml object

object(stdClass)#2 (2) {
  ["Headers"]=>
  object(stdClass)#3 (2) {
    ["Code"]=>
    int(0)
    ["Message"]=>
    string(7) "Message"
  }
  ["Item"]=>
  object(stdClass)#4 (9) {
    ["LocalID"]=>
    int(991)
    ["ItemID"]=>
    int(0)
    ["SItemID"]=>
    int(0)
    ["UOM"]=>
    string(3) "UOM"
    ["ItemName"]=>
    string(8) "ItemName"
    ["ItemDescription"]=>
    string(15) "ItemDescription"
    ["Local"]=>
    string(5) "Local"
    ["Synonyms"]=>
    object(stdClass)#5 (1) {
      ["Synonym"]=>
      object(stdClass)#6 (2) {
        ["SynonymValue"]=>
        string(12) "SynonymValue"
        ["Contractor"]=>
        int(0)
      }
    }
    ["Properites"]=>
    object(stdClass)#7 (1) {
      ["Property"]=>
      object(stdClass)#8 (2) {
        ["PropertyKey"]=>
        string(11) "PropertyKey"
        ["PropertyValue"]=>
        string(13) "PropertyValue"
      }
    }
  }
}

My server method for this request:

public function GetItemData($parametersIn) {
    srand((double) microtime() * 1234567);
    $xml = 'XML'; // my response in xml
    $parametersOut = simplexml_load_string($xml);
    return $parametersOut;
}

Why when i using __doRequest i get this strange string ? how i can convert it to array or object?

ContentLicense: CC BY-SA 3.0


问:
Making new dataframes from old dataframes by column number
I'm trying to re-organize my dataframes by Column orders

for Example

```<code>x <- data.frame("A" = c(1,1), "B" = c(2,2), "C" = c(3,3))
y <- data.frame("A" = c(2,2), "B" = c(3,3), "C" = c(4,4))
z <- data.frame("A" = c(3,3), "B" = c(4,4), "C" = c(5,5))
</code>```

Say I have dataframes as above.
What I want to do is make new dataframes by column orders of those above dataframes. (Simply put, I want to put all the "A"s ,"B"s and "C"s, to 3 new dataframes.

the below dataframes are my wanted results

```<code>a <-  data.frame("A" = c(1,1), "A" = c(2,2), "A" = c(3,3))
b <- data.frame("B" = c(2,2), "B" = c(3,3), "B" = c(4,4))
c <- data.frame("C" = c(3,3), "C" = c(4,4), "C" = c(5,5))
</code>```

答:
Assuming you have equal number of columns in all the dataframes, one way is to use lapply over list of dataframes and subset them sequentially.

```<code>lst1 <- list(x, y, z)
lapply(seq_len(ncol(x)), function(i) cbind.data.frame(lapply(lst1, `[`, i)))

#[[1]]
#  A A A
#1 1 2 3
#2 1 2 3

#[[2]]
#  B B B
#1 2 3 4
#2 2 3 4

#[[3]]
#  C C C
#1 3 4 5
#2 3 4 5
</code>```

If your dataframes are not already sorted by names you might want to do that first.

```<code>lst1 <- lapply(list(x, y, z), function(i) i[order(names(i))])
</code>```

We can also use purrr using the same logic

```<code>library(purrr)
map(seq_len(ncol(x)), ~cbind.data.frame(map(lst1, `[`, .)))
</code>```

Body:
I'm trying to re-organize my dataframes by Column orders

for Example

x <- data.frame("A" = c(1,1), "B" = c(2,2), "C" = c(3,3))
y <- data.frame("A" = c(2,2), "B" = c(3,3), "C" = c(4,4))
z <- data.frame("A" = c(3,3), "B" = c(4,4), "C" = c(5,5))

Say I have dataframes as above.
What I want to do is make new dataframes by column orders of those above dataframes. (Simply put, I want to put all the "A"s ,"B"s and "C"s, to 3 new dataframes.

the below dataframes are my wanted results

a <-  data.frame("A" = c(1,1), "A" = c(2,2), "A" = c(3,3))
b <- data.frame("B" = c(2,2), "B" = c(3,3), "B" = c(4,4))
c <- data.frame("C" = c(3,3), "C" = c(4,4), "C" = c(5,5))

Body:
Assuming you have equal number of columns in all the dataframes, one way is to use lapply over list of dataframes and subset them sequentially.

lst1 <- list(x, y, z)
lapply(seq_len(ncol(x)), function(i) cbind.data.frame(lapply(lst1, `[`, i)))

#[[1]]
#  A A A
#1 1 2 3
#2 1 2 3

#[[2]]
#  B B B
#1 2 3 4
#2 2 3 4

#[[3]]
#  C C C
#1 3 4 5
#2 3 4 5

If your dataframes are not already sorted by names you might want to do that first.

lst1 <- lapply(list(x, y, z), function(i) i[order(names(i))])

We can also use purrr using the same logic

library(purrr)
map(seq_len(ncol(x)), ~cbind.data.frame(map(lst1, `[`, .)))


问:
python code for creating class object from dataframe rows
I have one data frame with row entries and column names. I also have a class defined with attributes (class attribute names are different from dataframe columns).

Now the requirement is to create objects of that class per record from the dataframe and the final list of objects should be output

Class A:

```<code>AA, AB, AC....etc
</code>```

dataframe:

```<code>A B c ...
1 2 3 ...
1 2 3 ...
</code>```

How to avoid column names and start creating objects?

I have tried using this code:

```<code>Aobjs = [A(**kwargs) for kwargs in dataframe.to_dict(orient='records')]
</code>```

答:
Will something like this work for you?:

df = pd.DataFrame({'one': [1, 2, 3], 'two': [ 6, 5, 4]})
df
#    one  two
# 0    1    6
# 1    2    5
# 2    3    4

class Silly:
    def __init__(self, first, second):
        self.first = first
        self.second = second

A = [Silly(a.one, a.two) for a in df.itertuples()]
# [<__main__.Silly object at 0x7f97b26fe7f0>, <__main__.Silly object at 0x7f97b26fe978>, <__main__.Silly object at 0x7f97b26fe4a8>]
```

My guess is that your index is not a valid kwarg.

Body:
I have one data frame with row entries and column names. I also have a class defined with attributes (class attribute names are different from dataframe columns).

Now the requirement is to create objects of that class per record from the dataframe and the final list of objects should be output

Class A:

AA, AB, AC....etc

dataframe:

A B c ...
1 2 3 ...
1 2 3 ...

How to avoid column names and start creating objects?

I have tried using this code:

Aobjs = [A(**kwargs) for kwargs in dataframe.to_dict(orient='records')]

Body:
Will something like this work for you?:

df = pd.DataFrame({'one': [1, 2, 3], 'two': [ 6, 5, 4]})
df
#    one  two
# 0    1    6
# 1    2    5
# 2    3    4

class Silly:
    def __init__(self, first, second):
        self.first = first
        self.second = second

A = [Silly(a.one, a.two) for a in df.itertuples()]
# [<__main__.Silly object at 0x7f97b26fe7f0>, <__main__.Silly object at 0x7f97b26fe978>, <__main__.Silly object at 0x7f97b26fe4a8>]

My guess is that your index is not a valid kwarg.


问:
How do I upload a file to a REST endpoint?
Using Twitter as an example: Twitter has an endpoint for uploading file data. https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload-append

Can anyone provide an example of a real HTTP message containing, for example, image file data, showing how it is supposed to be structured? I'm fairly sure Twitter's documentation is nonsense, as their "example request" is the following:

POST https://upload.twitter.com/1.1/media/upload.json?command=APPEND&media_id=123&segment_index=2&media_data=123

Is the media_data really supposed to go in the URL? What if you have raw binary media data? Would it go in the body? How is the REST service to know how the data is encoded?

答:
You're looking at the chunked uploader - it's intended for sending large files, breaking them into chunks, so a network failure doesn't mean you have to re-upload a 100 MB .mp4. It is, as a result, fairly complicated. (Side note: The file data goes in the request body, not the URL as a GET parameter... as indicated by "Requests should be multipart/form-data POST format.")

There's a far less complicated unchunked uploader that'll be easier to work with if you're just uploading a regular old image.

All of this gets a lot easier if you use one of Twitter's recommended libraries for your language.


问:
Waiting for API call before proceeding to display component
I am using axios to make an API call. The call occurs when the mouse enters certain HTML elements on the page. Usually, on the first hover none of the data is received, but on the second one the data usually appears. I figure that this is because I am not waiting for the API call to return. Is there a way to implement this?

Below is the Axios instance that I use to make the API call.

Thank you for the time and consideration.

```<code>instance
.get('observations?patientId=37')
.then((response) => {
   this.clinicaltabs[0].title = response.data.data;
});
</code>```

答:
What I'd do:

Use a spinner loading for you hoverable HTML element and make it visible when sending your request.

```<code>this.loading = true; //Some way for disabling the hover event

instance
.get('observations?patientId=37')
.then((response) => {
   this.clinicaltabs[0].title = response.data.data;
})
.finally(() => this.loading = false);
</code>```

Then you could use the v-if="loading" or something like to control the display of the component until it loads.

Body:
I am using axios to make an API call. The call occurs when the mouse enters certain HTML elements on the page. Usually, on the first hover none of the data is received, but on the second one the data usually appears. I figure that this is because I am not waiting for the API call to return. Is there a way to implement this?

Below is the Axios instance that I use to make the API call.

Thank you for the time and consideration.

instance
.get('observations?patientId=37')
.then((response) => {
   this.clinicaltabs[0].title = response.data.data;
});

Body:
What I'd do:

Use a spinner loading for you hoverable HTML element and make it visible when sending your request.

this.loading = true; //Some way for disabling the hover event

instance
.get('observations?patientId=37')
.then((response) => {
   this.clinicaltabs[0].title = response.data.data;
})
.finally(() => this.loading = false);

Then you could use the v-if="loading" or something like to control the display of the component until it loads.


问:
MySQL connector error "The server time zone value Central European Time"
My problem

MySQL connector "The server time zone value Central European Time" is unrecognized or represents more than one time zone.

The project

Small web Project with:
JavaEE, Tomcat 8.5, MySQL, Maven

My attempt

Maven -> change MySQL-connector form 6.x to 5.1.39 (no change)

Edit context.xml URL change

Connection in context.xml

URL="jdbc: mysql://127.0.0.1:3306/rk_tu_lager?useLegacyDatetimeCode=false;serverTimezone=CEST;useSSL=false;

Error:

Caused by:
  com.mysql.cj.core.exceptions.InvalidConnectionAttributeException:  The
  server time zone value 'Mitteleurop?ische Sommerzeit' is unrecognized
  or  represents more than one time zone. You must configure either the
  server or JDBC driver (via the serverTimezone configuration property)
  to use a more specifc time zone value if you want to utilize time zone
  support.

答:
Find what is the timezone you are in and replace +00:00 with your timezone.

SET @@global.time_zone = '+00:00';
SET @@session.time_zone = '+00:00';
```
<p>Then check if the values were set:</p>
<pre class="lang-sql prettyprint-override"><code>SELECT @@global.time_zone, @@session.time_zone;
</code>```

Body:
Find what is the timezone you are in and replace +00:00 with your timezone.

SET @@global.time_zone = '+00:00';
SET @@session.time_zone = '+00:00';

Then check if the values were set:

SELECT @@global.time_zone, @@session.time_zone;


问:
Nhibernate(Fluent) SchemaExport and SQlite Problem!
I am using Nhibernate(Fluent) with Sqlite and it worked with no problems what I have done:

Create the POCO EntityClasses for each table like this:

```<code>public class tbl_Manufactor : BusinessObject<tbl_Manufactor>
{
    public virtual string Name { get; set; }
}
</code>```

The Entity Classes all inherit from BusinessObject which contains the ID Property and simple CRUD functions
I have also other 6 Entity Classes

Create the Mappings with FluentHibernate like this:

```<code>using Database.Entitites;
using FluentNHibernate.Mapping;

namespace Database.Mappings
{
    public class tbl_ManufactorMap : ClassMap<tbl_Manufactor>
    {
        public tbl_ManufactorMap()
        {
            Id(x => x.ID);
            Map(x => x.Name);
        }
    }
}
</code>```

Create the Fluent Config like this:

```<code> var Config = Fluently.Configure()
            .Database(SQLiteConfiguration.Standard
                .ConnectionString(c=>c.FromConnectionStringWithKey("dbconnection"))
                .ShowSql())
            .Mappings(m =>
                m.FluentMappings.AddFromAssemblyOf<tbl_Manufactor>())
            .ExposeConfiguration(cfg =>  _configuration = cfg)

            sessionFactory = Config.BuildSessionFactory();
</code>```

Do a SchemaExport to Create the Schema with:

```<code>new SchemaExport(_configuration)
                .Create(false, true);
</code>```

Then Nhibernate created a fully working SQlite Database with the right tables!

But then I wanted to add 2 entity classes(I have done it in the same way as before) but when I run my test(which created my first database schema) it not add the new classes(tables) to the database!

The craziest thing is, that the test is always deleting any created database and recreate it with SchemaExport every time I run the test.

Could someone help me?

答:
You could check the following :
 - Are the new entity classes in the same assembly ?
 - Check also for a loop in the model.</p>

Body:
I am using Nhibernate(Fluent) with Sqlite and it worked with no problems what I have done:

Create the POCO EntityClasses for each table like this:

public class tbl_Manufactor : BusinessObject<tbl_Manufactor>
{
    public virtual string Name { get; set; }
}

The Entity Classes all inherit from BusinessObject which contains the ID Property and simple CRUD functions
I have also other 6 Entity Classes

Create the Mappings with FluentHibernate like this:

using Database.Entitites;
using FluentNHibernate.Mapping;

namespace Database.Mappings
{
    public class tbl_ManufactorMap : ClassMap<tbl_Manufactor>
    {
        public tbl_ManufactorMap()
        {
            Id(x => x.ID);
            Map(x => x.Name);
        }
    }
}

Create the Fluent Config like this:

 var Config = Fluently.Configure()
            .Database(SQLiteConfiguration.Standard
                .ConnectionString(c=>c.FromConnectionStringWithKey("dbconnection"))
                .ShowSql())
            .Mappings(m =>
                m.FluentMappings.AddFromAssemblyOf<tbl_Manufactor>())
            .ExposeConfiguration(cfg =>  _configuration = cfg)

            sessionFactory = Config.BuildSessionFactory();

Do a SchemaExport to Create the Schema with:

new SchemaExport(_configuration)
                .Create(false, true);

Then Nhibernate created a fully working SQlite Database with the right tables!

But then I wanted to add 2 entity classes(I have done it in the same way as before) but when I run my test(which created my first database schema) it not add the new classes(tables) to the database!

The craziest thing is, that the test is always deleting any created database and recreate it with SchemaExport every time I run the test.

Could someone help me?


问:
React Native SectionList Rendering Incorreclty
I'm attempting to bind an array of objects to a SelectionList, it appears to be binding but its rendering each character as an individual list item rather than a single item.

Here is my code:

r: GetRecipesResponse is a list of objects that I am then converting to an array, this is visible to the left of the above, the rendering issue is apparent on the right.

```<code>interface States {
    response: GetRecipesResponse;
    globalItems: any[];
    isModalVisible: boolean;
    selectedItem: any;
    selectedItemUnit: any;
}

export class MatrixScreen extends BaseNetworkScreen<GetRecipesResponse, Props, States> {

    itemWidth: number = 100;
    itemMargin: number = 3;
    selectedItemsArray: any[];

    constructor(props: Props) {
        super(props);

        this.selectedItemsArray = [];

        this.state = {
            isLoading: false,
            response: null,
            globalItems: this.selectedItemsArray,
            isModalVisible: false,
            selectedItem: null,
            selectedItemUnit: null
        };
    }
}

renderSelectLists(r: GetRecipesResponse): any {

    var arr = [];
    for (var key in r.data.recipe) {
      arr.push(r.data.recipe[key].name);
    }

    let sections = []
    for (const key in this.state.globalItems) {
        if (this.state.globalItems.hasOwnProperty(key)) {
            sections.push({
                data: this.state.globalItems[key],
                key: key,
                unit: this.state.selectedItemUnit
            })
        }
    }

    return (
        <View style={{ flex: 1, flexDirection: 'row' }}>
            <View style={styles.addContainer}>

                <Text>Press To Add Item</Text>

                <SectionList

                    sections={[{ data: arr }]}
                    renderItem={({ item }) => <Text style={styles.SectionListItemS} onPress={this.loadMatrixModal.bind(this, item)}> {item} </Text>}
                    keyExtractor={(item, index: any) => index}
                />
            </View>
            <View style={styles.removeContainer}>
                <Text>Press To Remove Item</Text>
                <SectionList
                    sections={sections}
                    renderItem={({ item, index }) => <Text style={styles.SectionListItemS} onPress={this.removeSectionListItem.bind(this, index)}> {item} </Text>}
                    keyExtractor={(item, index: any) => item}
                />
            </View>
        </View>
    );
}
</code>```

Logging out "sections" to the console after it's been defined returns the following:

Update:

If I add renderItem={({ item, index }) => <Text style={styles.SectionListItemS} onPress={this.removeSectionListItem.bind(this, index)}> {console.log(item)} {item} </Text>}

Interestingly it outputs the following to the console,

答:
You're not rendering the property you want.

What you need is to access the data property of each item.

So you need to change:

```<code>renderItem={({ item }) => <Text style={styles.SectionListItemS} onPress={this.loadMatrixModal.bind(this, item)}> {item} </Text>}
</code>```

To this:

```<code>renderItem={({ item }) => <Text style={styles.SectionListItemS} onPress={this.loadMatrixModal.bind(this, item)}> {item.data} </Text>}
</code>```

Notice how I changed { item } to { item.data }, that's because item holds the entire item object and you want to render the data property.

Body:
I'm attempting to bind an array of objects to a SelectionList, it appears to be binding but its rendering each character as an individual list item rather than a single item.

Here is my code:

r: GetRecipesResponse is a list of objects that I am then converting to an array, this is visible to the left of the above, the rendering issue is apparent on the right.

interface States {
    response: GetRecipesResponse;
    globalItems: any[];
    isModalVisible: boolean;
    selectedItem: any;
    selectedItemUnit: any;
}

export class MatrixScreen extends BaseNetworkScreen<GetRecipesResponse, Props, States> {

    itemWidth: number = 100;
    itemMargin: number = 3;
    selectedItemsArray: any[];

    constructor(props: Props) {
        super(props);

        this.selectedItemsArray = [];

        this.state = {
            isLoading: false,
            response: null,
            globalItems: this.selectedItemsArray,
            isModalVisible: false,
            selectedItem: null,
            selectedItemUnit: null
        };
    }
}

renderSelectLists(r: GetRecipesResponse): any {

    var arr = [];
    for (var key in r.data.recipe) {
      arr.push(r.data.recipe[key].name);
    }

    let sections = []
    for (const key in this.state.globalItems) {
        if (this.state.globalItems.hasOwnProperty(key)) {
            sections.push({
                data: this.state.globalItems[key],
                key: key,
                unit: this.state.selectedItemUnit
            })
        }
    }

    return (
        <View style={{ flex: 1, flexDirection: 'row' }}>
            <View style={styles.addContainer}>

                <Text>Press To Add Item</Text>

                <SectionList

                    sections={[{ data: arr }]}
                    renderItem={({ item }) => <Text style={styles.SectionListItemS} onPress={this.loadMatrixModal.bind(this, item)}> {item} </Text>}
                    keyExtractor={(item, index: any) => index}
                />
            </View>
            <View style={styles.removeContainer}>
                <Text>Press To Remove Item</Text>
                <SectionList
                    sections={sections}
                    renderItem={({ item, index }) => <Text style={styles.SectionListItemS} onPress={this.removeSectionListItem.bind(this, index)}> {item} </Text>}
                    keyExtractor={(item, index: any) => item}
                />
            </View>
        </View>
    );
}

Logging out "sections" to the console after it's been defined returns the following:

Update:

If I add renderItem={({ item, index }) => <Text style={styles.SectionListItemS} onPress={this.removeSectionListItem.bind(this, index)}> {console.log(item)} {item} </Text>}

Interestingly it outputs the following to the console,

Body:
You're not rendering the property you want.

What you need is to access the data property of each item.

So you need to change:

renderItem={({ item }) => <Text style={styles.SectionListItemS} onPress={this.loadMatrixModal.bind(this, item)}> {item} </Text>}

To this:

renderItem={({ item }) => <Text style={styles.SectionListItemS} onPress={this.loadMatrixModal.bind(this, item)}> {item.data} </Text>}

Notice how I changed { item } to { item.data }, that's because item holds the entire item object and you want to render the data property.


问:
How to print a fixed length memory area which contains multiple \0?
I have a memory area with fixed length.

```<code>char *p = malloc(100);
memset(p, 0 ,100);
</code>```

I have some strings in this memory area, along with some \0, for example

```<code>memcpy(p, "asdf", 4);
memcpy(p + 10, "ghi", 3);
memcpy(p + 20, "1234", 3);
</code>```

So, there are \0 between asdf and ghi

I want to print this memory are and the output is

```<code>asdfghi1234
</code>```

How can I do that? Note that above code is just an example, where are these \0 is not fixed.

答:
Assuming you know the size of the block of memory (hard coded to 100 here):

```<code>for (int i = 0; i < 100; i++)
{
    char c = p[i];
    if (c != 0)
        printf("%c", c);
}
</code>```

Minor nit but in your sample above, the string will be "asdfghi123", because the memcpy for "1234" is only copying 3 bytes.

Body:
I have a memory area with fixed length.

char *p = malloc(100);
memset(p, 0 ,100);

I have some strings in this memory area, along with some \0, for example

memcpy(p, "asdf", 4);
memcpy(p + 10, "ghi", 3);
memcpy(p + 20, "1234", 3);

So, there are \0 between asdf and ghi

I want to print this memory are and the output is

asdfghi1234

How can I do that? Note that above code is just an example, where are these \0 is not fixed.

Body:
Assuming you know the size of the block of memory (hard coded to 100 here):

for (int i = 0; i < 100; i++)
{
    char c = p[i];
    if (c != 0)
        printf("%c", c);
}

Minor nit but in your sample above, the string will be "asdfghi123", because the memcpy for "1234" is only copying 3 bytes.


问:
How do I sort very large files
I have some files that should be sorted according to id at the beginning of each line.
The files are about 2-3 gb.
I tried to read all data into an ArrayList and sort them. But memory is not enough to keep them all. It does not work.

Lines look like

0052304 0000004000000000000000000000000000000041   John Teddy   000023

0022024 0000004000000000000000000000000000000041   George Clan 00013

How can I sort the files??

答:
Use the java library big-sorter which can be used for sorting very large text or binary files.

Here's how your exact problem would be implemented:

// write the input to a file
String s = "0052304 0000004000000000000000000000000000000041   John Teddy   000023\n"
        + "0022024 0000004000000000000000000000000000000041   George Clan 00013";
File input = new File("target/input");
Files.write(input.toPath(),s.getBytes(StandardCharsets.UTF_8), StandardOpenOption.WRITE);

File output = new File("target/output");

//sort the input
Sorter
    .serializerLinesUtf8()
    .comparator((a,b) -> {
        String ida = a.substring(0, a.indexOf(' '));
        String idb = b.substring(0, b.indexOf(' '));
        return ida.compareTo(idb);
    })
    .input(input)
    .output(output)
    .sort();

// display the output
Files.readAllLines(output.toPath()).forEach(System.out::println);
```

<p>output:</p>

```0022024 0000004000000000000000000000000000000041   George Clan 00013
0052304 0000004000000000000000000000000000000041   John Teddy   000023
```

Title: How do I sort very large files

Body:
Use the java library big-sorter which can be used for sorting very large text or binary files.

Here's how your exact problem would be implemented:

// write the input to a file
String s = "0052304 0000004000000000000000000000000000000041   John Teddy   000023\n"
        + "0022024 0000004000000000000000000000000000000041   George Clan 00013";
File input = new File("target/input");
Files.write(input.toPath(),s.getBytes(StandardCharsets.UTF_8), StandardOpenOption.WRITE);

File output = new File("target/output");

//sort the input
Sorter
    .serializerLinesUtf8()
    .comparator((a,b) -> {
        String ida = a.substring(0, a.indexOf(' '));
        String idb = b.substring(0, b.indexOf(' '));
        return ida.compareTo(idb);
    })
    .input(input)
    .output(output)
    .sort();

// display the output
Files.readAllLines(output.toPath()).forEach(System.out::println);

output:

0022024 0000004000000000000000000000000000000041   George Clan 00013
0052304 0000004000000000000000000000000000000041   John Teddy   000023


问:
How can I do something like foreach in Stata using R?
I'm new to R and am using Stata. I can loop through the variables using foreach and forvalue in Stata.

I would like to loop over column rather than loop over row. For example, I have column named var1, var2, var3. And the data as below:

```<code>var1 var2 var3
  1    1   1
  2   999  3
 999   2  999
</code>```

I would like to recode all "999" values in the variables to missing. In Stata, I can do

```<code>forvalue i = 1(1)3{
  replace var`i' ="NA" if var`i' =="999"
}
</code>```

Therefore, I have the outcome like

```<code>var1 var2 var3
  1    1   1
  2   NA   3
  NA   2  NA
</code>```

Also, if I have column named ht, wgt, bmi, I would like to calculate the mean of the column and store the mean in new column with respective name. The dataset is as below:

```<code> ht     wgt   bmi
154.5  43.1 18.1
164.2  63   23.4
</code>```

In Stata, I can do

```<code>foreach i of varlist ht wgt bmi{
  gen `i'mean = mean(`i')
}
</code>```

And the outcome will be

```<code> ht    wgt   bmi  htmean wgtmean bmimean
154.5  43.1 18.1  159.35  53.05   20.75
164.2  63   23.4  159.35  53.05   20.75
</code>```

I've no idea how to do using R.

答:
So several options here. I strongly recommend adding some sample data so that we can better help you. Depending on what you are doing you could do several things:

```<code>library(dplyr)
mtcars %>%
    mutate(my_hp = case_when(
        hp<50~"Small",
        hp < 100~"Medium",
        TRUE~"Large"
    ))

</code>```

This applies to conditional logic use the mutate function to create a new variable(column) and the case_when function to use different cases dependent on the value of hp.

Additionally, you could go with a base R approach which could look like

```<code>mtcars$my_hp <- ifelse(mtcars$hp < 50, "Small",
                                             ifelse(mtcars$hp< 100, "Medium",
                                                         "Large"))
</code>```

So in this case you are creating a new value called my_hp using chained ifelse statements which check for a condition.

And if you absolutely wanted to do a loop, which you would not need to do in this case, you could do something like:

```<code>for( i in 1:nrow(mtcars)){
    mtcars$my_hp[i] <- ifelse(mtcars$hp[i] < 50, "Small",
                                                            ifelse(mtcars$hp[i]< 100, "Medium",
                                                                         "Large"))

}
</code>```

Body:
I'm new to R and am using Stata. I can loop through the variables using foreach and forvalue in Stata.

I would like to loop over column rather than loop over row. For example, I have column named var1, var2, var3. And the data as below:

var1 var2 var3
  1    1   1
  2   999  3
 999   2  999

I would like to recode all "999" values in the variables to missing. In Stata, I can do

forvalue i = 1(1)3{
  replace var`i' ="NA" if var`i' =="999"
}

Therefore, I have the outcome like

var1 var2 var3
  1    1   1
  2   NA   3
  NA   2  NA

Also, if I have column named ht, wgt, bmi, I would like to calculate the mean of the column and store the mean in new column with respective name. The dataset is as below:

 ht     wgt   bmi
154.5  43.1 18.1
164.2  63   23.4

In Stata, I can do

foreach i of varlist ht wgt bmi{
  gen `i'mean = mean(`i')
}

And the outcome will be

 ht    wgt   bmi  htmean wgtmean bmimean
154.5  43.1 18.1  159.35  53.05   20.75
164.2  63   23.4  159.35  53.05   20.75

I've no idea how to do using R.

Body:
So several options here. I strongly recommend adding some sample data so that we can better help you. Depending on what you are doing you could do several things:

library(dplyr)
mtcars %>%
    mutate(my_hp = case_when(
        hp<50~"Small",
        hp < 100~"Medium",
        TRUE~"Large"
    ))

This applies to conditional logic use the mutate function to create a new variable(column) and the case_when function to use different cases dependent on the value of hp.

Additionally, you could go with a base R approach which could look like

mtcars$my_hp <- ifelse(mtcars$hp < 50, "Small",
                                             ifelse(mtcars$hp< 100, "Medium",
                                                         "Large"))

So in this case you are creating a new value called my_hp using chained ifelse statements which check for a condition.

And if you absolutely wanted to do a loop, which you would not need to do in this case, you could do something like:

for( i in 1:nrow(mtcars)){
    mtcars$my_hp[i] <- ifelse(mtcars$hp[i] < 50, "Small",
                                                            ifelse(mtcars$hp[i]< 100, "Medium",
                                                                         "Large"))

}


问:
CYPHER/NEO4J: Counting and removing duplicates from pattern comprehension list results
I am trying to combine count and distinct with comprehension list and keep getting errors.

I think this explains what I'd like to do, though I'm aware it does not work:

```<code>Match (n) WHERE n.id={id}
RETURN n {.id, ems: [(n)<-[:LOTS_OF_PATHS*]-()<-[:EVEN_MORE_PATHS*]-(m) | id:     distinct m.id, count: count(distinct m)]}
</code>```

Have also tried with some collects in there

```<code>Match (n) WHERE n.id={id}
RETURN n {.id, ems: [(n)<-[:LOTS_OF_PATHS*]-()<-[:EVEN_MORE_PATHS*]-(m) | collect(distinct m {id:m.id}), count: count(distinct m)]}
</code>```

I'm actually collecting the comprehension lists, and ideally would like no repeats within each array, and ideally no repeats amongst the sum of collects.

```<code>Match (n) WHERE n.id={id}
RETURN n {.id, collect([(n)<-[:LOTS_OF_PATHS*]-()<-[:EVEN_MORE_PATHS*]-(m) | distinct m.id])+ collect([(n)<-[:OTHER_PATHS*]-()<-[:MORE_PATHS*]-(o) | distinct o.id]) as distinct_ems_and_os}
</code>```

The count is less important as I can count the array, but would love to understand it a bit better.

答:
This query (which does not use the fairly limited pattern comprehension) might work for you:

```<code>MATCH (n)<-[:LOTS_OF_PATHS*]-()<-[:EVEN_MORE_PATHS*]-(m)
WHERE n.id = $id
WITH COLLECT(DISTINCT m.id) AS ems
RETURN {id: $id, ems: ems, count: SIZE(ems)}
</code>```

NOTE: variable-length relationships have exponential complexity. You may need to set a reasonable upper bound on the number of hops to avoid running out of memory or long execution times.

Body:
I am trying to combine count and distinct with comprehension list and keep getting errors.

I think this explains what I'd like to do, though I'm aware it does not work:

Match (n) WHERE n.id={id}
RETURN n {.id, ems: [(n)<-[:LOTS_OF_PATHS*]-()<-[:EVEN_MORE_PATHS*]-(m) | id:     distinct m.id, count: count(distinct m)]}

Have also tried with some collects in there

Match (n) WHERE n.id={id}
RETURN n {.id, ems: [(n)<-[:LOTS_OF_PATHS*]-()<-[:EVEN_MORE_PATHS*]-(m) | collect(distinct m {id:m.id}), count: count(distinct m)]}

I'm actually collecting the comprehension lists, and ideally would like no repeats within each array, and ideally no repeats amongst the sum of collects.

Match (n) WHERE n.id={id}
RETURN n {.id, collect([(n)<-[:LOTS_OF_PATHS*]-()<-[:EVEN_MORE_PATHS*]-(m) | distinct m.id])+ collect([(n)<-[:OTHER_PATHS*]-()<-[:MORE_PATHS*]-(o) | distinct o.id]) as distinct_ems_and_os}

The count is less important as I can count the array, but would love to understand it a bit better.

Body:
This query (which does not use the fairly limited pattern comprehension) might work for you:

MATCH (n)<-[:LOTS_OF_PATHS*]-()<-[:EVEN_MORE_PATHS*]-(m)
WHERE n.id = $id
WITH COLLECT(DISTINCT m.id) AS ems
RETURN {id: $id, ems: ems, count: SIZE(ems)}

NOTE: variable-length relationships have exponential complexity. You may need to set a reasonable upper bound on the number of hops to avoid running out of memory or long execution times.


问:
I am not able to remove elements from the list
The task that I have to do is showing all other elements rather than (Americano). I tried to use 'Record.remove("Americano") but it shows the error

```<code>Record.remove("Americano")
ValueError: list.remove(x): x not in list
</code>```

What should I Do......

=========================this is the result of=======================     Record.append(record[1]) print(Record) ->

```<code>['Menu_name', 'Cafe_latte', 'Americano', 'Americano', 'Smoothie_queen', 'Americano', 'Americano', 'Cafe_mocha', 'Cafe_latte', 'Americano', 'Amorparty', 'Plain_yogurt', 'Americano', 'Americano', 'Cafe_mocha', 'Berry_smoothie', 'Cafe_mocha', 'Cafe_latte', 'Americano', 'Cafe_latte', 'Berry_smoothie', 'Berry_smoothie', 'Plain_yogurt', 'Berry_smoothie', 'Plane_yougurt', 'Berry_smoothie', 'Cafe_latte', 'Americano', 'Americano', 'Cafe_mocha', 'Plain_yogurt', 'Americano', 'Plain_yogurt', 'Cafe_mocha', 'Plain_yogurt', 'Americano', 'Cofe_latte', 'Plain_yogurt', 'Cafe_mocha', 'Americano', 'Berry_smoothie', 'Cafe_latte', 'Cafe_latte', 'Cafe_mocha', 'Cafe_latte', 'Cafe_latte', 'Cafe_mocha', 'Americano', 'Plain_yogurt', 'Americano', 'Americano', 'Cofe_latte', 'Berry_smoothie', 'Berry_smudie', 'American_air', 'Plain_yogurt', 'Berry_smoothie', 'Berry_smoothie', 'Berry_smoothie', 'Cafe_latte', 'Americano', 'Plain_yogurt', 'Cafe_latte', 'Cafe_mocha', 'Cafe_mocha', 'Plain_yogurt', 'Berry_smoothie', 'Berry_smoothie', 'Cafe_mocha', 'Cafe_mocha', 'Berry_smoothie', 'Cafe_mocha', 'Plain_yogurt']
</code>```

```<code>def load_menu():
    Menu = []
    #========= STEP 1 ==========
    menufile = open("menu.txt", "r")

    for line in menufile:
        menu = line.split()
        Menu.append(menu)

    menufile.close()

    for menu in Menu:
        print(menu[0]," : ",menu[1])
    #========= STEP 1 ==========
    return Menu

def error_check(date):
    #========= STEP 3 ==========
    Record = []
    recordfile = open("ledger_"+date+".txt","r")

    for line in recordfile:
        record = line.split()
        Record.append(record[1])
        Record.remove("Americano")
    print(Record)

    recordfile.close()
    #========= STEP 3 ==========
</code>```

答:
ValueError: list.remove(x): x not in list
```

<p>You have error because list Record don't have "Americano" in Record.</p>

<p>You should check record is not 'Americano' before add it to Record</p>

<p>Try this:</p>

<pre class="lang-py prettyprint-override"><code>def error_check(date):
    #========= STEP 3 ==========
    Record = []
    recordfile = open("ledger_"+date+".txt","r")

    for line in recordfile:
        record = line.split()[1]
        if record != "Americano":
            Record.append(record)
    print(Record)
    recordfile.close()
</code>```

Body:
The task that I have to do is showing all other elements rather than (Americano). I tried to use 'Record.remove("Americano") but it shows the error

Record.remove("Americano")
ValueError: list.remove(x): x not in list

What should I Do......

=========================this is the result of=======================     Record.append(record[1]) print(Record) ->

['Menu_name', 'Cafe_latte', 'Americano', 'Americano', 'Smoothie_queen', 'Americano', 'Americano', 'Cafe_mocha', 'Cafe_latte', 'Americano', 'Amorparty', 'Plain_yogurt', 'Americano', 'Americano', 'Cafe_mocha', 'Berry_smoothie', 'Cafe_mocha', 'Cafe_latte', 'Americano', 'Cafe_latte', 'Berry_smoothie', 'Berry_smoothie', 'Plain_yogurt', 'Berry_smoothie', 'Plane_yougurt', 'Berry_smoothie', 'Cafe_latte', 'Americano', 'Americano', 'Cafe_mocha', 'Plain_yogurt', 'Americano', 'Plain_yogurt', 'Cafe_mocha', 'Plain_yogurt', 'Americano', 'Cofe_latte', 'Plain_yogurt', 'Cafe_mocha', 'Americano', 'Berry_smoothie', 'Cafe_latte', 'Cafe_latte', 'Cafe_mocha', 'Cafe_latte', 'Cafe_latte', 'Cafe_mocha', 'Americano', 'Plain_yogurt', 'Americano', 'Americano', 'Cofe_latte', 'Berry_smoothie', 'Berry_smudie', 'American_air', 'Plain_yogurt', 'Berry_smoothie', 'Berry_smoothie', 'Berry_smoothie', 'Cafe_latte', 'Americano', 'Plain_yogurt', 'Cafe_latte', 'Cafe_mocha', 'Cafe_mocha', 'Plain_yogurt', 'Berry_smoothie', 'Berry_smoothie', 'Cafe_mocha', 'Cafe_mocha', 'Berry_smoothie', 'Cafe_mocha', 'Plain_yogurt']

def load_menu():
    Menu = []
    #========= STEP 1 ==========
    menufile = open("menu.txt", "r")

    for line in menufile:
        menu = line.split()
        Menu.append(menu)

    menufile.close()

    for menu in Menu:
        print(menu[0]," : ",menu[1])
    #========= STEP 1 ==========
    return Menu

def error_check(date):
    #========= STEP 3 ==========
    Record = []
    recordfile = open("ledger_"+date+".txt","r")

    for line in recordfile:
        record = line.split()
        Record.append(record[1])
        Record.remove("Americano")
    print(Record)

    recordfile.close()
    #========= STEP 3 ==========

Body:
ValueError: list.remove(x): x not in list

You have error because list Record don't have "Americano" in Record.

You should check record is not 'Americano' before add it to Record

Try this:

def error_check(date):
    #========= STEP 3 ==========
    Record = []
    recordfile = open("ledger_"+date+".txt","r")

    for line in recordfile:
        record = line.split()[1]
        if record != "Americano":
            Record.append(record)
    print(Record)
    recordfile.close()


问:
Enable ASLR in GDB
I know that GDB disables ASLR for applications it debugs.
Is there a way to enable ASLR inside GDB? I have a bug that I can only reproduce with ASLR enabled.

Thanks,

答:
Is there a way to enable ASLR inside GDB?

Yes:

```<code>(gdb) set disable-randomization off
</code>```

Title: Enable ASLR in GDB

Body:
Is there a way to enable ASLR inside GDB?

Yes:

(gdb) set disable-randomization off


问:
Request Data from Database and Check with if() condition but the result show even if() condition not meet
I'm trying to do something like after user click the button, store data in database and than request that data to check with if condition, if the condition is meet or true, the button should disappear.

Storing Data is success but if() condition is wrong when i use the stored data to check.

This is the part that i want to check using if()

```<code><?
    $usercheck = $conn->query("SELECT * FROM wallets WHERE wallet = $wallet  ");
    if($usercheck['s1'] == 0){
    $res = $conn->query("SELECT * FROM shortlink WHERE shortid = 1 ");
        while($row = $res->fetch_array()){
    ?>
    <div class="col-md-2"><? echo $row['shortname']; ?></div>
    <div class="col-md-2"><? echo $row['shortreward']; ?> <i class="fab fa-viacoin"></i></div>
    <div class="col-md-2"><a href="shortlink.php?claim=<? echo $row['shortid']; ?>" ><button class="btn-primary" name="claim">Claim</button></a></div>
    <? } } ?>
</code>```

The expect output is if($usercheck['s3'] == 0)is correct button should show but if($usercheck['s3'] == 0) is wrong button shouldn't be show

答:
After i add single code at $wallet in sql statement and do one more while loop, the problem solved :D</p>

```<code><?
        $usercheck = $conn->query("SELECT * FROM wallets WHERE wallet = '$wallet'  ");
        while($row = $usercheck->fetch_assoc()){
           $s = $row['s1'];
       }
       if($s == 0){
        $res = $conn->query("SELECT * FROM shortlink WHERE shortid = 1 ");
            while($row = $res->fetch_array()){
        ?>
        <div class="col-md-2"><? echo $row['shortname']; ?></div>
        <div class="col-md-2"><? echo $row['shortreward']; ?> <i class="fab fa-viacoin"></i></div>
        <div class="col-md-2"><a href="shortlink.php?claim=<? echo $row['shortid']; ?>" ><button class="btn-primary" name="claim">Claim</button></a></div>
        <? } } ?>
</code>```

Body:
I'm trying to do something like after user click the button, store data in database and than request that data to check with if condition, if the condition is meet or true, the button should disappear.

Storing Data is success but if() condition is wrong when i use the stored data to check.

This is the part that i want to check using if()

<?
    $usercheck = $conn->query("SELECT * FROM wallets WHERE wallet = $wallet  ");
    if($usercheck['s1'] == 0){
    $res = $conn->query("SELECT * FROM shortlink WHERE shortid = 1 ");
        while($row = $res->fetch_array()){
    ?>

<? echo $row['shortname']; ?>

<? echo $row['shortreward']; ?>

<a href="shortlink.php?claim=<? echo $row['shortid']; ?>" ><button class="btn-primary" name="claim">Claim</button>

    <? } } ?>

The expect output is if($usercheck['s3'] == 0)is correct button should show but if($usercheck['s3'] == 0) is wrong button shouldn't be show

Body:
After i add single code at $wallet in sql statement and do one more while loop, the problem solved :D

<?
        $usercheck = $conn->query("SELECT * FROM wallets WHERE wallet = '$wallet'  ");
        while($row = $usercheck->fetch_assoc()){
           $s = $row['s1'];
       }
       if($s == 0){
        $res = $conn->query("SELECT * FROM shortlink WHERE shortid = 1 ");
            while($row = $res->fetch_array()){
        ?>
        <div class="col-md-2"><? echo $row['shortname']; ?></div>
        <div class="col-md-2"><? echo $row['shortreward']; ?> <i class="fab fa-viacoin"></i></div>
        <div class="col-md-2"><a href="shortlink.php?claim=<? echo $row['shortid']; ?>" ><button class="btn-primary" name="claim">Claim</button></a></div>
        <? } } ?>


问:
Get data from 3 tables by one query
I have a small blog project
I have 3 tables

```<code>Posts
PostID | TITLE | WRITERS(USERS) | CATEGORIES
1 | SOME TITLE | 1,2 | 1,2

USERS
USERID | USERNAME
1 | Alaa
2 | John

Categories
1 | Business
2 | Marketing
</code>```

I am trying to get this output

```<code>POST TITLE: SOME TITLE
Writers: Alaa And John
Categories: Business, And marketing
</code>```

Please note that i am talking about a very big loop, 100 post in a page for many viewers

So, currently i have two ideas

First idea

```<code>1- take value from writers ( 1,2 )
2- Explode it by php
3- use mysql query to bring the writers
4- Do the same thing for categories
</code>```

Second idea is to remove the columns writers, categories from the posts table and create a fourth table and call it connections, which will refer ids to each others ( connect everything together )
But i don't even know if i can do the mysql query

答:
You can get all these values in one MySQL query.

```<code>SELECT p.TITLE AS `Post Title`,
       GROUP_CONCAT(DISTINCT u.USERNAME) AS Writers,
       GROUP_CONCAT(DISTINCT c.CategoryName) AS Categories
FROM Posts p
JOIN Users u ON FIND_IN_SET(u.USERID, p.WRITERS)
JOIN Categories c ON FIND_IN_SET(c.Id, p.CATEGORIES)
GROUP BY p.TITLE
</code>```

Output:

```<code>Post Title  Writers     Categories
SOME TITLE  Alaa,John   Business,Marketing
</code>```

Demo on dbfiddle

Note: storing values in comma separated lists (e.g. your WRITERS and CATEGORIES columns) is a bad idea and makes writing this sort of query problematic (it's only MySQL's FIND_IN_SET function which makes it workable at all) and you should look into properly normalising your data (one value per row). Here is an example of how your database could look normalised.

Title: Get data from 3 tables by one query

Body:
I have a small blog project
I have 3 tables

Posts
PostID | TITLE | WRITERS(USERS) | CATEGORIES
1 | SOME TITLE | 1,2 | 1,2

USERS
USERID | USERNAME
1 | Alaa
2 | John

Categories
1 | Business
2 | Marketing

I am trying to get this output

POST TITLE: SOME TITLE
Writers: Alaa And John
Categories: Business, And marketing

Please note that i am talking about a very big loop, 100 post in a page for many viewers

So, currently i have two ideas

First idea

1- take value from writers ( 1,2 )
2- Explode it by php
3- use mysql query to bring the writers
4- Do the same thing for categories

Second idea is to remove the columns writers, categories from the posts table and create a fourth table and call it connections, which will refer ids to each others ( connect everything together )
But i don't even know if i can do the mysql query

Body:
You can get all these values in one MySQL query.

SELECT p.TITLE AS `Post Title`,
       GROUP_CONCAT(DISTINCT u.USERNAME) AS Writers,
       GROUP_CONCAT(DISTINCT c.CategoryName) AS Categories
FROM Posts p
JOIN Users u ON FIND_IN_SET(u.USERID, p.WRITERS)
JOIN Categories c ON FIND_IN_SET(c.Id, p.CATEGORIES)
GROUP BY p.TITLE

Output:

Post Title  Writers     Categories
SOME TITLE  Alaa,John   Business,Marketing

Demo on dbfiddle

Note: storing values in comma separated lists (e.g. your WRITERS and CATEGORIES columns) is a bad idea and makes writing this sort of query problematic (it's only MySQL's FIND_IN_SET function which makes it workable at all) and you should look into properly normalising your data (one value per row). Here is an example of how your database could look normalised.


问:
Insert query using foreach
I'm trying to generate a statement sheet. For that, I try to insert data into Mysql using foreach. It works great. But I try to escape the insert query if any duplicate row found in database. I do not want to escape the whole process, but it should escape if a duplicate row found and continue with the next insert query. </p>

```<code>$gps = $this->Webmastermodel->acquireStatementDetail();

foreach($gps as $statement){

$insertdata = array(
'product_invoice_id' => $statement['InvoiceNo'],
'PUC' => $statement['productPUC'],
'productQTY' => $statement['productQty'],
'product_sub_total' => $statement['productSubTotal'],
'commissionGain_on_SubTotal' => $statement['commisionChargedOnProductSubTotal']
    );

$this->db->insert('partner_business', $insertdata);

        }
</code>```

答:
I would use insert_batch if i were you:

```<code>$insertdata = array();
foreach($gps as $statement)
{

    $insertdata[] = array(
    'product_invoice_id' => $statement['InvoiceNo'],
    'PUC' => $statement['productPUC'],
    'productQTY' => $statement['productQty'],
    'product_sub_total' => $statement['productSubTotal'],
    'commissionGain_on_SubTotal' => $statement['commisionChargedOnProductSubTotal']
        );
}

$this->db->insert_batch('partner_business', $insertdata);
</code>```

But since your question is about skipping if a row already exits, you can modify your query and use replace instead:

```<code>$this->db->replace('partner_business', $insertdata);
</code>```

Keeping in mind that its all about providing the right primary_key in your $data array, if there is and existing id it will update its data else it will insert a new row.

Title: Insert query using foreach

Body:
I'm trying to generate a statement sheet. For that, I try to insert data into Mysql using foreach. It works great. But I try to escape the insert query if any duplicate row found in database. I do not want to escape the whole process, but it should escape if a duplicate row found and continue with the next insert query.

$gps = $this->Webmastermodel->acquireStatementDetail();

foreach($gps as $statement){

$insertdata = array(
'product_invoice_id' => $statement['InvoiceNo'],
'PUC' => $statement['productPUC'],
'productQTY' => $statement['productQty'],
'product_sub_total' => $statement['productSubTotal'],
'commissionGain_on_SubTotal' => $statement['commisionChargedOnProductSubTotal']
    );

$this->db->insert('partner_business', $insertdata);

        }

Body:
I would use insert_batch if i were you:

$insertdata = array();
foreach($gps as $statement)
{

    $insertdata[] = array(
    'product_invoice_id' => $statement['InvoiceNo'],
    'PUC' => $statement['productPUC'],
    'productQTY' => $statement['productQty'],
    'product_sub_total' => $statement['productSubTotal'],
    'commissionGain_on_SubTotal' => $statement['commisionChargedOnProductSubTotal']
        );
}

$this->db->insert_batch('partner_business', $insertdata);

But since your question is about skipping if a row already exits, you can modify your query and use replace instead:

$this->db->replace('partner_business', $insertdata);

Keeping in mind that its all about providing the right primary_key in your $data array, if there is and existing id it will update its data else it will insert a new row.


问:
How can I get a callback after a caller has been "enqueued"?
I want to run some code that takes a few seconds to complete (lookup the appropriate agents and call them). If I do it inline, the queueing of the call is delayed by a few seconds and the caller hears silence.

The "action" callback only triggers after the caller leaves the queue, and if I do it in the "waitUrl" callback, the call music is delayed.

Is there an elegant solution for this? Like some way to run the code async, or do it in a callback that won't affect the caller experience?

I guess I could use a 3rd party service (like Zapier, e.g. incoming webhook that calls a Twilio function from an outgoing webhook) to defer the long-running code, but I'd prefer to keep everything on the Twilio platform.

答:
Twilio developer evangelist here.

As you've noted, there are several times that Twilio requests your application and gives you opportunities to perform these actions. But in the context of a voice call, these webhooks are synchronous.

Asynchronous webhooks come in the form of the statusCallback, but these callbacks only occur for major events in the lifecycle of the call such as queued (this is for when calls are initiated, not when they are enqueued), ringing, in-progress, completed, busy, failed or no-answer.

For asynchronous actions you want to take in response to synchronous webhooks, you will need to setup an asynchronous call or pass the long running action off to a job to be processed outside of the synchronous call flow. There isn't anything inherent in Twilio to do this for you.


答:
Since the NUL bytes don’t mess up the way the text appears (I think) and that’s all you’re looking for, you should be able to write all of the bytes directly to stdout:</p>

```<code>fwrite(p, sizeof(char), 100, stdout);
</code>```

Title: How to print a fixed length memory area which contains multiple \0?

Body:
Since the NUL bytes don’t mess up the way the text appears (I think) and that’s all you’re looking for, you should be able to write all of the bytes directly to stdout:

fwrite(p, sizeof(char), 100, stdout);


问:
Installing Java for Eclipse on OSX
I've been trying to install Java, mainly for Eclipse, in the latest OSX (10.11) but it just wont work. I installed JRE 8 and 7 and when I launch Eclipse it says that the Java version isn't suitable for it (Says I have 1.6.0_65) and that I need version 1.7 or higher. Then I tried to install the JDK 7 and 8. Both installers get stuck on

```<code>Verifying JDK 7/8 Update xx.pkg
</code>```

and wont move on. I don't know what else to do. Can anyone help me?

Thank you,
Vasco

答: I just had the same problem trying to open the JDK 8 Update 211.pkg. I uninstalled the Java JRE using the comand line instructions here. I then restarted my machine, and tried opening the JDK 8 Update 211.pkg again and it worked right away.

Title: Installing Java for Eclipse on OSX

Body:
I've been trying to install Java, mainly for Eclipse, in the latest OSX (10.11) but it just wont work. I installed JRE 8 and 7 and when I launch Eclipse it says that the Java version isn't suitable for it (Says I have 1.6.0_65) and that I need version 1.7 or higher. Then I tried to install the JDK 7 and 8. Both installers get stuck on

Verifying JDK 7/8 Update xx.pkg

and wont move on. I don't know what else to do. Can anyone help me?

Thank you,
Vasco


问:
Can I update the style of the parents after element when an input inside it is focused using CSS/ SCSS?
Can I update the style of the parents after element when an input inside it is focused?

The design means I need to use an after element rather than styling the input with a border but i need to update the background colour of the after element when the input is focused. Can I do this just using SCSS / CSS?

HTML

```<code><div class="subscribe__wrapper">
    <div class="subscribe__input">
        <input class="mr-medium" type="email" id="fields-emailAdress" required name="fields[email]"
            placeholder="Your email address">
    </div>
    <button class="next btn-rounded btn-rounded--small ml-min">
    </button>
</div>
</code>```

SCSS

```<code>.subscribe__wrapper {
position: relative;
&:after {
      content: '';
      left: 0;
      right: 0;
      bottom: 0;
      height: 2px;
      background: $border-color;
      position: absolute;
    }
}

.subscribe__wrapper input:focus {
  .subscribe__wrapper & {
     &:after {
          background: red;
        }
    }
}
</code>```

答:
With pure CSS and your current markup, no, it's not possible. See this related question.

As suggested in the accepted answer to that question, though, you can modify your markup to add another element after the input and then style it using a sibling selector (+ or ~) when the input is in focus. This new element would have the background instead of putting it on a pseudo element of .subscribe__wrapper.

For example:

.subscribe__wrapper {
  position: relative;
  z-index: 0;
  padding: 12px;
  border: 2px solid blue;
}

.background {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: -1;
}

.subscribe__wrapper input:focus + .background {
  background-color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="subscribe__wrapper">
  <div class="subscribe__input">
    <input class="mr-medium" type="email" id="fields-emailAdress" required name="fields[email]" placeholder="Your email address">
    <div class="background"></div>
  </div>
  <button class="next btn-rounded btn-rounded--small ml-min"></button>
</div></code>```

Body:
Can I update the style of the parents after element when an input inside it is focused?

The design means I need to use an after element rather than styling the input with a border but i need to update the background colour of the after element when the input is focused. Can I do this just using SCSS / CSS?

HTML

        <input class="mr-medium" type="email" id="fields-emailAdress" required name="fields[email]"
            placeholder="Your email address">

    <button class="next btn-rounded btn-rounded--small ml-min">
    </button>

SCSS

.subscribe__wrapper {
position: relative;
&:after {
      content: '';
      left: 0;
      right: 0;
      bottom: 0;
      height: 2px;
      background: $border-color;
      position: absolute;
    }
}

.subscribe__wrapper input:focus {
  .subscribe__wrapper & {
     &:after {
          background: red;
        }
    }
}

Body:
With pure CSS and your current markup, no, it's not possible. See this related question.

As suggested in the accepted answer to that question, though, you can modify your markup to add another element after the input and then style it using a sibling selector (+ or ~) when the input is in focus. This new element would have the background instead of putting it on a pseudo element of .subscribe__wrapper.

For example:

.subscribe__wrapper {
  position: relative;
  z-index: 0;
  padding: 12px;
  border: 2px solid blue;
}

.background {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: -1;
}

.subscribe__wrapper input:focus + .background {
  background-color: red;
}

<div class="subscribe__wrapper">
  <div class="subscribe__input">
    <input class="mr-medium" type="email" id="fields-emailAdress" required name="fields[email]" placeholder="Your email address">
    <div class="background"></div>
  </div>
  <button class="next btn-rounded btn-rounded--small ml-min"></button>
</div>


问:
C# Generic Copy Constructor
I have an interface, and two classes that implements the interface.  The classes have generic types.  I would like to clone from an instance of one class to the other.

```<code>interface IFoo
{
    // stuff
}

class Foo<T> : IFoo
{
    // foo stuff
    // ifoo implementation
}

class Bar<T> : IFoo
{
    // bar stuff
    // ifoo implementation
}
</code>```

I have a Foo and would like a Bar.  Bar has a copy constructor taking a parameter of IFoo.
I created an extension method to implement the clone:

```<code>public static Bar<T> Clone<T>(this IFoo foo)
{
    return new Bar<T>(foo);
}
</code>```

Calling the method requires the type:

```<code>someFoo.Clone<T> ...
</code>```

Is there a way to omit declaring the type when calling the method by modifying the extension method, or any other way, to allow the the instance to just be passed in without caring about its underlying type?

Update
Here is how this is being used to better illustrate the situation.

In a method I iterate a collection and return an enumeration of IFoo.  In the method I look at an attribute of the source collection and determine the type of the Foo.

```<code>IFoo foo = null;

string type = element.Attribute("Type").Value;
switch (type)
{
    case "int":
        foo = new Foo<int>();
        break;

    case "string":
        foo = new Foo<string>();
        break;

    // etc
}
// other stuff

yield return foo;
</code>```

The calling method has a List.  Later I select individual items from this list for use, at which point I would like a Bar instead of a Foo.  When selecting from the list the instances are of type IFoo, as in they only see the extension methods for "this IFoo foo".  I do not want to cast the IFoo to a Foo, that would require re-declaring the type of T.  I would just like to have Foo tell Bar what it is.  Is this possible?

答:
Try defining the method as such

```<code>public static Bar<T> Clone<T>(this Foo<T> foo)
{
    return new Bar<T>(foo);
}
</code>```

This way, the parameter would have a generic type and the compiler would have a source for inferring the type from.

OwnerDisplayName: blu

Title: C# Generic Copy Constructor

Body:
I have an interface, and two classes that implements the interface.  The classes have generic types.  I would like to clone from an instance of one class to the other.

interface IFoo
{
    // stuff
}

class Foo<T> : IFoo
{
    // foo stuff
    // ifoo implementation
}

class Bar<T> : IFoo
{
    // bar stuff
    // ifoo implementation
}

I have a Foo and would like a Bar.  Bar has a copy constructor taking a parameter of IFoo.
I created an extension method to implement the clone:

public static Bar<T> Clone<T>(this IFoo foo)
{
    return new Bar<T>(foo);
}

Calling the method requires the type:

someFoo.Clone<T> ...

Is there a way to omit declaring the type when calling the method by modifying the extension method, or any other way, to allow the the instance to just be passed in without caring about its underlying type?

Update
Here is how this is being used to better illustrate the situation.

In a method I iterate a collection and return an enumeration of IFoo.  In the method I look at an attribute of the source collection and determine the type of the Foo.

IFoo foo = null;

string type = element.Attribute("Type").Value;
switch (type)
{
    case "int":
        foo = new Foo<int>();
        break;

    case "string":
        foo = new Foo<string>();
        break;

    // etc
}
// other stuff

yield return foo;

The calling method has a List.  Later I select individual items from this list for use, at which point I would like a Bar instead of a Foo.  When selecting from the list the instances are of type IFoo, as in they only see the extension methods for "this IFoo foo".  I do not want to cast the IFoo to a Foo, that would require re-declaring the type of T.  I would just like to have Foo tell Bar what it is.  Is this possible?

LastEditorDisplayName: blu

Body:
Try defining the method as such

public static Bar<T> Clone<T>(this Foo<T> foo)
{
    return new Bar<T>(foo);
}

This way, the parameter would have a generic type and the compiler would have a source for inferring the type from.

OwnerDisplayName: configurator


问:
Python to delete a row in excel spreadsheet
I have a really large excel file and i need to delete about 20,000 rows, contingent on meeting a simple condition and excel won't let me delete such a complex range when using a filter. The condition is:

If the first column contains the value, X, then I need to be able to delete the entire row.

I'm trying to automate this using python and xlwt, but am not quite sure where to start. Seeking some code snippits to get me started...
Grateful for any help that's out there!

答:
You can try using the csv reader:

http://docs.python.org/library/csv.html


问:
xamarin.forms (android ) Font scaling not working
I want to have fix scaling regardless of user's settings. I am successful to get this working when user change the display settings and increase/decrease the font size.

But My app doesn't scale the fonts to 1 when:

on app installation

on font-family change

I have tried doing Font scaling through updating/overriding the configuration.

```<code>private void AdjustFontScale()
        {
            Configuration configuration = Resources.Configuration;
            var fontScale = configuration.FontScale;
            configuration.FontScale = (float)1;
            DisplayMetrics metrics = new DisplayMetrics();
            WindowManager.DefaultDisplay.GetMetrics(metrics);
            metrics.ScaledDensity = configuration.FontScale * metrics.Density;
           BaseContext.Resources.UpdateConfiguration(configuration, metrics);
        }

- I have added  android:configChanges="fontScale" in my androidmanifest.xml file.
- AdjustFontScale() is called from OnCreate(), OnResume() and from OnConfigurationChanged() functions.

</code>```

I expect fonts should be scaled to 1 at App installation.

答:
you could try to override attachBaseContext method:

```<code>protected override void AttachBaseContext(Context @base)
{
    Configuration overrideConfiguration = new Configuration();
    overrideConfiguration = @base.Resources.Configuration;
    overrideConfiguration.SetToDefaults();
    var fontScale = overrideConfiguration.FontScale;
    overrideConfiguration.FontScale = (float)1;
    Context context = @base.CreateConfigurationContext(overrideConfiguration);
    base.AttachBaseContext(context);
}
</code>```

Body:
I want to have fix scaling regardless of user's settings. I am successful to get this working when user change the display settings and increase/decrease the font size.

But My app doesn't scale the fonts to 1 when:

on app installation

on font-family change

I have tried doing Font scaling through updating/overriding the configuration.

private void AdjustFontScale()
        {
            Configuration configuration = Resources.Configuration;
            var fontScale = configuration.FontScale;
            configuration.FontScale = (float)1;
            DisplayMetrics metrics = new DisplayMetrics();
            WindowManager.DefaultDisplay.GetMetrics(metrics);
            metrics.ScaledDensity = configuration.FontScale * metrics.Density;
           BaseContext.Resources.UpdateConfiguration(configuration, metrics);
        }

- I have added  android:configChanges="fontScale" in my androidmanifest.xml file.
- AdjustFontScale() is called from OnCreate(), OnResume() and from OnConfigurationChanged() functions.

I expect fonts should be scaled to 1 at App installation.

Body:
you could try to override attachBaseContext method:

protected override void AttachBaseContext(Context @base)
{
    Configuration overrideConfiguration = new Configuration();
    overrideConfiguration = @base.Resources.Configuration;
    overrideConfiguration.SetToDefaults();
    var fontScale = overrideConfiguration.FontScale;
    overrideConfiguration.FontScale = (float)1;
    Context context = @base.CreateConfigurationContext(overrideConfiguration);
    base.AttachBaseContext(context);
}