问:
How to process a binary image to align sparse letters in a row?
I am trying to use tesseract ocr to convert an image to text. The image always have three letters without rotation/skew, but randomly distributed in an 90x50 png file.

By just cleaning and converting to black/white, tesseract could not get the text in the image. After aligning them by hand in Paint, the ocr gives the exact match. I doesn't even need to be exactly aligned.
What I want is some tips on how to automate this alignment of the characters in the image prior to sending it to tesseract.

I am using python with tesseract and opencv.

Original image:

What I have done - turn black and white:

What I want to do - aligned by code:

答:
You can use the following code to achieve this output. Some of the constants may need to be changed to fit your needs:

```<code>import cv2
import numpy as np

# Read the image (resize so it is easier to see)
img = cv2.imread("/home/stephen/Desktop/letters.png",0)
h,w = img.shape
img = cv2.resize(img, (w*5,h*5))
# Threshold the image and find the contours
_, thresh = cv2.threshold(img, 123, 255, cv2.THRESH_BINARY_INV);
contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)

# Create a white background iamge to paste the letters on
bg = np.zeros((200,200), np.uint8)
bg[:] = 255
left = 5

# Iterate through the contours
for contour,h in zip(contours, hierarchy[0]):
    # Ignore inside parts (circle in a 'p' or 'b')
    if h[3] == -1:
        # Get the bounding rectangle
        x,y,w,h = cv2.boundingRect(contour)
        # Paste it onto the background
        bg[5:5+h,left:left+w] = img[y:y+h,x:x+w]
        left += (w + 5)
cv2.imshow('thresh', bg)
cv2.waitKey()
</code>```

Body:
You can use the following code to achieve this output. Some of the constants may need to be changed to fit your needs:

import cv2
import numpy as np

# Read the image (resize so it is easier to see)
img = cv2.imread("/home/stephen/Desktop/letters.png",0)
h,w = img.shape
img = cv2.resize(img, (w*5,h*5))
# Threshold the image and find the contours
_, thresh = cv2.threshold(img, 123, 255, cv2.THRESH_BINARY_INV);
contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)

# Create a white background iamge to paste the letters on
bg = np.zeros((200,200), np.uint8)
bg[:] = 255
left = 5

# Iterate through the contours
for contour,h in zip(contours, hierarchy[0]):
    # Ignore inside parts (circle in a 'p' or 'b')
    if h[3] == -1:
        # Get the bounding rectangle
        x,y,w,h = cv2.boundingRect(contour)
        # Paste it onto the background
        bg[5:5+h,left:left+w] = img[y:y+h,x:x+w]
        left += (w + 5)
cv2.imshow('thresh', bg)
cv2.waitKey()


来源: stackexchange

问:
Parsing JSON response into a struct
I'm using Alamofire and getting back the data from the API in JSON.
i want to use the data into a struct.
the response is the following:

```<code>{
  "status" : 1,
  "data" : [
{
  "classes" : [

  ],
  "day" : "Wednesday"
},
{
  "classes" : [
    {
      "time" : "1:30 PM",
      "available_spots" : 2,
      "trainer" : "Ahmed Jasim",
      "thumbnail" : "\/uploads\/classes\/6\/files\/class_6_15555066955cb72607131886.71740331.jpg",
      "id" : 6,
      "name" : "Gym Class C"
    }
  ],
  "day" : "Thursday"
},
{
  "classes" : [

  ],
  "day" : "Friday"
},
{
  "classes" : [

  ],
  "day" : "Saturday"
},
{
  "classes" : [
    {
      "available_spots" : 2,
      "id" : 1,
      "trainer" : "Ahmed Jasim",
      "name" : "Karate",
      "thumbnail" : "\/uploads\/classes\/1\/files\/class_1_15548800215cad9615e62404.41767774.jpg",
      "time" : "5:00 PM"
    }
  ],
  "day" : "Sunday"
},
{
  "classes" : [
    {
      "thumbnail" : "\/uploads\/classes\/1\/files\/class_1_15548800215cad9615e62404.41767774.jpg",
      "available_spots" : 2,
      "time" : "11:00 AM",
      "name" : "Karate",
      "id" : 1,
      "trainer" : "Ahmed Jasim"
    },
    {
      "trainer" : "Jalal Hassan",
      "available_spots" : 20,
      "thumbnail" : "\/uploads\/classes\/2\/files\/class_2_15548819805cad9dbc7b9a80.11639647.jpg",
      "time" : "4:00 PM",
      "name" : "Gym Class B",
      "id" : 2
    }
  ],
  "day" : "Monday"
},
{
  "classes" : [
    {
      "name" : "Gym Class B",
      "trainer" : "Jalal Hassan",
      "time" : "9:00 AM",
      "available_spots" : 20,
      "id" : 2,
      "thumbnail" : "\/uploads\/classes\/2\/files\/class_2_15548819805cad9dbc7b9a80.11639647.jpg"
    }
  ],
  "day" : "Tuesday"
}
 ],
 "message" : "Retrieved successfully",
 "success" : true
}
</code>```

I want to get the ' day & classes ' and use them in a struct.
the struct i'm using is as the following.

```<code>struct section {
day: String!
classes: [String]!
}
</code>```

so i want to get the day and it's classes and store them.
the call for the struct:

```<code> var sections = [Section(day: "Monday", classes: ["A","B","C"]]
</code>```

what i want to achieve is get all the days and it's classes & if the day has no classes it'll just be an empty array.

but i'm not sure if this is possible or not.

this is the code inside Alamofire request:

```<code>     let classesJSON: JSON = JSON(response.result.value!)

                if response.data != nil {

                    for index in 0..<classesJSON["data"].count {

                        var sections = Section(day: classesJSON["data"][index]["day"].stringValue, classes: [])
                        for data in classesJSON["data"].arrayValue {

                            for value in data["classes"].arrayValue {
                                sections.classes.append(value["name"].stringValue)
                               //sections.classes[index] = value["name"].stringValue
                            }
                        }
                        print(sections)
                    }

                }
</code>```

my problem is i'm getting all the classes in the response, what i want is to get the specific class for the day.

```<code>Section(day: Optional("Sunday"), classes: Optional(["Gym Class C", "Karate", "Karate", "Gym Class B", "Gym Class B"])

Section(day: Optional("Monday"), classes: Optional(["Gym Class C", "Karate", "Karate", "Gym Class B", "Gym Class B"])
</code>```

^ this is what i'm getting, but i want to seperate them so i can get the day and it's classes, not all of them

答:
I would recommend ditching SwiftyJSON and use real model objects with Codable instead.

Parse your data using structs like these:

```<code>struct APIResponse: Codable {
    let status: Int
    let data: [ClassData]
    let message: String
    let success: Bool
}

struct ClassData: Codable {
    let classes: [Class]
    let day: String
}

struct Class: Codable {
    let time: String
    let availableSpots: Int
    let trainer, thumbnail: String
    let id: Int
    let name: String

    enum CodingKeys: String, CodingKey {
        case time
        case availableSpots = "available_spots"
        case trainer, thumbnail, id, name
    }
}

struct Section {
    let day: String
    let classes: [String]
}

do {
    let response = try JSONDecoder().decode(APIResponse.self, from: json)

    let classesPerDay: [String: [Class]] = response.data.reduce(into: [:]) {
        $0[$1.day, default: []].append(contentsOf: $1.classes)
    }

    let sections = classesPerDay.map { Section(day: $0, classes: $1.map { $0.name }) }
    print(sections)
} catch {
    print(error)
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Parsing JSON response into a struct

Body:
I'm using Alamofire and getting back the data from the API in JSON.
i want to use the data into a struct.
the response is the following:

{
  "status" : 1,
  "data" : [
{
  "classes" : [

  ],
  "day" : "Wednesday"
},
{
  "classes" : [
    {
      "time" : "1:30 PM",
      "available_spots" : 2,
      "trainer" : "Ahmed Jasim",
      "thumbnail" : "\/uploads\/classes\/6\/files\/class_6_15555066955cb72607131886.71740331.jpg",
      "id" : 6,
      "name" : "Gym Class C"
    }
  ],
  "day" : "Thursday"
},
{
  "classes" : [

  ],
  "day" : "Friday"
},
{
  "classes" : [

  ],
  "day" : "Saturday"
},
{
  "classes" : [
    {
      "available_spots" : 2,
      "id" : 1,
      "trainer" : "Ahmed Jasim",
      "name" : "Karate",
      "thumbnail" : "\/uploads\/classes\/1\/files\/class_1_15548800215cad9615e62404.41767774.jpg",
      "time" : "5:00 PM"
    }
  ],
  "day" : "Sunday"
},
{
  "classes" : [
    {
      "thumbnail" : "\/uploads\/classes\/1\/files\/class_1_15548800215cad9615e62404.41767774.jpg",
      "available_spots" : 2,
      "time" : "11:00 AM",
      "name" : "Karate",
      "id" : 1,
      "trainer" : "Ahmed Jasim"
    },
    {
      "trainer" : "Jalal Hassan",
      "available_spots" : 20,
      "thumbnail" : "\/uploads\/classes\/2\/files\/class_2_15548819805cad9dbc7b9a80.11639647.jpg",
      "time" : "4:00 PM",
      "name" : "Gym Class B",
      "id" : 2
    }
  ],
  "day" : "Monday"
},
{
  "classes" : [
    {
      "name" : "Gym Class B",
      "trainer" : "Jalal Hassan",
      "time" : "9:00 AM",
      "available_spots" : 20,
      "id" : 2,
      "thumbnail" : "\/uploads\/classes\/2\/files\/class_2_15548819805cad9dbc7b9a80.11639647.jpg"
    }
  ],
  "day" : "Tuesday"
}
 ],
 "message" : "Retrieved successfully",
 "success" : true
}

I want to get the ' day & classes ' and use them in a struct.
the struct i'm using is as the following.

struct section {
day: String!
classes: [String]!
}

so i want to get the day and it's classes and store them.
the call for the struct:

 var sections = [Section(day: "Monday", classes: ["A","B","C"]]

what i want to achieve is get all the days and it's classes & if the day has no classes it'll just be an empty array.

but i'm not sure if this is possible or not.

this is the code inside Alamofire request:

     let classesJSON: JSON = JSON(response.result.value!)

                if response.data != nil {

                    for index in 0..<classesJSON["data"].count {

                        var sections = Section(day: classesJSON["data"][index]["day"].stringValue, classes: [])
                        for data in classesJSON["data"].arrayValue {

                            for value in data["classes"].arrayValue {
                                sections.classes.append(value["name"].stringValue)
                               //sections.classes[index] = value["name"].stringValue
                            }
                        }
                        print(sections)
                    }

                }

my problem is i'm getting all the classes in the response, what i want is to get the specific class for the day.

Section(day: Optional("Sunday"), classes: Optional(["Gym Class C", "Karate", "Karate", "Gym Class B", "Gym Class B"])

Section(day: Optional("Monday"), classes: Optional(["Gym Class C", "Karate", "Karate", "Gym Class B", "Gym Class B"])

^ this is what i'm getting, but i want to seperate them so i can get the day and it's classes, not all of them

Body:
I would recommend ditching SwiftyJSON and use real model objects with Codable instead.

Parse your data using structs like these:

struct APIResponse: Codable {
    let status: Int
    let data: [ClassData]
    let message: String
    let success: Bool
}

struct ClassData: Codable {
    let classes: [Class]
    let day: String
}

struct Class: Codable {
    let time: String
    let availableSpots: Int
    let trainer, thumbnail: String
    let id: Int
    let name: String

    enum CodingKeys: String, CodingKey {
        case time
        case availableSpots = "available_spots"
        case trainer, thumbnail, id, name
    }
}

struct Section {
    let day: String
    let classes: [String]
}

do {
    let response = try JSONDecoder().decode(APIResponse.self, from: json)

    let classesPerDay: [String: [Class]] = response.data.reduce(into: [:]) {
        $0[$1.day, default: []].append(contentsOf: $1.classes)
    }

    let sections = classesPerDay.map { Section(day: $0, classes: $1.map { $0.name }) }
    print(sections)
} catch {
    print(error)
}


问:
Quicksort is not sorting correctly
I essentially copied my code from a UCBerkeley quicksort video, but it only seems to sort in pairs almost. I'm not sure what's going on here.

I've looked through each line multiple times and can't see what's wrong. Everything makes sense to me.

```<code>static <E extends Comparable<? super E>>
void quicksort(E[] A, int low, int high) {
    if (low < high) {
        int pivotIndex = (low + high) / 2;
        E pivot = A[pivotIndex];
        // move pivot to end
        A[pivotIndex] = A[high];
        A[high] = pivot;

        int i = low - 1;
        int j = high;
        do {
            do {
                i++;
            } while (A[i].compareTo(pivot) < 0);
            do {
                j--;
            } while ((A[i].compareTo(pivot)) > 0 && (j > low));
            if (i < j) {
                E swap = A[i];
                A[i] = A[j];
                A[j] = swap;
            }
        } while (i < j);
        // i is now the first spot in the right partition (where we will put pivot)
        // now put pivot back where it belongs
        A[high] = A[i];
        A[i] = pivot;
        quicksort(A, low, i - 1); // sort left partition
        quicksort(A, i + 1, high);
    }
}
</code>```

I expected[2, 3, 5, 6, 10, 101, 200, 300] but got [3, 5, 2, 6, 10, 101, 200, 300]

答:
The compare in the second inner loop is using A[i] for the compare, when it should be using A[j]:

```<code>            } while ((A[j].compareTo(pivot)) > 0 && (j > low));  // A[j] not A[i]
</code>```

An alternative variation for this type of quicksort doesn't swap the pivot with A[high], and by leaving the pivot in the middle, the code won't need to check for j > low in the second inner loop, which is a bit faster. Using this variation needs other changes: init j to high + 1, and the two recursive calls should be quicksort(A, low, j) and quicksort(A, j+1, high). Note that values equal to the pivot, including the pivot itself, may end up in either either partition, since values equal to pivot get swapped.

Example code for primitives (int), that uses recursion on smaller or equal part, then iterates back for larger part to avoid stack overflow in worst case scenario. It can be converted to use generic object E.

```<code>    public static void qsort(int[] a, int lo, int hi)
    {
        while(lo < hi){
            int  md = lo+(hi-lo)/2;
            int  ll = lo-1;
            int  hh = hi+1;
            int p = a[md];
            int t;
            while(true){
                while(a[++ll] < p);
                while(a[--hh] > p);
                if(ll >= hh)
                    break;
                t     = a[ll];
                a[ll] = a[hh];
                a[hh] = t;
            }
            ll = hh++;
            if((ll - lo) <= (hi - hh)){
                qsort(a, lo, ll);
                lo = hh;
            } else {
                qsort(a, hh, hi);
                hi = ll;
            }
        }
    }
</code>```

Title: Quicksort is not sorting correctly

Body:
I essentially copied my code from a UCBerkeley quicksort video, but it only seems to sort in pairs almost. I'm not sure what's going on here.

I've looked through each line multiple times and can't see what's wrong. Everything makes sense to me.

static <E extends Comparable<? super E>>
void quicksort(E[] A, int low, int high) {
    if (low < high) {
        int pivotIndex = (low + high) / 2;
        E pivot = A[pivotIndex];
        // move pivot to end
        A[pivotIndex] = A[high];
        A[high] = pivot;

        int i = low - 1;
        int j = high;
        do {
            do {
                i++;
            } while (A[i].compareTo(pivot) < 0);
            do {
                j--;
            } while ((A[i].compareTo(pivot)) > 0 && (j > low));
            if (i < j) {
                E swap = A[i];
                A[i] = A[j];
                A[j] = swap;
            }
        } while (i < j);
        // i is now the first spot in the right partition (where we will put pivot)
        // now put pivot back where it belongs
        A[high] = A[i];
        A[i] = pivot;
        quicksort(A, low, i - 1); // sort left partition
        quicksort(A, i + 1, high);
    }
}

I expected[2, 3, 5, 6, 10, 101, 200, 300] but got [3, 5, 2, 6, 10, 101, 200, 300]

Body:
The compare in the second inner loop is using A[i] for the compare, when it should be using A[j]:

            } while ((A[j].compareTo(pivot)) > 0 && (j > low));  // A[j] not A[i]

An alternative variation for this type of quicksort doesn't swap the pivot with A[high], and by leaving the pivot in the middle, the code won't need to check for j > low in the second inner loop, which is a bit faster. Using this variation needs other changes: init j to high + 1, and the two recursive calls should be quicksort(A, low, j) and quicksort(A, j+1, high). Note that values equal to the pivot, including the pivot itself, may end up in either either partition, since values equal to pivot get swapped.

Example code for primitives (int), that uses recursion on smaller or equal part, then iterates back for larger part to avoid stack overflow in worst case scenario. It can be converted to use generic object E.

    public static void qsort(int[] a, int lo, int hi)
    {
        while(lo < hi){
            int  md = lo+(hi-lo)/2;
            int  ll = lo-1;
            int  hh = hi+1;
            int p = a[md];
            int t;
            while(true){
                while(a[++ll] < p);
                while(a[--hh] > p);
                if(ll >= hh)
                    break;
                t     = a[ll];
                a[ll] = a[hh];
                a[hh] = t;
            }
            ll = hh++;
            if((ll - lo) <= (hi - hh)){
                qsort(a, lo, ll);
                lo = hh;
            } else {
                qsort(a, hh, hi);
                hi = ll;
            }
        }
    }


问:
Get special max record
I have in my Table1 3 fields (IdFactory Type Numeric-IdSector Type Numeric-NameFactory Type Text).When i click on Button1 i get max record of (IdFactory) in TextBox1.My ComboBox1 is filled with several numbers from 1 to 100.I choose (IdSector) by ComboBox1 and the records in this field (IdSector) repeat only 5 times.How to automatically display max record of (IdSector) in combobox1 when i Click on Button1.this is my code to get max record on TextBox1</p>

答:
ExecuteScalar returns Nothing, not DBNull.Value if no result has been found.

```<code>Dim result As Object = Cmd.ExecuteScalar
Dim id As Integer
If result Is Nothing Then
    id = 1
Else
    id = CInt(result)  + 1
End If
TextBox1.Text = id.ToString()
ComboBox1.SelectedItem = id
</code>```

This assumes that you have added the numbers to the ComboBox as Integer and not as String. If you have added them as String do ComboBox1.SelectedItem = id.ToString().

Title: Get special max record

Body:
ExecuteScalar returns Nothing, not DBNull.Value if no result has been found.

Dim result As Object = Cmd.ExecuteScalar
Dim id As Integer
If result Is Nothing Then
    id = 1
Else
    id = CInt(result)  + 1
End If
TextBox1.Text = id.ToString()
ComboBox1.SelectedItem = id

This assumes that you have added the numbers to the ComboBox as Integer and not as String. If you have added them as String do ComboBox1.SelectedItem = id.ToString().


问:
Android Daily Weekly leaderboard implementation?
Hi I want to implement leaderboard for my game. I just implemented google play leaderboard. But the question is I want Daily and weekly leaderboard. And I need to reset from google play console daily and weekly.

@Thank you.

答:
You can  reset the value in draft leaderboard only , daily/weekly as needed ,
 in the Google Play Console, click the button labeled Reset leader board progress at the bottom of the form for that event.
To reset leaderboard data programmatically, call the Management API Scores methods.

link  https://developers.google.com/games/services/common/concepts/leaderboards


问:
How to fix a table causing "502: Bad Gateway" error in PHP
I am creating a simple database that can do basic CRUD operations (create, read, update, delete) using php. I am able to complete the create, and able to see the results if I directly query the mySQL DB in the back end. But, I am having trouble getting the table to display on the webpage. It is instead displaying a "Bad Gateway" error if I attempt to display the database entries.

I tried removing the reference to the table, specifically

```<code>    <?php while ($row = mysqli_fetch_array($results)) { ?>
            <tr>
                <td><?php echo $row['name']; ?></td>...
</code>```

and the web page on front end works fine. Albeit can only see the data if I query the backend.

```<code>    <?php  include('php_code.php'); ?>
    ...
    ...
    ...

    <?php $results = mysqli_query($db, "SELECT * FROM info"); ?>

    <table>
        <thead>
        <tr>
            <th>Name</th>
            <th>Address</th>
            <th>City</th>
            <th colspan="2">Action</th>
        </tr>
        </thead>

        <?php while ($row = mysqli_fetch_array($results)) { ?>
            <tr>
                <td><?php echo $row['name']; ?></td>
                <td><?php echo $row['address']; ?></td>
                <td><?php echo $row['city']; ?></td>
                <td>
                    <a href="test.php?edit=<?php echo $row['id']; ?>"
    class="edit_btn" >Edit</a>
                </td>
                <td>
                    <a href="php_code.php?del=<?php echo $row['id']; ?>"
    class="del_btn">Delete</a>
                </td>
            </tr>
        <?php } ?>
    </table>

    <!--in php_code.php-->
     //to retrieve records
        $select_query = "SELECT * FROM info";
        $result = mysqli_query($db, $select_query);
</code>```

I should be able to see the table with data containing name, address and city. But I am getting a 502 error instead.

答:
Try this

```<code><?php
  include('php_code.php');
  $results = mysqli_query($db, "SELECT * FROM `info` ");

  $return = <<<HTML
    <table>
        <thead>
        <tr>
          <th>Name</th>
          <th>Address</th>
          <th>City</th>
          <th colspan="2">Action</th>
        </tr>
        </thead>
        <tbody>
HTML;

  while ($row = mysqli_fetch_array($results)) {
    $return .= <<<HTML
      <tr>
        <td>{$row['name']}</td>
        <td>{$row['address']}</td>
        <td>{$row['city']}</td>
        <td><a href="test.php?edit={$row['id']}" class="edit_btn" >Edit</a></td>
        <td><a href="php_code.php?del={$row['id']}" class="del_btn">Delete</a></td>
      </tr>
HTML;
  }

  $return .= <<<HTML
      </tbody>
    </table>
HTML;

  echo $return;

?>
</code>```

your php_code.php should really only have the database config...

Body:
I am creating a simple database that can do basic CRUD operations (create, read, update, delete) using php. I am able to complete the create, and able to see the results if I directly query the mySQL DB in the back end. But, I am having trouble getting the table to display on the webpage. It is instead displaying a "Bad Gateway" error if I attempt to display the database entries.

I tried removing the reference to the table, specifically

    <?php while ($row = mysqli_fetch_array($results)) { ?>

                <?php echo $row['name']; ?>	...

and the web page on front end works fine. Albeit can only see the data if I query the backend.

    <?php  include('php_code.php'); ?>
    ...
    ...
    ...

    <?php $results = mysqli_query($db, "SELECT * FROM info"); ?>

            Name
            Address
            City
            Action

        <?php while ($row = mysqli_fetch_array($results)) { ?>

                <?php echo $row['name']; ?>
                <?php echo $row['address']; ?>
                <?php echo $row['city']; ?>

                    <a href="test.php?edit=<?php echo $row['id']; ?>"
    class="edit_btn" >Edit

                    <a href="php_code.php?del=<?php echo $row['id']; ?>"
    class="del_btn">Delete

        <?php } ?>

     //to retrieve records
        $select_query = "SELECT * FROM info";
        $result = mysqli_query($db, $select_query);

I should be able to see the table with data containing name, address and city. But I am getting a 502 error instead.

Body:
Try this

<?php
  include('php_code.php');
  $results = mysqli_query($db, "SELECT * FROM `info` ");

  $return = <<<HTML
    <table>
        <thead>
        <tr>
          <th>Name</th>
          <th>Address</th>
          <th>City</th>
          <th colspan="2">Action</th>
        </tr>
        </thead>
        <tbody>
HTML;

  while ($row = mysqli_fetch_array($results)) {
    $return .= <<<HTML
      <tr>
        <td>{$row['name']}</td>
        <td>{$row['address']}</td>
        <td>{$row['city']}</td>
        <td><a href="test.php?edit={$row['id']}" class="edit_btn" >Edit</a></td>
        <td><a href="php_code.php?del={$row['id']}" class="del_btn">Delete</a></td>
      </tr>
HTML;
  }

  $return .= <<<HTML
      </tbody>
    </table>
HTML;

  echo $return;

?>

your php_code.php should really only have the database config...


问:
Nock.js: how do I check for the existence of a header?
I am using Nock with Mocha, and want to check that certain headers exist on a request. I don't care about the other headers, and I don't care about the specific content of the headers whose existence I'm checking for. Is there an easy way to do this? .matchHeader() passes when the specific header is absent, and reqheaders fails unless I specify all the header fields.

答:
reqheaders is the right approach with this.

I'm not sure what issue you came across, but not all the headers need to be supplied. Only the ones that are required for a match.

The other nice feature of reqheaders is that the value can be a function returning a boolean. Since you don't care about the actual value of the headers, returning true has the effect of matching if the header simply exists.

```<code>const scope = nock('http://www.example.com', {
  reqheaders: {
    'x-one': () => true,
  }
}).get('/').reply(200, 'match!')

const reqOpts = {
  hostname: 'www.example.com',
  path: '/',
  method: 'GET',
  headers: {
    'X-One': 'hello world',
    'X-Two': 'foo bar',
    'Content-Type': 'application/json',
  }
}

const req = http.request(reqOpts, res => {
  console.log("##### res status", res.statusCode)

  res.on('data', (chunk) => {
    console.log("##### chunk", chunk.toString())
  })
})

req.end()
scope.done()
</code>```

Body:
reqheaders is the right approach with this.

I'm not sure what issue you came across, but not all the headers need to be supplied. Only the ones that are required for a match.

The other nice feature of reqheaders is that the value can be a function returning a boolean. Since you don't care about the actual value of the headers, returning true has the effect of matching if the header simply exists.

const scope = nock('http://www.example.com', {
  reqheaders: {
    'x-one': () => true,
  }
}).get('/').reply(200, 'match!')

const reqOpts = {
  hostname: 'www.example.com',
  path: '/',
  method: 'GET',
  headers: {
    'X-One': 'hello world',
    'X-Two': 'foo bar',
    'Content-Type': 'application/json',
  }
}

const req = http.request(reqOpts, res => {
  console.log("##### res status", res.statusCode)

  res.on('data', (chunk) => {
    console.log("##### chunk", chunk.toString())
  })
})

req.end()
scope.done()


问:
how to merge two array in php? [php]
I created SUBJECTS TO BE TAKEN BY STUDENTS in "subject" table

TABLE "SUBJECT"

```<code>ID| SHORTNAME | SUBJECT_NAME
1 | MT        | MATHEMATICS
2 | ASC       | ADDITIONAL SCIENCE
</code>```

The columns in this table are automatically generated into the table "MID_YEAR_EXAMINATION"

TABLE "MID_YEAR_EXAMINATION"

```<code>ID | STUDENT NAME | MT | ASC
</code>```

The scores obtained by students in each subject are inserted in the table "MID_YEAR_EXAMINATION"

```<code>ID | STUDENT_NAME | MT | ASC
1  | ALEX         | 88 | 62
2  | ELLY         | 78 | 43
</code>```

MY QUESTION is i have two arrays
code2

```<code>$input1= array(
    "id" => $row['ID'],
    "name" => $row['STUDENT_NAME']
);

$sel_query3="Select * from SUBJECT  ORDER BY SUBJECT_NAME";
$result3 = @mysqli_query($con,$sel_query3);
while($row2 = @mysqli_fetch_assoc($result3)){
    $MP = $row2['SHORTNAME'];
    $m = $row['SUBJECT_NAME']; //TO GET student's score
    in each subject
            $input2 = array($MP => $m);
    }
}
Echo  json_encode($input2);
</code>```

how to fix that arrays as follows with edit that code:

FROM

```<code>[
    "id"   => "1",
    "name" => "ALEX",
    "MT"   => "88"
]
[
    "id"   => "1",
    "name" => "ALEX",
    "ASC"  => "62"
]
</code>```

TO

```<code>[
    "id"   => "1",
    "name" => "ALEX",
    "MT"   => "88",
    "ASC"  => "62"
]
</code>```

("MT" and "ASC" merge in one array)

I need your help. Thanks!

答:
Use PHP's array_merge() function: https://www.php.net/manual/en/function.array-merge.php

If the source arrays are assigned to $a and $b, it's simply $combined = array_merge( $a, $b );

If $b has a different value for the same-named element in $a, the value from $b will win out.

```<code>$a = [
  "id"   => "1",
  "name" => "ALEX",
  "MT"   => "88"
];
$b = [
    "id"   => "1",
    "name" => "ALEX",
    "ASC"  => "62"
];
print_r( array_merge( $a, $b ) );
</code>```

output:

```<code>Array
(
    [id] => 1
    [name] => ALEX
    [MT] => 88
    [ASC] => 62
)
</code>```

Title: how to merge two array in php? [php]

Body:
I created SUBJECTS TO BE TAKEN BY STUDENTS in "subject" table

TABLE "SUBJECT"

ID| SHORTNAME | SUBJECT_NAME
1 | MT        | MATHEMATICS
2 | ASC       | ADDITIONAL SCIENCE

The columns in this table are automatically generated into the table "MID_YEAR_EXAMINATION"

TABLE "MID_YEAR_EXAMINATION"

ID | STUDENT NAME | MT | ASC

The scores obtained by students in each subject are inserted in the table "MID_YEAR_EXAMINATION"

ID | STUDENT_NAME | MT | ASC
1  | ALEX         | 88 | 62
2  | ELLY         | 78 | 43

MY QUESTION is i have two arrays
code2

$input1= array(
    "id" => $row['ID'],
    "name" => $row['STUDENT_NAME']
);

$sel_query3="Select * from SUBJECT  ORDER BY SUBJECT_NAME";
$result3 = @mysqli_query($con,$sel_query3);
while($row2 = @mysqli_fetch_assoc($result3)){
    $MP = $row2['SHORTNAME'];
    $m = $row['SUBJECT_NAME']; //TO GET student's score
    in each subject
            $input2 = array($MP => $m);
    }
}
Echo  json_encode($input2);

how to fix that arrays as follows with edit that code:

FROM

[
    "id"   => "1",
    "name" => "ALEX",
    "MT"   => "88"
]
[
    "id"   => "1",
    "name" => "ALEX",
    "ASC"  => "62"
]

TO

[
    "id"   => "1",
    "name" => "ALEX",
    "MT"   => "88",
    "ASC"  => "62"
]

("MT" and "ASC" merge in one array)

I need your help. Thanks!

Body:
Use PHP's array_merge() function: https://www.php.net/manual/en/function.array-merge.php

If the source arrays are assigned to $a and $b, it's simply $combined = array_merge( $a, $b );

If $b has a different value for the same-named element in $a, the value from $b will win out.

$a = [
  "id"   => "1",
  "name" => "ALEX",
  "MT"   => "88"
];
$b = [
    "id"   => "1",
    "name" => "ALEX",
    "ASC"  => "62"
];
print_r( array_merge( $a, $b ) );

output:

Array
(
    [id] => 1
    [name] => ALEX
    [MT] => 88
    [ASC] => 62
)


问:
gRPC slow bandwidth to remote server
I have a gRPC service that transfers files from a local machine to a remote server, and I'm noticing some significant bandwidth issues. On average, it's downloading at about 1mb/s with one connection sharing several streams (usually about 8).

The server uses TLS to encryption, but that doesn't seem to be the bottleneck, as turning off TLS has negligible effect on the performance. I've also tried using iperf3 to test the bandwidth directly between the client and the server, and it resulted in 10mb/s.

```<code>Connecting to host <host>, port <port>
[  7] local 10.0.0.112 port 59651 connected to <ip> port <port>
[ ID] Interval           Transfer     Bitrate
[  7]   0.00-1.00   sec  1.28 MBytes  10.7 Mbits/sec
[  7]   1.00-2.00   sec   894 KBytes  7.35 Mbits/sec
[  7]   2.00-3.00   sec   999 KBytes  8.17 Mbits/sec
[  7]   3.00-4.00   sec  1.19 MBytes  10.0 Mbits/sec
[  7]   4.00-5.00   sec   753 KBytes  6.17 Mbits/sec
[  7]   5.00-6.00   sec  1.16 MBytes  9.67 Mbits/sec
[  7]   6.00-7.00   sec  1.00 MBytes  8.44 Mbits/sec
[  7]   7.00-8.00   sec  1.26 MBytes  10.5 Mbits/sec
[  7]   8.00-9.00   sec  1.22 MBytes  10.2 Mbits/sec
[  7]   9.00-10.00  sec  1.15 MBytes  9.66 Mbits/sec
- - - - - - - - - - - - - - - - - - - - - - - - -
[ ID] Interval           Transfer     Bitrate
[  7]   0.00-10.00  sec  10.8 MBytes  9.09 Mbits/sec                  sender
[  7]   0.00-10.00  sec  10.7 MBytes  8.95 Mbits/sec                  receiver
</code>```

The upload bandwidth from the client is about 10mb/s, and the download of the server is about 50mb/s (via speedtest-cli)

traceroute doesn't show anything interesting either...

```<code>traceroute to mikemeredith.ddns.net (108.52.111.249), 64 hops max, 72 byte packets
 1  10.0.0.1 (10.0.0.1)  2.195 ms  5.388 ms  1.385 ms
 2  <ip>  (<ip>)  8.256 ms  145.115 ms  19.025 ms
 3  <ip2> (<ip2>)  9.951 ms  9.471 ms  141.929 ms
 4  <ip3> (<ip3>)  18.389 ms  9.684 ms  12.248 ms
 5  <ip4> (<ip4>)  143.880 ms  25.077 ms  10.606 ms
 6  ae-13-ar01.capitolhghts.md.bad.comcast.net (68.87.168.61)  142.567 ms  137.153 ms  20.790 ms
 7  be-33657-cr02.ashburn.va.ibone.comcast.net (68.86.90.57)  14.326 ms  144.076 ms  22.957 ms
 8  be-1102-cs01.ashburn.va.ibone.comcast.net (96.110.32.169)  13.881 ms  144.756 ms  23.981 ms
 9  be-2107-pe07.ashburn.va.ibone.comcast.net (96.110.32.186)  20.203 ms  94.433 ms  23.034 ms
10  n-a.gw12.iad8.alter.net (152.179.50.205)  20.254 ms  278.023 ms  31.660 ms
11  * * *
12  <ip12> (<ip13>)  66.277 ms  39.229 ms  34.543 ms
13  <ip13> (<ip14>)  48.849 ms  49.300 ms  49.546 ms
</code>```

Here's the actual code

Client Connection:

creds, err := credentials.NewClientTLSFromFile(cerLoc, "")
if err != nil {
    fmt..Printf("failed to get tls from file: %v\n", err)
    panic(err)
}
conn, err = grpc.Dial(host+port, grpc.WithTransportCredentials(creds))
```

<p>Client Stream:</p>

<pre class="lang-golang prettyprint-override"><code>ctx, cancel := context.WithCancel(context.Background())
defer cancel()
client := proto.Client(conn)
stream, err := client.BackupFiles(ctx, grpc.UseCompressor(gzip.Name))
// Send on stream, max size of message is 2mb
</code>```

Server Listening:

// Start serving on port
l, err := net.Listen("tcp", port)
if err != nil {
    fmt.Printf("error listening on port %v: %v\n", port, err)
    panic(err)
}

var s *grpc.Server
creds, err := credentials.NewServerTLSFromFile(
    certLoc,
    keyLoc,
)
if err != nil {
    fmt.Printf("error getting tls certs: %v\n", err)
    panic(err)
}
s = grpc.NewServer(grpc.Creds(creds))
proto.RegisterBackupServer(s, &server{})
err = s.Serve(l)

// Actual stream handling

// Get a pooled SharedBuffer for assembling the file
b := getBuffer()
defer putBuffer(b)
c := make(chan int, []50)
u, _ := user.Current()

uid := uuid.New()
fout, err := os.Create(filePath + uid.String())
if err != nil {
    fmt.Println("error creating staging file: ", err)
    panic(err)
}
var wg sync.WaitGroup

go assemble(b, fout, c, &wg)
for {
    in, err := stream.Recv()
    if err == io.EOF {
        break
    }
    if err != nil {
        fmt.Println("encountered an error receiving on stream: ", err)
        return err
    }

    bytesWritten = b.LockWrite(in.Payload) // This buffer is shared between the stream and the go routine

    c <- bytesWritten
}

close(c)
wg.Wait()

_ = fout.Close()

// This is a pre-declared workerpool that basically moves files around
wp.Submit(func() {
    finalizeFile(fout.Name(), name, perms, "", checkSum, userID)
})

return stream.SendAndClose(&proto.Resp{
    Status:   true,
})

func assemble(b *buffer.SharedBuffer, fout *os.File, in chan int, wg *sync.WaitGroup) {
    wg.Add(1)
    defer wg.Done()

    buf := make([]byte, buffer.BUFFSIZE*2)

    for i := range in {
        if fout != nil {
            b.Lock()
            _, err := b.Read(buf[:i])
            b.Unlock()
            if err == io.EOF {
                continue
            }
            if err != nil {
                panic(err)
            }
            n, err := fout.Write(buf[:i])
            if err != nil {
                panic(err)
            }
            if n != i {
                fmt.Printf("failed to write all bytes to file: %v != %v", n, i)
                panic(err)
            }
        }
    }
}
```

Seems like I might be missing something with the inner workings of gRPC?

答:
If I get it right, you are reading the input stream within one goroutine and dispatch the bytes to a second goroutine. Why don't you let the second goroutine handle the stream entirely? In this way the first goroutine is free to process the following streams, if any.

Typically the pattern is to have one goroutine that listens for incoming requests and spawns new goroutines for handling them. It is crutial that the main goroutine does not call any blocking API, besides the one to listen for requests.

For example:

```<code>for {
    newStream := ListenForStreams() //Block until next stream
    go consumeStream(newStream)
}
</code>```

Title: gRPC slow bandwidth to remote server

Body:
I have a gRPC service that transfers files from a local machine to a remote server, and I'm noticing some significant bandwidth issues. On average, it's downloading at about 1mb/s with one connection sharing several streams (usually about 8).

The server uses TLS to encryption, but that doesn't seem to be the bottleneck, as turning off TLS has negligible effect on the performance. I've also tried using iperf3 to test the bandwidth directly between the client and the server, and it resulted in 10mb/s.

Connecting to host <host>, port <port>
[  7] local 10.0.0.112 port 59651 connected to <ip> port <port>
[ ID] Interval           Transfer     Bitrate
[  7]   0.00-1.00   sec  1.28 MBytes  10.7 Mbits/sec
[  7]   1.00-2.00   sec   894 KBytes  7.35 Mbits/sec
[  7]   2.00-3.00   sec   999 KBytes  8.17 Mbits/sec
[  7]   3.00-4.00   sec  1.19 MBytes  10.0 Mbits/sec
[  7]   4.00-5.00   sec   753 KBytes  6.17 Mbits/sec
[  7]   5.00-6.00   sec  1.16 MBytes  9.67 Mbits/sec
[  7]   6.00-7.00   sec  1.00 MBytes  8.44 Mbits/sec
[  7]   7.00-8.00   sec  1.26 MBytes  10.5 Mbits/sec
[  7]   8.00-9.00   sec  1.22 MBytes  10.2 Mbits/sec
[  7]   9.00-10.00  sec  1.15 MBytes  9.66 Mbits/sec
- - - - - - - - - - - - - - - - - - - - - - - - -
[ ID] Interval           Transfer     Bitrate
[  7]   0.00-10.00  sec  10.8 MBytes  9.09 Mbits/sec                  sender
[  7]   0.00-10.00  sec  10.7 MBytes  8.95 Mbits/sec                  receiver

The upload bandwidth from the client is about 10mb/s, and the download of the server is about 50mb/s (via speedtest-cli)

traceroute doesn't show anything interesting either...

traceroute to mikemeredith.ddns.net (108.52.111.249), 64 hops max, 72 byte packets
 1  10.0.0.1 (10.0.0.1)  2.195 ms  5.388 ms  1.385 ms
 2  <ip>  (<ip>)  8.256 ms  145.115 ms  19.025 ms
 3  <ip2> (<ip2>)  9.951 ms  9.471 ms  141.929 ms
 4  <ip3> (<ip3>)  18.389 ms  9.684 ms  12.248 ms
 5  <ip4> (<ip4>)  143.880 ms  25.077 ms  10.606 ms
 6  ae-13-ar01.capitolhghts.md.bad.comcast.net (68.87.168.61)  142.567 ms  137.153 ms  20.790 ms
 7  be-33657-cr02.ashburn.va.ibone.comcast.net (68.86.90.57)  14.326 ms  144.076 ms  22.957 ms
 8  be-1102-cs01.ashburn.va.ibone.comcast.net (96.110.32.169)  13.881 ms  144.756 ms  23.981 ms
 9  be-2107-pe07.ashburn.va.ibone.comcast.net (96.110.32.186)  20.203 ms  94.433 ms  23.034 ms
10  n-a.gw12.iad8.alter.net (152.179.50.205)  20.254 ms  278.023 ms  31.660 ms
11  * * *
12  <ip12> (<ip13>)  66.277 ms  39.229 ms  34.543 ms
13  <ip13> (<ip14>)  48.849 ms  49.300 ms  49.546 ms

Here's the actual code

Client Connection:

creds, err := credentials.NewClientTLSFromFile(cerLoc, "")
if err != nil {
    fmt..Printf("failed to get tls from file: %v\n", err)
    panic(err)
}
conn, err = grpc.Dial(host+port, grpc.WithTransportCredentials(creds))

Client Stream:

ctx, cancel := context.WithCancel(context.Background())
defer cancel()
client := proto.Client(conn)
stream, err := client.BackupFiles(ctx, grpc.UseCompressor(gzip.Name))
// Send on stream, max size of message is 2mb

Server Listening:

// Start serving on port
l, err := net.Listen("tcp", port)
if err != nil {
    fmt.Printf("error listening on port %v: %v\n", port, err)
    panic(err)
}

var s *grpc.Server
creds, err := credentials.NewServerTLSFromFile(
    certLoc,
    keyLoc,
)
if err != nil {
    fmt.Printf("error getting tls certs: %v\n", err)
    panic(err)
}
s = grpc.NewServer(grpc.Creds(creds))
proto.RegisterBackupServer(s, &server{})
err = s.Serve(l)

// Actual stream handling

// Get a pooled SharedBuffer for assembling the file
b := getBuffer()
defer putBuffer(b)
c := make(chan int, []50)
u, _ := user.Current()

uid := uuid.New()
fout, err := os.Create(filePath + uid.String())
if err != nil {
    fmt.Println("error creating staging file: ", err)
    panic(err)
}
var wg sync.WaitGroup

go assemble(b, fout, c, &wg)
for {
    in, err := stream.Recv()
    if err == io.EOF {
        break
    }
    if err != nil {
        fmt.Println("encountered an error receiving on stream: ", err)
        return err
    }

    bytesWritten = b.LockWrite(in.Payload) // This buffer is shared between the stream and the go routine

    c <- bytesWritten
}

close(c)
wg.Wait()

_ = fout.Close()

// This is a pre-declared workerpool that basically moves files around
wp.Submit(func() {
    finalizeFile(fout.Name(), name, perms, "", checkSum, userID)
})

return stream.SendAndClose(&proto.Resp{
    Status:   true,
})

func assemble(b *buffer.SharedBuffer, fout *os.File, in chan int, wg *sync.WaitGroup) {
    wg.Add(1)
    defer wg.Done()

    buf := make([]byte, buffer.BUFFSIZE*2)

    for i := range in {
        if fout != nil {
            b.Lock()
            _, err := b.Read(buf[:i])
            b.Unlock()
            if err == io.EOF {
                continue
            }
            if err != nil {
                panic(err)
            }
            n, err := fout.Write(buf[:i])
            if err != nil {
                panic(err)
            }
            if n != i {
                fmt.Printf("failed to write all bytes to file: %v != %v", n, i)
                panic(err)
            }
        }
    }
}

Seems like I might be missing something with the inner workings of gRPC?

Body:
If I get it right, you are reading the input stream within one goroutine and dispatch the bytes to a second goroutine. Why don't you let the second goroutine handle the stream entirely? In this way the first goroutine is free to process the following streams, if any.

Typically the pattern is to have one goroutine that listens for incoming requests and spawns new goroutines for handling them. It is crutial that the main goroutine does not call any blocking API, besides the one to listen for requests.

For example:

for {
    newStream := ListenForStreams() //Block until next stream
    go consumeStream(newStream)
}


问:
How can I install XGBoost package in python on Windows
I tried to install XGBoost package in python.
I am using windows os, 64bits . I have gone through following.

The package directory states that xgboost is unstable for windows and is disabled:
pip installation on windows is currently disabled for further invesigation, please install from github.
https://pypi.python.org/pypi/xgboost/

I am not well versed in Visual Studio, facing problem building XGBoost.
I am missing opportunities to utilize xgboost package in data science.

Please guide, so that I can import the XGBoost package in python.

Thanks

答:
The following command should work but, If you have a problem with  this command

conda install -c conda-forge xgboost

First activate your environment . Assume your environment is named
simply write in conda terminal :

```<code>activate <MY_ENV>
</code>```

and then

```<code> pip install xgboost
</code>```

ContentLicense: CC BY-SA 3.0

Body:
The following command should work but, If you have a problem with  this command

conda install -c conda-forge xgboost

First activate your environment . Assume your environment is named
simply write in conda terminal :

activate <MY_ENV>

and then

 pip install xgboost


问:
UnhandledPromiseRejectionWarning NodeJS
I am trying to fix my error but I don't know how I can fix it. I have searched arround the internet and tried some solutions like this Node UnhandledPromiseRejectionWarning but I didn't manage to fix it.

This is my error

And this is my code

```<code>var express = require('express')
var session = require('express-session')
var bodyParser = require('body-parser')
var request = require('request-promise')
var mongoose = require('mongoose')

require('dotenv').config()

mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true })

var citySchema = new mongoose.Schema({
    name: String
})

var cityModel = mongoose.model('City', citySchema)

async function collectWeather(cities) {
    var weatherData = []
    for (var city_object of cities) {
        var city = city_object.name
        var url = `http://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&appid=e`
        request(url)
        var body = await request(url)
        var weatherJSON = JSON.parse(body)
        var weather = {
        city: city,
        temperature: Math.round(weatherJSON.main.temp),
        description: weatherJSON.weather[0].description,
        icon: weatherJSON.weather[0].icon,
        }
        weatherData.push(weather)
    }
    return weatherData
}

express()
    .use(express.static('static'))
    .use(bodyParser.urlencoded({extended: true}))
    .use(session({
        resave: false,
        saveUninitialized: true,
        secret: process.env.SESSION_SECRET
    }))

    .set('view engine', 'ejs')
    .set('views', 'view')

    .get('/', function(req, res) {
        cityModel.find({}, function(err, cities) {
            collectWeather(cities).then(function(result) {
                var weatherData = {weatherData: result}
                res.render('index', weatherData)
            })
        })
    })

    .post('/', function(req, res) {
        var newCity = new cityModel({name: req.body.city_name})
        newCity.save()
        res.redirect('/')
    })

    .listen(4000)
</code>```

I am still a beginner with node.js.

Thank you in advance.

答:
You should always catch your promises, you missed that here</p>

```<code>collectWeather(cities).then(function(result) {
    var weatherData = {weatherData: result}
    res.render('index', weatherData)
}).catch(err => {

    //res.render('error', err)
})
</code>```

Title: UnhandledPromiseRejectionWarning NodeJS

Body:
I am trying to fix my error but I don't know how I can fix it. I have searched arround the internet and tried some solutions like this Node UnhandledPromiseRejectionWarning but I didn't manage to fix it.

This is my error

And this is my code

var express = require('express')
var session = require('express-session')
var bodyParser = require('body-parser')
var request = require('request-promise')
var mongoose = require('mongoose')

require('dotenv').config()

mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true })

var citySchema = new mongoose.Schema({
    name: String
})

var cityModel = mongoose.model('City', citySchema)

async function collectWeather(cities) {
    var weatherData = []
    for (var city_object of cities) {
        var city = city_object.name
        var url = `http://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&appid=e`
        request(url)
        var body = await request(url)
        var weatherJSON = JSON.parse(body)
        var weather = {
        city: city,
        temperature: Math.round(weatherJSON.main.temp),
        description: weatherJSON.weather[0].description,
        icon: weatherJSON.weather[0].icon,
        }
        weatherData.push(weather)
    }
    return weatherData
}

express()
    .use(express.static('static'))
    .use(bodyParser.urlencoded({extended: true}))
    .use(session({
        resave: false,
        saveUninitialized: true,
        secret: process.env.SESSION_SECRET
    }))

    .set('view engine', 'ejs')
    .set('views', 'view')

    .get('/', function(req, res) {
        cityModel.find({}, function(err, cities) {
            collectWeather(cities).then(function(result) {
                var weatherData = {weatherData: result}
                res.render('index', weatherData)
            })
        })
    })

    .post('/', function(req, res) {
        var newCity = new cityModel({name: req.body.city_name})
        newCity.save()
        res.redirect('/')
    })

    .listen(4000)

I am still a beginner with node.js.

Thank you in advance.

Body:
You should always catch your promises, you missed that here

collectWeather(cities).then(function(result) {
    var weatherData = {weatherData: result}
    res.render('index', weatherData)
}).catch(err => {

    //res.render('error', err)
})


问:
How to find URLs that starts with "/" and contain "php"?
I have a 95MB XML file of content that is going from an old CMS (Drupal via Wordpress) to a new CMS (Squarespace).

The Squarespace import process keeps breaking & it appears to come down to links that attempt to execute PHP in the new server.

For example:

During the import process the new CMS recognises this as an internal link & tries to execute that URL to import the content, treats it as an attack or attempt at code injection & shuts down the process.

So I want a way of finding URLs that start with "/" & contain "php" so I can remove them.

I should be clear I only want to identify internal links & not external links to other sites.

Is this possible via Regex? I'd really like to avoid writing script to do this if I can just plug a Regex statement into Atom & Find/Replace.

答:
Yes this is possible whith Regex. Try with this one:

```<code>(\/*)[\w.]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\(\)\*\+,;=.]+\b.php\b
</code>```

It will be match all possible charakters for valid URL.

Body:
Yes this is possible whith Regex. Try with this one:

(\/*)[\w.]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\(\)\*\+,;=.]+\b.php\b

It will be match all possible charakters for valid URL.


问:
How can I pass more parameters to a custom sort() function?
I have an array of objects I need to sort on a custom function. Since I want to do this several times on several object attributes, I'd like to pass the key name for the attribute dynamically into the custom sort function:

```<code>function compareOnOneFixedKey(a, b) {
    a = parseInt(a.oneFixedKey)
    b = parseInt(b.oneFixedKey)
    if (a < b) return -1
    if (a > b) return 1
        return 0
}

arrayOfObjects.sort(compareByThisKey)
</code>```

This should become something like:

```<code>function compareOnKey(key, a, b) {
    a = parseInt(a[key])
    b = parseInt(b[key])
    if (a < b) return -1
    if (a > b) return 1
        return 0
}
arrayOfObjects.sort(compareOn('myKey'))
</code>```

Can this be done in a convenient way?

答:
const objArr = [{
    name: 'Z',
    age: 0
  }, {
    name: 'A',
    age: 25
  }, {
    name: 'F',
    age: 5
}]

const sortKey = {
    name: 'name',
    age: 'age'
}

const sortArr = (arr, key) => {
    return arr.sort((a, b) => {
        return a[key]  b[key] ? 1 : 0
    })
}

console.log("sortKey.name: ", sortArr(objArr, sortKey.name))
console.log("sortKey.age: ", sortArr(objArr, sortKey.age))```

Body:
I have an array of objects I need to sort on a custom function. Since I want to do this several times on several object attributes, I'd like to pass the key name for the attribute dynamically into the custom sort function:

function compareOnOneFixedKey(a, b) {
    a = parseInt(a.oneFixedKey)
    b = parseInt(b.oneFixedKey)
    if (a  b) return 1
        return 0
}

arrayOfObjects.sort(compareByThisKey)

This should become something like:

function compareOnKey(key, a, b) {
    a = parseInt(a[key])
    b = parseInt(b[key])
    if (a  b) return 1
        return 0
}
arrayOfObjects.sort(compareOn('myKey'))

Can this be done in a convenient way?

Body:
const objArr = [{
    name: 'Z',
    age: 0
  }, {
    name: 'A',
    age: 25
  }, {
    name: 'F',
    age: 5
}]

const sortKey = {
    name: 'name',
    age: 'age'
}

const sortArr = (arr, key) => {
    return arr.sort((a, b) => {
        return a[key] < b[key] ? -1 : a[key] > b[key] ? 1 : 0
    })
}

console.log("sortKey.name: ", sortArr(objArr, sortKey.name))
console.log("sortKey.age: ", sortArr(objArr, sortKey.age))


问:
ASP.NET w/ VB.NET - MultiSelect on ListBox Or CheckBoxList w/ AutoPostback enabled
Background: I have a winForm app that registers a user in the database based on the user input provided in the form, auto-generates a random password and username for the user, and e-mails the user a link to take an application based on the marketing company selected.

Problem:
I got the bundles listbox to populate w/ autopostback set to true but the bundles listbox populates as soon as you click on an lbcarrier and it doesn't allow you select more than one carrier.

Do you have any ideas on how to allow multiselect with the postback feature on?

Here's a screenshot of the interface:

code on default.aspx:

```<code>        <td class="style1">
            Carriers:</td>
        <td bgcolor="#ffffff" class="style2">
            <asp:ListBox AutoPostback="true" ID="lbCarriers" runat="server" Height="86px" Width="250px">
            </asp:ListBox>
                </td>
            </tr>

        <td class="style1">
            Bundles:</td>
        <td bgcolor="#ffffff" class="style2">
            <asp:ListBox ID="bundles" runat="server" Height="86px" Width="250px">
            </asp:ListBox>
                </td>
            </tr>
</code>```

code on default.aspx.vb:

```<code>Protected Sub lbCarriers_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles lbCarriers.SelectedIndexChanged

    Dim splt() As String
    Dim ac1 As Array
    bundles.Items.Clear()
    Dim item As ListItem = lbCarriers.SelectedItem
    splt = item.ToString().Split("|")
    ac1 = proxy.GetContractingBundles("test", "test", Trim(splt(0)))
    For Each Pitem In ac1
        bundles.Items.Add(Trim(splt(2)) & " | " & Pitem.FormBundleName)
    Next
End Sub
</code>```

Thanks for looking!

答: Easiest fix would be to turn AutoPostBack off, and change the SelectionMode as suggested. Then have a button, Get Bundles. In that click event you can add your code to retrieve the bundles based off of the Carrier listbox.

Body:
Background: I have a winForm app that registers a user in the database based on the user input provided in the form, auto-generates a random password and username for the user, and e-mails the user a link to take an application based on the marketing company selected.

Problem:
I got the bundles listbox to populate w/ autopostback set to true but the bundles listbox populates as soon as you click on an lbcarrier and it doesn't allow you select more than one carrier.

Do you have any ideas on how to allow multiselect with the postback feature on?

Here's a screenshot of the interface:

code on default.aspx:

            Carriers:

            <asp:ListBox AutoPostback="true" ID="lbCarriers" runat="server" Height="86px" Width="250px">
            </asp:ListBox>

            Bundles:

            <asp:ListBox ID="bundles" runat="server" Height="86px" Width="250px">
            </asp:ListBox>

code on default.aspx.vb:

Protected Sub lbCarriers_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles lbCarriers.SelectedIndexChanged

    Dim splt() As String
    Dim ac1 As Array
    bundles.Items.Clear()
    Dim item As ListItem = lbCarriers.SelectedItem
    splt = item.ToString().Split("|")
    ac1 = proxy.GetContractingBundles("test", "test", Trim(splt(0)))
    For Each Pitem In ac1
        bundles.Items.Add(Trim(splt(2)) & " | " & Pitem.FormBundleName)
    Next
End Sub

Thanks for looking!


问:
Can I run a VBA macro to run SQL queries I have saved in a MS Access database?
I spent alot of time to create 24 different separate MS Access queries that I have saved in the MS Access database.  They have to be run in a specific order.

I want to run a macro that will just execute them one after another.

I know I can do this using VBA but I have copy all the SQL into VBA one at a time.

is there a way I can just have VBA run the saved queries in the MS Access database without copying them into VBA?

I am very good with SQL. 15+ years doing Oracle work,  Code writing, DB Tuning, Data DBA work.

I am new to using SQL and VBA to run against MS Access DB.

答:
In its very simplest form, you can define a Sub such as:

Sub ExecuteQueries()
    With CurrentDb
        .Execute "MyQuery1"
        .Execute "MyQuery2"
        '...
        .Execute "MyQueryN"
    End With
End Sub
```

Or define this as a Function in a public module if you intend to invoke this from an MS Access Macro.

Body:
In its very simplest form, you can define a Sub such as:

Sub ExecuteQueries()
    With CurrentDb
        .Execute "MyQuery1"
        .Execute "MyQuery2"
        '...
        .Execute "MyQueryN"
    End With
End Sub

Or define this as a Function in a public module if you intend to invoke this from an MS Access Macro.


问:
What does the Date(0000,00,00) function equal in a SQL environment?
I am converting a Crystal Report into a SQL query. I have an IF statement in Crystal where

```<code>if {loanview.FUNDING_DATE} <> Date(0000,00,00)....
</code>```

Is Date(0000,00,00) a current date? Because I see a CurrentDate function as well

答:
After some googling, I found this following definition of Date(0000,00,00)-

The special “zero” date '0000-00-00' can be stored and retrieved as
  '0000-00-00'. When a '0000-00-00' date is used through Connector/ODBC,
  it is automatically converted to NULL because ODBC cannot handle that
  kind of date. ... MySQL permits you to store dates where the day or
  month and day are zero.

To me, it might be a checking which is something like-

```<code>if {loanview.FUNDING_DATE} <> NULL
BEGIN
    --Place necessary operation when the date is not NULL
END
</code>```

Note: This is not a confirmed solution/answer. I just sharing my opinion and you can implement the above logic in SQL and check both part - Report and Query output shows same result or not.

Body:
I am converting a Crystal Report into a SQL query. I have an IF statement in Crystal where

if {loanview.FUNDING_DATE} <> Date(0000,00,00)....

Is Date(0000,00,00) a current date? Because I see a CurrentDate function as well

Body:
After some googling, I found this following definition of Date(0000,00,00)-

The special “zero” date '0000-00-00' can be stored and retrieved as
  '0000-00-00'. When a '0000-00-00' date is used through Connector/ODBC,
  it is automatically converted to NULL because ODBC cannot handle that
  kind of date. ... MySQL permits you to store dates where the day or
  month and day are zero.

To me, it might be a checking which is something like-

if {loanview.FUNDING_DATE} <> NULL
BEGIN
    --Place necessary operation when the date is not NULL
END

Note: This is not a confirmed solution/answer. I just sharing my opinion and you can implement the above logic in SQL and check both part - Report and Query output shows same result or not.


问:
Oracle INSTR replacement in SQLite
I'm currently porting part of an application from an Oracle to a SQLite backend (Java, using plain JDBC). One Oracle-specific feature often being used is the INSTR function with three arguments:

INSTR(<string>, <search-string>, <position>)

This function searches within a string for a search string starting from a certain position. The third parameter can either be positive or negative. If it's negative, the search works backwards starting at the end of the string.

This function isn't available in SQLite and the best I could come up with is an alternative by nesting some other functions:

If <position> is positive:

LENGTH(<string>) - LENGTH(SUBSTR(SUBSTR(<string>,
  <position>), STRPOS(SUBSTR(<string>, <position>),
  <search-string>) + 1))

If <position> is negative (in our case -1 is the only negative value being used):

LENGTH(<string>) - LENGTH(REPLACE(<string>,
  RTRIM(<string>, REPLACE(<string>, <search-string>,
  '')), ''))

This seems to be giving the desired result, but you can see why I'm not really in favor of this approach. Certainly because in the original syntax the INSTR is used a lot and is being nested as well. It becomes a disaster for maintenance afterwards.

Is there a more elegant approach or could I be missing some other native solution for what seems to be a rather trivial task?

答:
SQL

```<code>   CASE WHEN position = 0
        THEN INSTR(string, substring)
        WHEN position > 0
        THEN INSTR(SUBSTR(string, position), substring) + position - 1
        WHEN position < 0
        THEN LENGTH(RTRIM(REPLACE(string,
                                  substring,
                                  REPLACE(HEX(ZEROBLOB(LENGTH(substring))),
                                          '00',
                                          '¬')),
                          string)) - LENGTH(substring) + 1
   END
</code>```

It assumes the ¬ character won't be part of the search string (but in the unlikely event this assumption is false could of course be changed to a different rarely used character).

SQLFiddle Demo

Some worked examples here: http://sqlfiddle.com/#!5/7e40f9/5

Credits

The positive position method was adapted from Tim Biegeleisen's answer. (But a zero value needs to be handled separately).

The negative position method used the method described in this question as a starting point.

The creation of a string consisting of a character repeated n times was taken from this simplified answer.

Title: Oracle INSTR replacement in SQLite

Body:
SQL

   CASE WHEN position = 0
        THEN INSTR(string, substring)
        WHEN position > 0
        THEN INSTR(SUBSTR(string, position), substring) + position - 1
        WHEN position < 0
        THEN LENGTH(RTRIM(REPLACE(string,
                                  substring,
                                  REPLACE(HEX(ZEROBLOB(LENGTH(substring))),
                                          '00',
                                          '¬')),
                          string)) - LENGTH(substring) + 1
   END

It assumes the ¬ character won't be part of the search string (but in the unlikely event this assumption is false could of course be changed to a different rarely used character).

SQLFiddle Demo

Some worked examples here: http://sqlfiddle.com/#!5/7e40f9/5

Credits

The positive position method was adapted from Tim Biegeleisen's answer. (But a zero value needs to be handled separately).

The negative position method used the method described in this question as a starting point.

The creation of a string consisting of a character repeated n times was taken from this simplified answer.


问:
How do I write to the log streaming service
Sorry for such a stupid simple question but how do I get info to appear in the log streaming service below the code on the develop tab.

It seems pretty straight forward to setup with verbose when you look at the info page

https://learn.microsoft.com/en-us/azure/app-service-web/web-sites-streaming-logs-and-console

But then none of these do anything...

```<code>System.Diagnostics.Trace.TraceInformation("My trace statement");
System.Diagnostics.Trace.TraceWarning("My warning statement");
System.Diagnostics.Trace.TraceError("My error statement");
</code>```

答:
I think you have to put this under <system.web> in your web.config file:

```<code><trace enabled="true" writeToDiagnosticsTrace="true" localOnly="false" mostRecent="true" pageOutput="false" />
</code>```

Body:
Sorry for such a stupid simple question but how do I get info to appear in the log streaming service below the code on the develop tab.

It seems pretty straight forward to setup with verbose when you look at the info page

https://learn.microsoft.com/en-us/azure/app-service-web/web-sites-streaming-logs-and-console

But then none of these do anything...

System.Diagnostics.Trace.TraceInformation("My trace statement");
System.Diagnostics.Trace.TraceWarning("My warning statement");
System.Diagnostics.Trace.TraceError("My error statement");

Body:
I think you have to put this under <system.web> in your web.config file:

<trace enabled="true" writeToDiagnosticsTrace="true" localOnly="false" mostRecent="true" pageOutput="false" />


问:
Problem with jquery button click
I am facing a problem in the jquery click event.

My web page involves creating a button through javascript and assigning a class to the button ( call it A ). Now I want to detect the click of that button and I have written the following code for it :

```
 $(".A").click( function () {

    // do something

 });
```

To my surprise, this click event never gets called.

But when I make the button statically on the webpage ( during design time ), the same code works.

Is there a different approach to bind a button click with jquery in case a button is created dynamically?

答:
Have a look at the live() jquery method to automatically wire up events to new elements. Or, as you create the new button, attach the new click event.

```<code>var newbutton = $('<input type="button" value="click me"/>');
somediv.append(newbutton);
newbutton.click(yourhandler);
</code>```

Title: Problem with jquery button click

Body:
I am facing a problem in the jquery click event.

My web page involves creating a button through javascript and assigning a class to the button ( call it A ). Now I want to detect the click of that button and I have written the following code for it :

 $(".A").click( function () {

    // do something

 });

To my surprise, this click event never gets called.

But when I make the button statically on the webpage ( during design time ), the same code works.

Is there a different approach to bind a button click with jquery in case a button is created dynamically?

Body:
Have a look at the live() jquery method to automatically wire up events to new elements. Or, as you create the new button, attach the new click event.

var newbutton = $('<input type="button" value="click me"/>');
somediv.append(newbutton);
newbutton.click(yourhandler);


问:
Selection.addRange() is deprecated - How to solve error
Seeking the net brought me to Selection.addRange() is deprecated and will be removed from Chrome

But this is a bit to broad. I get this error because i have included some bootstrap into my project. Now for me "Range" means [from A to Z] or [from START to END]

Reading the above posted post tells me the trick to solve the problem is to call removeAllRanges(); befor addRange(..); But reading removeALLranges let me suggest that several ranges or values can be added.

I tried to add removeAllRanges(); in between and it brought me several more errors because if i add a range (start) i have to add a second one (end).

Actually its not a range, its more the parameter to set in addRange.

Here is the code in some of bootstrap generated file that causes the issue

```<code>(function() {
    var iframe = document.createElement("iframe");
    body.appendChild(iframe);

    var iframeDoc = dom.getIframeDocument(iframe);
    iframeDoc.open();
    iframeDoc.write("<html><head></head><body>12</body></html>");
    iframeDoc.close();

    var sel = dom.getIframeWindow(iframe).getSelection();
    var docEl = iframeDoc.documentElement;
    var iframeBody = docEl.lastChild, textNode = iframeBody.firstChild;

    // Test whether the native selection will allow a collapsed selection within a non-editable element
    var r1 = iframeDoc.createRange();
    r1.setStart(textNode, 1);
    r1.collapse(true);
    sel.addRange(r1);
    collapsedNonEditableSelectionsSupported = (sel.rangeCount == 1);
    sel.removeAllRanges();

    // Test whether the native selection is capable of supporting multiple ranges
    var r2 = r1.cloneRange();
    r1.setStart(textNode, 0);
    r2.setEnd(textNode, 2);
    sel.addRange(r1);
    sel.addRange(r2);

    selectionSupportsMultipleRanges = (sel.rangeCount == 2);

    // Clean up
    r1.detach();
    r2.detach();

    body.removeChild(iframe);
})();
</code>```

The problem part here is

```<code>sel.removeAllRanges();

var r2 = r1.cloneRange();
r1.setStart(textNode, 0);
r2.setEnd(textNode, 2);
sel.addRange(r1);
sel.addRange(r2);      //<<============ HERE
</code>```

of course i need the second range to let

```<code>selectionSupportsMultipleRanges = (sel.rangeCount == 2);
</code>```

work!

How can i solve this ?

Is there a way to add a real range insead of only a start parameter ?

答:
If you want to have a range (start to end) you can do something like:

```<code>let range = document.createRange()
range.setStart(r1);
range.setEnd(r2);
let range2 ....

let sel = window.getSelection()
selection.removeAllRanges();
selection.addRange(range);
selection.addRange(range2);
....
</code>```

I would look here:

https://developer.mozilla.org/en-US/docs/Web/API/Range
https://developer.mozilla.org/en-US/docs/Web/API/Selection/addRange

for more info on ranges.

Hope this answers your question (even if it's late).

Body:
Seeking the net brought me to Selection.addRange() is deprecated and will be removed from Chrome

But this is a bit to broad. I get this error because i have included some bootstrap into my project. Now for me "Range" means [from A to Z] or [from START to END]

Reading the above posted post tells me the trick to solve the problem is to call removeAllRanges(); befor addRange(..); But reading removeALLranges let me suggest that several ranges or values can be added.

I tried to add removeAllRanges(); in between and it brought me several more errors because if i add a range (start) i have to add a second one (end).

Actually its not a range, its more the parameter to set in addRange.

Here is the code in some of bootstrap generated file that causes the issue

(function() {
    var iframe = document.createElement("iframe");
    body.appendChild(iframe);

    var iframeDoc = dom.getIframeDocument(iframe);
    iframeDoc.open();
    iframeDoc.write("12");
    iframeDoc.close();

    var sel = dom.getIframeWindow(iframe).getSelection();
    var docEl = iframeDoc.documentElement;
    var iframeBody = docEl.lastChild, textNode = iframeBody.firstChild;

    // Test whether the native selection will allow a collapsed selection within a non-editable element
    var r1 = iframeDoc.createRange();
    r1.setStart(textNode, 1);
    r1.collapse(true);
    sel.addRange(r1);
    collapsedNonEditableSelectionsSupported = (sel.rangeCount == 1);
    sel.removeAllRanges();

    // Test whether the native selection is capable of supporting multiple ranges
    var r2 = r1.cloneRange();
    r1.setStart(textNode, 0);
    r2.setEnd(textNode, 2);
    sel.addRange(r1);
    sel.addRange(r2);

    selectionSupportsMultipleRanges = (sel.rangeCount == 2);

    // Clean up
    r1.detach();
    r2.detach();

    body.removeChild(iframe);
})();

The problem part here is

sel.removeAllRanges();

var r2 = r1.cloneRange();
r1.setStart(textNode, 0);
r2.setEnd(textNode, 2);
sel.addRange(r1);
sel.addRange(r2);      //<<============ HERE

of course i need the second range to let

selectionSupportsMultipleRanges = (sel.rangeCount == 2);

work!

How can i solve this ?

Is there a way to add a real range insead of only a start parameter ?

Body:
If you want to have a range (start to end) you can do something like:

let range = document.createRange()
range.setStart(r1);
range.setEnd(r2);
let range2 ....

let sel = window.getSelection()
selection.removeAllRanges();
selection.addRange(range);
selection.addRange(range2);
....

I would look here:

https://developer.mozilla.org/en-US/docs/Web/API/Range
https://developer.mozilla.org/en-US/docs/Web/API/Selection/addRange

for more info on ranges.

Hope this answers your question (even if it's late).


问:
Laravel PDO Settings?
I would like to return INT as integers from my database. At the moment all values are loaded as Strings. Database is MSSQL 2012 and I use the PDO driver (for v5.6).

Trying to set the properties here (as shown here on fideloper.com, but I don't know if that's still possible):

```<code>   'sqlsrv' => [
        'driver'   => 'sqlsrv',
        'charset'  => 'utf8',
        'prefix'   => '',
         ......
        'options'   => array(
            PDO::ATTR_STRINGIFY_FETCHES => false,
            PDO::ATTR_EMULATE_PREPARES => false,
        ),
    ],
</code>```

But always getting an error:

```<code>SQLSTATE[IMSSP]: The given attribute is only supported on the PDOStatement object.
</code>```

How can I set any settings for the PDO Driver to return INT as Integers and not as Strings.

This is still not working:

```<code> $pdo = DB::connection()->getPdo();
 $pdo->setAttribute(PDO::ATTR_STRINGIFY_FETCHES, false);
 $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
 .. do ORM Query
</code>```

Bringing the same error.

Maybe anyone can help me?

答:
If anyone is here looking on how to get the SQLSRV PDO driver to return decimal or money values as floats in PHP - unfortunately this isn't possible:

Formatting Decimal Strings and Money Values (PDO_SQLSRV Driver)

To preserve accuracy, decimal or numeric types are always fetched as
  strings with exact precisions and scales. If any value is less than 1,
  the leading zero is missing. It is the same with money and smallmoney
  fields as they are decimal fields with a fixed scale equal to 4.

https://learn.microsoft.com/en-us/sql/connect/php/formatting-decimals-pdo-sqlsrv-driver?view=sql-server-2017

Title: Laravel PDO Settings?

Body:
I would like to return INT as integers from my database. At the moment all values are loaded as Strings. Database is MSSQL 2012 and I use the PDO driver (for v5.6).

Trying to set the properties here (as shown here on fideloper.com, but I don't know if that's still possible):

   'sqlsrv' => [
        'driver'   => 'sqlsrv',
        'charset'  => 'utf8',
        'prefix'   => '',
         ......
        'options'   => array(
            PDO::ATTR_STRINGIFY_FETCHES => false,
            PDO::ATTR_EMULATE_PREPARES => false,
        ),
    ],

But always getting an error:

SQLSTATE[IMSSP]: The given attribute is only supported on the PDOStatement object.

How can I set any settings for the PDO Driver to return INT as Integers and not as Strings.

This is still not working:

 $pdo = DB::connection()->getPdo();
 $pdo->setAttribute(PDO::ATTR_STRINGIFY_FETCHES, false);
 $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
 .. do ORM Query

Bringing the same error.

Maybe anyone can help me?


问:
Use OR instead of AND in GraphQL boolean expression query
I am populating a table using graph QL query :

The graphql query looks like :

```<code>const DESSERT_QUERY = gql`
    query DESSERT_QUERY($where: dessert_bool_exp) {
      dessert(where: $where) {
        name
        calories
        fat
        carbs
      }
    }
  `;
</code>```

Query Variables :

```<code>{"where":
    {
    "name": {
      "_in": ["xyz"]
    },
    "calories": {
      "_eq": 1
    },
     "fat": {
      "_eq": 606
    },
    "carbs": {
      "_eq": 1
    },
    }
}
</code>```

How to implement an OR query.

Any guidance is appreciated. Thanks

答:
```<code>The correct GraphQL Query Variables is :

 {"where":
        {
        "name": {
          "_in": ["xyz"]
        },
        "calories": {
          "_eq": 1
        },
        "_or": [{"fat": {
          "_eq": 606
        }},
         {"carbs": {
          "_eq": 1
        }}]
    }
}
</code>```

Body:
I am populating a table using graph QL query :

The graphql query looks like :

const DESSERT_QUERY = gql`
    query DESSERT_QUERY($where: dessert_bool_exp) {
      dessert(where: $where) {
        name
        calories
        fat
        carbs
      }
    }
  `;

Query Variables :

{"where":
    {
    "name": {
      "_in": ["xyz"]
    },
    "calories": {
      "_eq": 1
    },
     "fat": {
      "_eq": 606
    },
    "carbs": {
      "_eq": 1
    },
    }
}

How to implement an OR query.

Any guidance is appreciated. Thanks


问:
Kotlin getParcelableArray from intent bundle not able to cast it to custom type
I am running into a weird problem . I have a class A which implements Parcelable interface in kotlin.

I am passing the array of class A from one activity to another no issues here.

```<code> var arrayOfA:Array<A> // just to tell the type assume the array is initialised with the value
 intent.putExtra("array", arrayOfA)
</code>```

But while receiving it in another activity , I am not able to assign it to variable of type Array it is asking me to assign it to Array when A is on type parcelable why I am not able to assign it the variable.

```<code>in second Activity
var arrayOfA:Array<A>?=null

arrayA=intent.get("array") as Array<A> // Problem here. Class cast exception
</code>```

I am not able to understand why. Can some one help me here. I don't want to change the type of variable to Array as it as many inter depedencies.(The class here is just a demonstration)

========================================

```<code>class A(val a:String?,val b:String?):Parcelable {
    constructor(parcel: Parcel) : this(
            parcel.readString(),
            parcel.readString()) {
    }

    override fun writeToParcel(parcel: Parcel, flags: Int) {
        parcel.writeString(a)
        parcel.writeString(b)
    }

    override fun describeContents(): Int {
        return 0
    }

    companion object CREATOR : Parcelable.Creator<A> {
        override fun createFromParcel(parcel: Parcel): A {
            return A(parcel)
        }

        override fun newArray(size: Int): Array<A?> {
            return arrayOfNulls(size)
        }
    }
}
</code>```

答:
Bundle.getParcelableArray (and Intent.getParcelableArrayExtra) return Parcelable[]. You can't cast Parcelable[] as MyClass[]. You can cast an element of Parcelable[] as MyClass.

Use Bundle.getParcelableArrayList (or its Intent counterpart) instead, because it has a generic type.

```<code>var values: List<MyClass> = listOf(...)
intent.putParcelableArrayListExtra("key", values.asArrayList())
values = intent.getParcelableArrayListExtra("key")!!

fun <E> List<E>.asArrayList(): ArrayList<E> = this as? ArrayList<E> ?: ArrayList(this)
</code>```

Body:
I am running into a weird problem . I have a class A which implements Parcelable interface in kotlin.

I am passing the array of class A from one activity to another no issues here.

 var arrayOfA:Array // just to tell the type assume the array is initialised with the value
 intent.putExtra("array", arrayOfA)

But while receiving it in another activity , I am not able to assign it to variable of type Array it is asking me to assign it to Array when A is on type parcelable why I am not able to assign it the variable.

in second Activity
var arrayOfA:Array?=null

arrayA=intent.get("array") as Array // Problem here. Class cast exception

I am not able to understand why. Can some one help me here. I don't want to change the type of variable to Array as it as many inter depedencies.(The class here is just a demonstration)

========================================

class A(val a:String?,val b:String?):Parcelable {
    constructor(parcel: Parcel) : this(
            parcel.readString(),
            parcel.readString()) {
    }

    override fun writeToParcel(parcel: Parcel, flags: Int) {
        parcel.writeString(a)
        parcel.writeString(b)
    }

    override fun describeContents(): Int {
        return 0
    }

    companion object CREATOR : Parcelable.Creator {
        override fun createFromParcel(parcel: Parcel): A {
            return A(parcel)
        }

        override fun newArray(size: Int): Array {
            return arrayOfNulls(size)
        }
    }
}

Body:
Bundle.getParcelableArray (and Intent.getParcelableArrayExtra) return Parcelable[]. You can't cast Parcelable[] as MyClass[]. You can cast an element of Parcelable[] as MyClass.

Use Bundle.getParcelableArrayList (or its Intent counterpart) instead, because it has a generic type.

var values: List<MyClass> = listOf(...)
intent.putParcelableArrayListExtra("key", values.asArrayList())
values = intent.getParcelableArrayListExtra("key")!!

fun <E> List<E>.asArrayList(): ArrayList<E> = this as? ArrayList<E> ?: ArrayList(this)


问:
How to find the furthest point from other given points in Java
I have a given S point (red on the graph) and n other points (black on the graph). I want to find a point P, in a distance of 1 from S, which is the furthest from all the black points (in this case - the sum of distances between P and each point should is the highest).

As P is 1 away from S, we can tell that y = √(1 - x^2).

The analitical way I would personally use would be to:

Calculate the sum of the distances

Q - P = √((Qx - Sx - x)^2 + (Qy - Sy - √(1 - x^2))^2) (repeat of all n points and sum up),

Calculate the derivative of the obtained expression,

Calculate roots of the derivative and find maximums (in the domain),

Calculate values at the ends of the intervals in the domain,

Choose the correct X.

What would be the most efficient way to do this in Java and what libraries could be used? I heard about libraries allowing to do this analyticaly, but it sounds complicated and slow so I was searching for any numerical ideas, but couldn't find any.

答:
First of all, it seems that O(N^2) is not so bad in the worst case for this problem. Because each call to cost function costs O(N). Consider this situation: N black points, which lie on another circle (R > 1, center in S) and split this new circle into N equal arcs. In this symmetric case, we have N maximums. Just to check them it takes O(N^2) — compute cost function in each point. So I think any algorithm which examines all local extremums will have at least O(N^2) in the worst case.

Here my solution sketch for general case:

If {Q_j} are black points, let`s define {O_j} so that each O_j is the closest point to Q_j which lies on the red circle around S. Points {O_j} split the circle into n arcs. We can calculate each O_j coords easily.

It seems that cost function which we are trying to optimize has only one local extremum within each arc (this part need more accurate proof), so we could find these extremums by ternary search -- linearithmic complexity. We need to check O_j for local extremums as well -- linear complexity.

Totally, we have to check O(NlogN) points, each check costs O(N). At least this method is more convenient than checking every point on circle with small epsilon.


问:
Bootstrap 4 img-circle class doesn't seem to exist
I'm writing a website in HTML5 and Bootstrap 4 and I'm trying to turn a square image into a circle. In Bootstrap 3 this was easily do-able with .img-circle, but now I can't seem to get it to work and I can't find any answers online.
Has Bootstrap dropped the img-circle class or is my code messed up?

It goes something like this:

```<code><!-- Within a tab-content div -->
<div class="col-xs-7">
    <img src="img/gallery2.JPG" class="img-circle" alt="HelPic">
</div>
</code>```

Hope somebody can help me out :)

答:
Now the class is this

 ```

Body:
I'm writing a website in HTML5 and Bootstrap 4 and I'm trying to turn a square image into a circle. In Bootstrap 3 this was easily do-able with .img-circle, but now I can't seem to get it to work and I can't find any answers online.
Has Bootstrap dropped the img-circle class or is my code messed up?

It goes something like this:

Hope somebody can help me out :)

Body:
Now the class is this

 <img src="img/img5.jpg" width="200px" class="rounded-circle float-right">


问:
Neural network to figure out the meaning of user input
I'm trying to make a neural network try to figure out the meaning of input(keyboard keys in this case) according to the user.

I have multiple possible output "commands" that the NN can interpret the inputs to mean, and at each state certain outputs can count as beneficial while others are a detriment

When the NN starts up for the first time, no input should have any particular meaning to it but as time goes on I want the NN to be able to figure out what the user most likely meant.

I've tried a Multilayer perceptron NN that has as many input nodes as there are physical inputs and as many output nodes as there are commands and a number of nodes equal to the sum of the other two layers as a single hidden layer, in this case it is then a 5,15,10.

The NN assumes that the user will only make moves that are in the NN's best interest.

So far it seems the NN is just figuring out what is the command it can take that will most likely result in a beneficial move, regardless of the input key rather than trying to figure out what key should result in what move according to the user.

Because of this I'm wondering (most likely wrong) if I should produce a separate NN for each input to try and figure out the current output according to the user.

Is there a different type of NN I should look into that will work better, and is there a recommended configuration for this problem?
I'll be happy with some recommendations of reading material that would help in this particular problem.

I'm at best an amateur in NN and would like to learn a lot more about the whole field, But I'm trying to focus my efforts on this problem for now.

答: Accordng to me you want the output to be according to behaviour of the player as number of inputs are more than in actual case. So according to me there should be some type of memory for the actions taken by the player in order to find the patterns.This can be done using Long Short term Memory.


问:
How to fabricate ASPX POST request
I'm battling with this for days, I have an ASPX page that has a file upload control and an upload button, and no matter what I do, I can't get the page to accept the automated POST request.

The request body is as follows (all newlines CRLF), all UTF8 == ANSII (no spec chars right now)

```<code>-----------------------------8cdc74445fc88d0
Content-Disposition: form-data; name="btnUpload"

Upload
-----------------------------8cdc74445fc88d0
Content-Disposition: form-data; name="ctrFileUpload"; filename="myfile.txt"
Content-Type: text/plain

This is a test!

-----------------------------8cdc74445fc88d0--
</code>```

The form has multiple buttons, so I need to kinda fill the file upload, and press the upload button. But this doesn't seem to work.

The same page works just fine from a web browser, although, in that scenario there is a viewstate garbage as one of the parts. I tried EnableViewState="false", ValidateRequest="false", EnableSessionState="ReadOnly", but the garbage part is still there when I use the browser.

Am I missing something? Tried studying the RFC and everything, but nothing seems to work.

答:
POST request is post request - it is same for browser and other applications. All you need to accomplish post is set http verb (method) when creating request. If you use .net as request generator from your application, this can be done by setting HttpWebRequest.Method Property. There're also examples there

Aaaaargh, everything is clear now.
There're no 'events' in http. Asp.net webforms introduced this(and many others) approach to make developing on web easier as i believe for those who had found difficult to program on web because of http statelessness or were bound to windows development. Asp.net webforms make web development much more like windows development. As i mentioned - there're no events in http protocol. So, asp.net uses viewstate garbage and its dopostbackwithoptions function to bind http client side clicks to server side events. That's why your automated post does not work - when that viewstate garbage is missing, webforms engine has no chance to bind to events. You should handle web request otherwise  - without relying on events

Title: How to fabricate ASPX POST request

Body:
I'm battling with this for days, I have an ASPX page that has a file upload control and an upload button, and no matter what I do, I can't get the page to accept the automated POST request.

The request body is as follows (all newlines CRLF), all UTF8 == ANSII (no spec chars right now)

-----------------------------8cdc74445fc88d0
Content-Disposition: form-data; name="btnUpload"

Upload
-----------------------------8cdc74445fc88d0
Content-Disposition: form-data; name="ctrFileUpload"; filename="myfile.txt"
Content-Type: text/plain

This is a test!

-----------------------------8cdc74445fc88d0--

The form has multiple buttons, so I need to kinda fill the file upload, and press the upload button. But this doesn't seem to work.

The same page works just fine from a web browser, although, in that scenario there is a viewstate garbage as one of the parts. I tried EnableViewState="false", ValidateRequest="false", EnableSessionState="ReadOnly", but the garbage part is still there when I use the browser.

Am I missing something? Tried studying the RFC and everything, but nothing seems to work.


问:
Is it possible to Decompile and read an SSIS package code?
I am working on a project which was owned by a different person. He created a job to update bunch of fields in handful of tables in SQL server. That job was based on an SSIS package. Now I have the DTSX file and the disabled job. When I tried to enable the job after changing the old credentials in the DTSX file, I am getting weird errors. I want to see the code behind the SSIS package and want to see how the update process is coded.
Is there a way to do this?</p>

答:
DTSX files are just XML files. Just rename to xml, and open with an editor.

The query is a string that is built up via string concatenation.


问:
(Angular2) Cannot read property 'extend' of undefined for toastr
I'm trying to use toastr in angularjs 2 as a service which will be injected in my component as mentioned below. When the handleEvent function is called i'm receiving "Cannot read property 'extend' of undefined". Any suggestions and/or explanation for the error is much appreciated.

app.moudle.ts has imported ToastrService and ToastrService has been added in providers.

```<code>//events/events-list.components.ts

import { ToastrService } from '../common/toastr.service';
@Component ({
    selector: 'event-list',
    template: `
    <div>
        <h1> Upcoming Angular 2 Event </h1>
        <hr>
        <div class="row">
            <div *ngFor="let event_data of all_data" class="col-md-5">
                <event-thumbnail (click)="handleEvent(event_data.name)" [event]="event_data"></event-thumbnail>
    </div>
            </div>
        </div>
    `
})

export class EventListComponent implements OnInit {
  all_data:any[]
  constructor(private eventService : EventService , private toastr : ToastrService ){
    //moved code from here to ngOnInit
  }

  ngOnInit(){
    this.all_data = this.eventService.getEvents();
  }

  handleEvent(eventName) {
    console.log("hey here  "+eventName);
    this.toastr.success(eventName);
  }
}
</code>```

Error:

[ This error is thrown after the console.log output ]

EXCEPTION: Error in ./EventListComponent class EventListComponent -
  inline template:6:16 caused by: Cannot read property 'extend' of
  undefined.
              ORIGINAL EXCEPTION: Cannot read property 'extend' of undefined

             TypeError: Cannot read property 'extend' of undefined
      at m (toastr.js:411)
      at Object.s [as success] (toastr.js:85)
      at ToastrService.success (toastr.service.ts:12)

答:
Also bootstrap.min.css should bet loaded before toastr.min.js.

Environments: Angular 7 and bootstrap 4.

Below is my part of angular.json, and it is working.

```<code>   "styles": [
      "node_modules/ngf-bootstrap/dist/bootstrap.min.css",
      "node_modules/toastr/build/toastr.min.css",
      "src/styles.css"
    ],
    "scripts": [
      "node_modules/jquery/dist/jquery.min.js",
      "node_modules/bootstrap/dist/js/bootstrap.js",
      "node_modules/toastr/build/toastr.min.js"
    ]
</code>```

Body:
I'm trying to use toastr in angularjs 2 as a service which will be injected in my component as mentioned below. When the handleEvent function is called i'm receiving "Cannot read property 'extend' of undefined". Any suggestions and/or explanation for the error is much appreciated.

app.moudle.ts has imported ToastrService and ToastrService has been added in providers.

//events/events-list.components.ts

import { ToastrService } from '../common/toastr.service';
@Component ({
    selector: 'event-list',
    template: `

 Upcoming Angular 2 Event

                <event-thumbnail (click)="handleEvent(event_data.name)" [event]="event_data"></event-thumbnail>

    `
})

export class EventListComponent implements OnInit {
  all_data:any[]
  constructor(private eventService : EventService , private toastr : ToastrService ){
    //moved code from here to ngOnInit
  }

  ngOnInit(){
    this.all_data = this.eventService.getEvents();
  }

  handleEvent(eventName) {
    console.log("hey here  "+eventName);
    this.toastr.success(eventName);
  }
}

Error:

[ This error is thrown after the console.log output ]

EXCEPTION: Error in ./EventListComponent class EventListComponent -
  inline template:6:16 caused by: Cannot read property 'extend' of
  undefined.
              ORIGINAL EXCEPTION: Cannot read property 'extend' of undefined

             TypeError: Cannot read property 'extend' of undefined
      at m (toastr.js:411)
      at Object.s [as success] (toastr.js:85)
      at ToastrService.success (toastr.service.ts:12)

Body:
Also bootstrap.min.css should bet loaded before toastr.min.js.

Environments: Angular 7 and bootstrap 4.

Below is my part of angular.json, and it is working.

   "styles": [
      "node_modules/ngf-bootstrap/dist/bootstrap.min.css",
      "node_modules/toastr/build/toastr.min.css",
      "src/styles.css"
    ],
    "scripts": [
      "node_modules/jquery/dist/jquery.min.js",
      "node_modules/bootstrap/dist/js/bootstrap.js",
      "node_modules/toastr/build/toastr.min.js"
    ]


问:
How to do na_values when creating pandas dataframe from Google BigQuery
I had used pd.read_csv(my_csv, na_values=['N/A', '--']) such that string 'N/A' and '--' get interpreted as NULL, NaN, etc.

But if I used BigQuery client, I couldn't figure how to achieve the same feat. I read the quick help from .to_dataframe() which "Return a pandas DataFrame from a QueryJob" but it didn't seem to take in any extra argument.

Is this possible? Or I have to do my own custom post-processing to track missing values?

答:
If you are running some query before getting its results in to the dataframe, you can easily do it on the BigQuery side without worrying about filtering your results on the client side.

Something like IF(column in ('N\A', '--'), null, column) as column should do the job for you.