问:
Mouse listener throws no errors but doesn't fire (java)
I am following code I found on geeksforgeeks but the mouse listener isn't firing. I suspect that somehow the implementation of runnable is locking access to my board object, but I'm not sure. I'm in a similar boat to the OP of this post.

```<code>public class Game extends Canvas implements MouseListener {

    JFrame jf = new JFrame();

    Game() {
        jf.getContentPane().add(this, BorderLayout.CENTER);
        jf.setSize(new Dimension(500,500+30));
        jf.setVisible(true);
        jf.addMouseListener(this);
    }

    public void mouseClicked(MouseEvent e){
        System.out.println("Hello World!");
    }

    public void mousePressed(MouseEvent e){}

    public void mouseReleased(MouseEvent e){}

    public void mouseEntered(MouseEvent e){}

    public void mouseExited(MouseEvent e){}

    public static void main(String[] args){
        Game game = new Game();
    }
}
</code>```

I suspect but doubt that the mouse listener may not be functioning properly due to it being created in a non-static method, but I doubt that that is the problem. I've tried moving the declaration to the beginning of the constructor, but that didn't help.

答:
The events will only register on the component which has focus. Which, in your program is your main panel, the Game class. So a quick fix would be just to change:

```<code> jf.addMouseListener(this);
</code>```

to

```<code>addMouseListener(this);
</code>```

But you should add the listener to any component you might want to get the events on, i.e. your main panel, the content pane, and jframe too.

Body:
I am following code I found on geeksforgeeks but the mouse listener isn't firing. I suspect that somehow the implementation of runnable is locking access to my board object, but I'm not sure. I'm in a similar boat to the OP of this post.

public class Game extends Canvas implements MouseListener {

    JFrame jf = new JFrame();

    Game() {
        jf.getContentPane().add(this, BorderLayout.CENTER);
        jf.setSize(new Dimension(500,500+30));
        jf.setVisible(true);
        jf.addMouseListener(this);
    }

    public void mouseClicked(MouseEvent e){
        System.out.println("Hello World!");
    }

    public void mousePressed(MouseEvent e){}

    public void mouseReleased(MouseEvent e){}

    public void mouseEntered(MouseEvent e){}

    public void mouseExited(MouseEvent e){}

    public static void main(String[] args){
        Game game = new Game();
    }
}

I suspect but doubt that the mouse listener may not be functioning properly due to it being created in a non-static method, but I doubt that that is the problem. I've tried moving the declaration to the beginning of the constructor, but that didn't help.

Body:
The events will only register on the component which has focus. Which, in your program is your main panel, the Game class. So a quick fix would be just to change:

 jf.addMouseListener(this);

to

addMouseListener(this);

But you should add the listener to any component you might want to get the events on, i.e. your main panel, the content pane, and jframe too.


来源: stackexchange

问:
From date to tuple Python
I have like input: 12/12/2019
and I want this output: (12,12,2019)
I tried this code but it doesn't work because they consider "/" as a division :

```<code>date= 12/12/2019
date=str(date).split("/")
print(tuple(date))
</code>```

答:
```<code>date= "12/12/2019"
date=str(date).split("/")
print(tuple(date))
</code>```

Should work. Without the quotes you are sunk, but I assume you are getting these from somewhere.

ContentLicense: CC BY-SA 4.0

Title: From date to tuple Python

Body:
I have like input: 12/12/2019
and I want this output: (12,12,2019)
I tried this code but it doesn't work because they consider "/" as a division :

date= 12/12/2019
date=str(date).split("/")
print(tuple(date))

Body:
date= "12/12/2019"
date=str(date).split("/")
print(tuple(date))

Should work. Without the quotes you are sunk, but I assume you are getting these from somewhere.


问:
Open a local file in Colabrotory Python Jupyter Notebook on a Chromebook
As the title suggests, I am working in a Jupyter Notebook, using Google's Colaborotory.  I want to open a local file (meaning actually stored on my machine, not somewhere in cloudland) using IPython.  I have tried a number of formats for the file name, but have not hit upon a format that does not result in the error, e.g.

```<code>[Errno 2] No such file or directory: file:///media/removable/HamRadio/COS/AI/mnist_test_10.csv
</code>```

I have searched around but haven't found any reference work that specifies how to accomplish this.  Any direction is appreciated.

答: You need to upload your file to Google Colab first then you right-click on file and choose copy file path

Body:
As the title suggests, I am working in a Jupyter Notebook, using Google's Colaborotory.  I want to open a local file (meaning actually stored on my machine, not somewhere in cloudland) using IPython.  I have tried a number of formats for the file name, but have not hit upon a format that does not result in the error, e.g.

[Errno 2] No such file or directory: file:///media/removable/HamRadio/COS/AI/mnist_test_10.csv

I have searched around but haven't found any reference work that specifies how to accomplish this.  Any direction is appreciated.


问:
How to access and store a particular object from a json file in c#
I am trying to make a multi-subject quiz game for children using unity3D and questions and answers are stored in a json file. Now i want to create an object named "science" and "maths" and want to store their respective questions in them and when i want to access science i could loop and find and just store the science question in my string instead of reading the whole json file.

here is my json file.

```<code>    Science ={
    "CourseName":"Science",
    "No_Of_Ques":4,
    "Ques_Data":[
                  { "Quesion":"which is the biggest planet in the solar system?",
                    "Answer":"jupiter",
                    "options":["mars","earth","venus","jupiter"]
                  },

                  { "Quesion":"How many planets are there in solar system?",
                    "Answer":"Eight",
                    "options":["Seven","Nine","Five","Eight"]
                  },

                  { "Quesion":"which is the closest planet to the sun?",
                    "Answer":"mercury",
                    "options":["mars","saturn","venus","mercury"]
                  },

                  { "Quesion":"How many moons does jupiter have?",
                    "Answer":"12",
                    "options":["5","13","9","12"]
                  }
                ]
}
</code>```

and this is how i have been acessing it so far

```<code>path = Application.dataPath + "/QnA.json";
    string json = File.ReadAllText(path);
    Course c1 = JsonUtility.FromJson<Course>(json);

    return c1;
</code>```

Course and needed serializable Classes:

```<code>[Serializable] public class Course
{
    public string CourseName;
    public string No_Of_Ques;
    public QnA[] Ques_Data;
}

[Serializable]
public class QnA
{
    public string Quesion;
    public string Answer;
    public string[] options;
}
</code>```

i have tried so many things like Deserialization and Jobject asset but none of them seem to work and every implementation that i have found on the internet has the json data in the same file as the c# code but i can not do that as my json contains hundreds of lines of data. kindly help me out a little.

答:
Create a course class in which create getter and setter functions for all of your json keys, for example:

if your json file is like that:

```<code>[
  {
    "CourseName": "Science",
    "No_Of_Ques": 1,
    ...
  },
  {
    "CourseName": "Math",
    "No_Of_Ques": 1,
    ...
  }
]
</code>```

then course class should be:

```<code>public class Course
    {
        public string CourseName { get; set; }
        public int No_Of_Ques { get; set; }
    }
</code>```

In your main class or anywhere you can access your selected course, here i am using only 0 index of a json, you can also loop through whole json and find your desirable course.

StreamReader to read a file

convert it to json

Deserialize the json as per your course

Console it

```<code>    using (StreamReader r = new StreamReader("../../../js.json"))
    {
        string json = r.ReadToEnd();
        List<Course> ro = JsonSerializer.Deserialize<List<Course>>(json);
        Console.WriteLine(ro[0].CourseName);
    }
</code>```

I added json file in the same dire where my mainClass file is, as StreamReader requires an absolute path therefore I used an absoulte path for my json file.

```<code>using (StreamReader r = new StreamReader("../../../js.json"))
</code>```

Require Libs

```<code>using System;
using System.Collections.Generic;
using System.IO;
using System.Text.Json;
</code>```

Note: I created a console app, not sure your app type

Body:
I am trying to make a multi-subject quiz game for children using unity3D and questions and answers are stored in a json file. Now i want to create an object named "science" and "maths" and want to store their respective questions in them and when i want to access science i could loop and find and just store the science question in my string instead of reading the whole json file.

here is my json file.

    Science ={
    "CourseName":"Science",
    "No_Of_Ques":4,
    "Ques_Data":[
                  { "Quesion":"which is the biggest planet in the solar system?",
                    "Answer":"jupiter",
                    "options":["mars","earth","venus","jupiter"]
                  },

                  { "Quesion":"How many planets are there in solar system?",
                    "Answer":"Eight",
                    "options":["Seven","Nine","Five","Eight"]
                  },

                  { "Quesion":"which is the closest planet to the sun?",
                    "Answer":"mercury",
                    "options":["mars","saturn","venus","mercury"]
                  },

                  { "Quesion":"How many moons does jupiter have?",
                    "Answer":"12",
                    "options":["5","13","9","12"]
                  }
                ]
}

and this is how i have been acessing it so far

path = Application.dataPath + "/QnA.json";
    string json = File.ReadAllText(path);
    Course c1 = JsonUtility.FromJson<Course>(json);

    return c1;

Course and needed serializable Classes:

[Serializable] public class Course
{
    public string CourseName;
    public string No_Of_Ques;
    public QnA[] Ques_Data;
}

[Serializable]
public class QnA
{
    public string Quesion;
    public string Answer;
    public string[] options;
}

i have tried so many things like Deserialization and Jobject asset but none of them seem to work and every implementation that i have found on the internet has the json data in the same file as the c# code but i can not do that as my json contains hundreds of lines of data. kindly help me out a little.

Body:
Create a course class in which create getter and setter functions for all of your json keys, for example:

if your json file is like that:

[
  {
    "CourseName": "Science",
    "No_Of_Ques": 1,
    ...
  },
  {
    "CourseName": "Math",
    "No_Of_Ques": 1,
    ...
  }
]

then course class should be:

public class Course
    {
        public string CourseName { get; set; }
        public int No_Of_Ques { get; set; }
    }

In your main class or anywhere you can access your selected course, here i am using only 0 index of a json, you can also loop through whole json and find your desirable course.

StreamReader to read a file

convert it to json

Deserialize the json as per your course

Console it

    using (StreamReader r = new StreamReader("../../../js.json"))
    {
        string json = r.ReadToEnd();
        List<Course> ro = JsonSerializer.Deserialize<List<Course>>(json);
        Console.WriteLine(ro[0].CourseName);
    }

I added json file in the same dire where my mainClass file is, as StreamReader requires an absolute path therefore I used an absoulte path for my json file.

using (StreamReader r = new StreamReader("../../../js.json"))

Require Libs

using System;
using System.Collections.Generic;
using System.IO;
using System.Text.Json;

Note: I created a console app, not sure your app type


问:
Javascript - Loop string until null character found
I want to iterate through a string until a null character is found (\0), like how we do in C language. I have listed down the steps which I have tried below.

```<code>let exampleValue = 'abcdef';
let i = 0;

// Trial 1
while (exampleValue[i] !== '\0') {
  i++;
  // This seems to go on infinitely
}

// Trial 2
while (exampleValue[i] !== '\0'.charCodeAt(0)) {
  i++;
  // This seems to go on infinitely
}

// Trial 3
while (exampleValue[i] !== \0) {
  i++;
  // This throws an invalid character error
}

// Trial 4
while (exampleValue[i] !== undefined) {
  i++;
  // This seems to work
}
</code>```

Based on the above samples, Trial 4 seems to work. Can I continue using Trial 4 for my desired output or is there a better way to solve my problem?

EDIT:
I apologize for not specifying my problem, I want to print each letter of the string by iterating through it without using exampleValue.length

EDIT 2:
After I read tadman's comment, I got to know Javascript's do not terminate their string using a null character but instead it stores it's keeps track of it characters and stores the length seperately.

答:
You are getting these cases because you will never get an '\0' in your string so the loop will run infinitely.

And the last case is working fine because after the last character of your string, the next character will be undefined.

Now, if you want to loop through the string then you can do it this way:

let exampleValue = 'abcdef';
  let i = 0;

  while (i < exampleValue.length ) {
    console.log(exampleValue[i]);
    i++;
  }```

Body:
I want to iterate through a string until a null character is found (\0), like how we do in C language. I have listed down the steps which I have tried below.

let exampleValue = 'abcdef';
let i = 0;

// Trial 1
while (exampleValue[i] !== '\0') {
  i++;
  // This seems to go on infinitely
}

// Trial 2
while (exampleValue[i] !== '\0'.charCodeAt(0)) {
  i++;
  // This seems to go on infinitely
}

// Trial 3
while (exampleValue[i] !== \0) {
  i++;
  // This throws an invalid character error
}

// Trial 4
while (exampleValue[i] !== undefined) {
  i++;
  // This seems to work
}

Based on the above samples, Trial 4 seems to work. Can I continue using Trial 4 for my desired output or is there a better way to solve my problem?

EDIT:
I apologize for not specifying my problem, I want to print each letter of the string by iterating through it without using exampleValue.length

EDIT 2:
After I read tadman's comment, I got to know Javascript's do not terminate their string using a null character but instead it stores it's keeps track of it characters and stores the length seperately.


答:
In order for that to work you need to input the date as a string using "" or '' characters.</p>

```<code>date = '12/12/2019'
date_split = date.split('/')
date_tuple = tuple(date_split)
print(date_tuple)
</code>```

Title: From date to tuple Python

Body:
In order for that to work you need to input the date as a string using "" or '' characters.

date = '12/12/2019'
date_split = date.split('/')
date_tuple = tuple(date_split)
print(date_tuple)


问:
Async/await func in another async/await func in Node.js, MongoDB
I am trying to search available objects of a MongoDB collection(e.g. ParkingSpot) using specific business logic, the problem is that inside this function which is an async/await func I am looking inside another collection with .find() which I use as an async/await as well. The second function doesn't execute and gets back as an promise " Promise {  } " and therefore the business logic is not applied. Can you help me please?
Here is 1st function:

```<code>exports.get_parkingSpots_avail_for_parking = async (req, res, next) => {
    try {
        const radius = req.body.radius;
        const userLatitude = req.body.userLatitude;
        const userLongitude = req.body.userLongitude;
        const reqStartDate = new Date(req.body.reqStartDate);
        const reqEndDate = new Date(req.body.reqEndDate);

        const parkingSpots = await ParkingSpot.find({
            isAvailable: true
        }, (err, parkingSpots) => {
            if (err) {
                return res.status(500).json({
                    error: err
                });
            }
            const freeParkingSpots = parkingSpots.filter(parkingSpot => {
                return distanceCalculator(parkingSpot.latitude, parkingSpot.longitude, userLatitude, userLongitude) < radius
            })
            const availParkingSpots = freeParkingSpots.filter( freeParkingSpot => {
               // console.log(freeParkingSpot._id);
                console.log(isParkingAvailable(reqStartDate, reqEndDate, freeParkingSpot._id));
                return isParkingAvailable(reqStartDate, reqEndDate, freeParkingSpot._id);
            })
        }).select('_id userId number address latitude longitude notes isAvailable startOfAvailability endOfAvailability');

        console.log(parkingSpots);
        if (parkingSpots.length > 0) {
            return res.status(200).json({
                parkingSpots: parkingSpots
            });
        }
        return res.status(404).json({
            message: "No available parking spots for requeste period"
        });

    } catch (err) {
        res.status(500).json({
            error: err
        })
    }
};
</code>```

```<code>Second function which is being called :
module.exports = async function isParkingAvailable(reqStartDate, reqEndDate, parkingSpotId) {
    const parkingSpotBookings =  await Booking.find({ parkingSpotId: parkingSpotId})
        .select('_id parkingSpotId sharerUserId renterUserId startDate endDate');
    if (parkingSpotBookings.length == 0) {
        return true;
    }
    parkingSpotBookings.filter(booking => {
        //console.log(parkingSpotId);
        //console.log("Is overlapping" +!isOverlapping(reqStartDate, reqEndDate, booking.startDate, booking.endDate));
        return !isOverlapping(reqStartDate, reqEndDate, booking.startDate, booking.endDate)
    })
}
</code>```

So the problem is that calling second function appears as that in console.log :Promise {  }

答:
Await will Return the result to your parkingSpot variable.
For the second function:
You have defined this function as an async, that means it is holding asynchronous process, and in Node JS es6 async process is processed as a promise, so if you won't call it with await it will return a promise only

```<code>exports.get_parkingSpots_avail_for_parking = async (req, res, next) => {
    try {
        const radius = req.body.radius;
        const userLatitude = req.body.userLatitude;
        const userLongitude = req.body.userLongitude;
        const reqStartDate = new Date(req.body.reqStartDate);
        const reqEndDate = new Date(req.body.reqEndDate);

        const parkingSpots = await ParkingSpot.find({isAvailable: true}).select('_id userId number address latitude longitude notes isAvailable startOfAvailability endOfAvailability');
        const freeParkingSpots = parkingSpots.filter(parkingSpot => {
            return distanceCalculator(parkingSpot.latitude, parkingSpot.longitude, userLatitude, userLongitude) < radius
        });
        const availParkingSpots = freeParkingSpots.filter( async freeParkingSpot => {
            /* You have defined this function as an async, that means it is holding asynchronous process, and in
Node JS es6 async process is processed as a promise, so if you won't call it with await it will return a promise only */
            return await isParkingAvailable(reqStartDate, reqEndDate, freeParkingSpot._id);
        });

        if (parkingSpots.length > 0) {
            return res.status(200).json({
                parkingSpots: parkingSpots
            });
        }
        return res.status(404).json({
            message: "No available parking spots for requeste period"
        });

    } catch (err) {
        res.status(500).json({
            error: err
        })
    }
};
</code>```

I hope it will help you.

Thank you

Body:
I am trying to search available objects of a MongoDB collection(e.g. ParkingSpot) using specific business logic, the problem is that inside this function which is an async/await func I am looking inside another collection with .find() which I use as an async/await as well. The second function doesn't execute and gets back as an promise " Promise {  } " and therefore the business logic is not applied. Can you help me please?
Here is 1st function:

exports.get_parkingSpots_avail_for_parking = async (req, res, next) => {
    try {
        const radius = req.body.radius;
        const userLatitude = req.body.userLatitude;
        const userLongitude = req.body.userLongitude;
        const reqStartDate = new Date(req.body.reqStartDate);
        const reqEndDate = new Date(req.body.reqEndDate);

        const parkingSpots = await ParkingSpot.find({
            isAvailable: true
        }, (err, parkingSpots) => {
            if (err) {
                return res.status(500).json({
                    error: err
                });
            }
            const freeParkingSpots = parkingSpots.filter(parkingSpot => {
                return distanceCalculator(parkingSpot.latitude, parkingSpot.longitude, userLatitude, userLongitude) < radius
            })
            const availParkingSpots = freeParkingSpots.filter( freeParkingSpot => {
               // console.log(freeParkingSpot._id);
                console.log(isParkingAvailable(reqStartDate, reqEndDate, freeParkingSpot._id));
                return isParkingAvailable(reqStartDate, reqEndDate, freeParkingSpot._id);
            })
        }).select('_id userId number address latitude longitude notes isAvailable startOfAvailability endOfAvailability');

        console.log(parkingSpots);
        if (parkingSpots.length > 0) {
            return res.status(200).json({
                parkingSpots: parkingSpots
            });
        }
        return res.status(404).json({
            message: "No available parking spots for requeste period"
        });

    } catch (err) {
        res.status(500).json({
            error: err
        })
    }
};

Second function which is being called :
module.exports = async function isParkingAvailable(reqStartDate, reqEndDate, parkingSpotId) {
    const parkingSpotBookings =  await Booking.find({ parkingSpotId: parkingSpotId})
        .select('_id parkingSpotId sharerUserId renterUserId startDate endDate');
    if (parkingSpotBookings.length == 0) {
        return true;
    }
    parkingSpotBookings.filter(booking => {
        //console.log(parkingSpotId);
        //console.log("Is overlapping" +!isOverlapping(reqStartDate, reqEndDate, booking.startDate, booking.endDate));
        return !isOverlapping(reqStartDate, reqEndDate, booking.startDate, booking.endDate)
    })
}

So the problem is that calling second function appears as that in console.log :Promise {  }

Body:
Await will Return the result to your parkingSpot variable.
For the second function:
You have defined this function as an async, that means it is holding asynchronous process, and in Node JS es6 async process is processed as a promise, so if you won't call it with await it will return a promise only

exports.get_parkingSpots_avail_for_parking = async (req, res, next) => {
    try {
        const radius = req.body.radius;
        const userLatitude = req.body.userLatitude;
        const userLongitude = req.body.userLongitude;
        const reqStartDate = new Date(req.body.reqStartDate);
        const reqEndDate = new Date(req.body.reqEndDate);

        const parkingSpots = await ParkingSpot.find({isAvailable: true}).select('_id userId number address latitude longitude notes isAvailable startOfAvailability endOfAvailability');
        const freeParkingSpots = parkingSpots.filter(parkingSpot => {
            return distanceCalculator(parkingSpot.latitude, parkingSpot.longitude, userLatitude, userLongitude) < radius
        });
        const availParkingSpots = freeParkingSpots.filter( async freeParkingSpot => {
            /* You have defined this function as an async, that means it is holding asynchronous process, and in
Node JS es6 async process is processed as a promise, so if you won't call it with await it will return a promise only */
            return await isParkingAvailable(reqStartDate, reqEndDate, freeParkingSpot._id);
        });

        if (parkingSpots.length > 0) {
            return res.status(200).json({
                parkingSpots: parkingSpots
            });
        }
        return res.status(404).json({
            message: "No available parking spots for requeste period"
        });

    } catch (err) {
        res.status(500).json({
            error: err
        })
    }
};

I hope it will help you.

Thank you


问:
Generating a list of uniquely name elements based on a for i in range statement
I have:

```<code>Number = 4
for i in range(1, Number):
    grwth = ('r'+'C')
print(grwth)
</code>```

But what I want is for 'rC' to have a unique name each time it is printed. So, if Number is entered to be 4, grwth should be a list of [rC, rC2, rC3, rC4] Like that. Is that possible to do ?

答:
Is that possible to do ?

Yep! Let's start by initializing grwth as a list and appending to it, rather than assigning:

```<code>number = 4
grwth = []
for i in range(1, number):
    grwth.append('r'+'C')
print(grwth)
</code>```

This results in ['rC', 'rC', 'rC']. The values are all the same because we're appending the same thing every time. But that variable i is accessible from inside our loop, so we can use it to append something different every time!

```<code>number = 4
grwth = []
for i in range(1, number):
    grwth.append('r'+'C'+str(i))
print(grwth)
</code>```

This gives us ['rC1', 'rC2', 'rC3']! Note that i is an integer, so we cast it to a number before appending. We could alternatively use any number of string formatting operations to create the string.

Note that there are any number of further improvements we could make to this code; we could use a list comprehension, tweak our use of range to be a little more intuitive, etc. But this should serve as a good starting point!

Body:
I have:

Number = 4
for i in range(1, Number):
    grwth = ('r'+'C')
print(grwth)

But what I want is for 'rC' to have a unique name each time it is printed. So, if Number is entered to be 4, grwth should be a list of [rC, rC2, rC3, rC4] Like that. Is that possible to do ?

Body:
Is that possible to do ?

Yep! Let's start by initializing grwth as a list and appending to it, rather than assigning:

number = 4
grwth = []
for i in range(1, number):
    grwth.append('r'+'C')
print(grwth)

This results in ['rC', 'rC', 'rC']. The values are all the same because we're appending the same thing every time. But that variable i is accessible from inside our loop, so we can use it to append something different every time!

number = 4
grwth = []
for i in range(1, number):
    grwth.append('r'+'C'+str(i))
print(grwth)

This gives us ['rC1', 'rC2', 'rC3']! Note that i is an integer, so we cast it to a number before appending. We could alternatively use any number of string formatting operations to create the string.

Note that there are any number of further improvements we could make to this code; we could use a list comprehension, tweak our use of range to be a little more intuitive, etc. But this should serve as a good starting point!


Title: From date to tuple Python


问:
Removing specific nested array key from request
I've run into a specific problem, where I need to remove specific nested array key from my request, so it doesn't store in my database. I created a Request class, and this is how I tried to accomplish this so far:

This is my data that I'm getting from request after form submit:

```<code>  "options" => array:2 [▼
    "product_options" => array:1 [▶]
    "additional_product_options" => array:1 [▼
      "Tenetur dolor labore" => null
    ]
  ]
</code>```

As you can see, additional_product_options array has a key with an empty value, and so I want to remove this key from array completely. I tried this using both unset() and array_filter(), but I'm not getting desired result. This is how I tried it so far:

```<code>if(isset($this->input('options')['additional_product_options'])){
            foreach ($this->input('options')['additional_product_options'] as $key => $val){
                if(is_null($key) || is_null($val)){ //Check for null values
                    unset($this->input('options')['additional_product_options'][$key]); //Remove key from array
                }
            }
        }
</code>```

After I dump my request with dd($this->options()), I'm still getting Tenetur dolor labore key in this array:

```<code>array:2 [▼
  "product_options" => array:1 [▼
    "Et sit id culpa rep" => "sdad,ads"
  ]
  "additional_product_options" => array:1 [▼
    "Tenetur dolor labore" => null
  ]
]
</code>```

With array_filter(), I'm still getting the same results:

```<code>if(isset($this->input('options')['additional_product_options'])){
     array_filter($this->input('options')['additional_product_options']);
}
</code>```

After dumping my data, the key is still here:

```<code>  "options" => array:2 [▼
    "product_options" => array:1 [▶]
    "additional_product_options" => array:1 [▼
      "Tenetur dolor labore" => null
    ]
  ]
</code>```

In ideal case,the Tenetur dolor labore key would be removed completely, and additional_product_options array would be empty. What am I doing wrong here?

答:
try this ... i have test it for current options array:

for test reason, i made the option array:

```<code>   $options = ['product_options' => ['additional_product_options' =>
['Tenetur dolor labore' => null]], 'additional_product_options' => 'some value'];
</code>```

then

```<code>  unset($options['product_options']['additional_product_options']['Tenetur dolor labore']);
</code>```

the result is removing the key as we want ...

Body:
I've run into a specific problem, where I need to remove specific nested array key from my request, so it doesn't store in my database. I created a Request class, and this is how I tried to accomplish this so far:

This is my data that I'm getting from request after form submit:

  "options" => array:2 [▼
    "product_options" => array:1 [▶]
    "additional_product_options" => array:1 [▼
      "Tenetur dolor labore" => null
    ]
  ]

As you can see, additional_product_options array has a key with an empty value, and so I want to remove this key from array completely. I tried this using both unset() and array_filter(), but I'm not getting desired result. This is how I tried it so far:

if(isset($this->input('options')['additional_product_options'])){
            foreach ($this->input('options')['additional_product_options'] as $key => $val){
                if(is_null($key) || is_null($val)){ //Check for null values
                    unset($this->input('options')['additional_product_options'][$key]); //Remove key from array
                }
            }
        }

After I dump my request with dd($this->options()), I'm still getting Tenetur dolor labore key in this array:

array:2 [▼
  "product_options" => array:1 [▼
    "Et sit id culpa rep" => "sdad,ads"
  ]
  "additional_product_options" => array:1 [▼
    "Tenetur dolor labore" => null
  ]
]

With array_filter(), I'm still getting the same results:

if(isset($this->input('options')['additional_product_options'])){
     array_filter($this->input('options')['additional_product_options']);
}

After dumping my data, the key is still here:

  "options" => array:2 [▼
    "product_options" => array:1 [▶]
    "additional_product_options" => array:1 [▼
      "Tenetur dolor labore" => null
    ]
  ]

In ideal case,the Tenetur dolor labore key would be removed completely, and additional_product_options array would be empty. What am I doing wrong here?

Body:
try this ... i have test it for current options array:

for test reason, i made the option array:

   $options = ['product_options' => ['additional_product_options' =>
['Tenetur dolor labore' => null]], 'additional_product_options' => 'some value'];

then

  unset($options['product_options']['additional_product_options']['Tenetur dolor labore']);

the result is removing the key as we want ...


问:
insertMany and replica set
I have a MongoDB db consisting of one PRIMARY and one SECONDARY instance (replica set) on the same server. When i execute a insertMany() command :

```<code>let docsArray = []
for(i = 0; i <= 7; i++){
   let docsArray.push(
       {something: i}
   );
}
await collection.insertMany(docsArray)
</code>```

something odd happens. My primary server saves the data in the correct order(the one I have specified) ,whereas the SECONDARY instance saves the docs in some random way. I have tried inserting the documents one by one throught creating a session and a loop:

```<code>for(i = 0; i <= 7; i++){
     let newDoc = something + i;
     await newDoc.save({session});
 }
</code>```

still give the same result. Why is that? Can the solution be something connected with the Write Concern? Thanks in advance!!!

答:
Documents in MongoDB collections are not ordered.

If you add some documents to a collection and execute a find without conditions on that collection, you might get the documents back in the order you inserted them or in a different order.

To get the documents in a particular order, request the order in the query.

Title: insertMany and replica set

Body:
I have a MongoDB db consisting of one PRIMARY and one SECONDARY instance (replica set) on the same server. When i execute a insertMany() command :

let docsArray = []
for(i = 0; i <= 7; i++){
   let docsArray.push(
       {something: i}
   );
}
await collection.insertMany(docsArray)

something odd happens. My primary server saves the data in the correct order(the one I have specified) ,whereas the SECONDARY instance saves the docs in some random way. I have tried inserting the documents one by one throught creating a session and a loop:

for(i = 0; i <= 7; i++){
     let newDoc = something + i;
     await newDoc.save({session});
 }

still give the same result. Why is that? Can the solution be something connected with the Write Concern? Thanks in advance!!!


问:
Docusign authentication type for polling
I am using an authorization code grant to create envelopes and listen events from webhook.
But I would like to use polling too.

Is the code grant Authentification a good solution to perform polling or I need to implement a JWT grant in addition?

答:
If you're using the Authorization Code Grant for polling, I would recommend the use of the extended scope in addition to signature. With extended you can keep generating new refresh tokens so that your authentication doesn't expire after 30 days.

Of course, Inbar outlines while polling in general is not a great idea.


问:
Invalid signal parameter type: MouseEvent
If I try and use a MouseEvent as an arg in a QML defined signal, I get the following error on load:

Invalid signal parameter type: MouseEvent

There is conflicting information in the Qt docs regarding this, in the QML signal syntax documentation it states that:

The allowed parameter types are the same as those listed under Defining Property Attributes [...] any QML object type can be used as a property type.

Whilst in the QML/C++ interaction documentation it states that:

When a QML object type is used as a signal parameter, the parameter should use var as the type

Setting the argument to use var does work, but this seems unnecessary according to the QML documentation.  There was a bug regarding this in the distant past but it was apparently resolved in v5.0.0.  So I am doing something wrong, or is this a regression?

Edit

A simple demonstration:

```<code>import QtQuick 2.3

Item {
    signal sig( MouseEvent mouse )
}
</code>```

答:
Use QtObject instead

```<code>signal sig(QtObject mouse)
</code>```

Note: This works because QtObject is plain QObject which is base of all Qt objects

Body:
If I try and use a MouseEvent as an arg in a QML defined signal, I get the following error on load:

Invalid signal parameter type: MouseEvent

There is conflicting information in the Qt docs regarding this, in the QML signal syntax documentation it states that:

The allowed parameter types are the same as those listed under Defining Property Attributes [...] any QML object type can be used as a property type.

Whilst in the QML/C++ interaction documentation it states that:

When a QML object type is used as a signal parameter, the parameter should use var as the type

Setting the argument to use var does work, but this seems unnecessary according to the QML documentation.  There was a bug regarding this in the distant past but it was apparently resolved in v5.0.0.  So I am doing something wrong, or is this a regression?

Edit

A simple demonstration:

import QtQuick 2.3

Item {
    signal sig( MouseEvent mouse )
}

Body:
Use QtObject instead

signal sig(QtObject mouse)

Note: This works because QtObject is plain QObject which is base of all Qt objects


问:
Google Analytics - gtag property
I have one GA account and multiple GA property in that account. The question, what's the Ideal set up in adding gtag? I know that each property has its own gtag code, so, should I use each gtag code and adde them in every webpage? The weird thing is, previous landing pages use one gtag code and it worked before in all the properties.

info.example.com
 (Account)

info.example.com
 (property)

info.example.co.uk
 (property)

info.example.hk (property)

答: Surely the tracking code must be present on all pages, then it depends on how you want to track. You can do it all within the same Property or in separate Properties.

Title: Google Analytics - gtag property


问:
Why does linking against static runtime libraries in Visual C++ 2008 still requires MSVCR71.dll at runtime?
I'm building a dll statically linked against the c runtime libraries. Why then does it require MSVCR71.dll at runtime?

答: msvcr71.dll is Visual C++ 2003's C runtime. If you're building with 2008, there's no reason there should be a reference to this DLL. My guess is that you depend on another DLL which was built with 2003, and which uses the dynamically linked runtime.

ContentLicense: CC BY-SA 3.0


问:
jconsole GUI not showing on OSX
I am using adoptopenjdk8 and trying to launch the jconsole GUI to attach to my java application.

I am running the jconsole like so

```<code>MBROWN-MBP:~ mark$ which jconsole
/usr/bin/jconsole
MBROWN-MBP:~ mark$ jconsole -debug
</code>```

This causes the application to open in the dock, but no GUI is opened so I cannot connect to my Java process.

I don't see any logs or output for the debug option to hint at what is going wrong.

答:
I have a cheesy workaround, but I don't know why this vanishing situation happens ... and want to know a real solution. If I use multiple monitors, I get the same situation - looks like it's launched on the dock, but it does not appear.

Workaround:
If I remove the monitor connections and launch JConsole, the JConsole window appears. From there, I then reattach the monitors and use JConsole. This workaround isn't ideal and is time consuming, but it's possible to use JConsole.

Title: jconsole GUI not showing on OSX

Body:
I am using adoptopenjdk8 and trying to launch the jconsole GUI to attach to my java application.

I am running the jconsole like so

MBROWN-MBP:~ mark$ which jconsole
/usr/bin/jconsole
MBROWN-MBP:~ mark$ jconsole -debug

This causes the application to open in the dock, but no GUI is opened so I cannot connect to my Java process.

I don't see any logs or output for the debug option to hint at what is going wrong.


问:
Omit factor variables in `huxreg`
I am running a regression in R with a lot of time and location fixed effects. I try to output a nice summary table into Latex. I switched from stargazer package to huxtable because stargazer does not behave consistently when omitting fixed effects (see this question).

Here is a simple example:

```<code>library(huxtable)

reg1 <- lm(mpg ~ disp, data = mtcars)
reg2 <- lm(mpg ~ disp + factor(gear) + factor(carb), data = mtcars)
huxreg(reg1, reg2)
</code>```

The output of huxreg is:

```<code>> huxreg(reg1, reg2)
────────────────────────────────────────────────────
                        (1)              (2)
                 ───────────────────────────────────
  (Intercept)          29.600 ***       25.533 ***
                       (1.230)          (2.996)
  disp                 -0.041 ***       -0.018
                       (0.005)          (0.011)
  factor(gear)4                          3.988
                                        (2.495)
  factor(gear)5                          5.391 *
                                        (2.591)
  factor(carb)2                         -1.979
                                        (1.667)
  factor(carb)3                         -4.161
                                        (2.131)
  factor(carb)4                         -6.199 *
                                        (2.221)
  factor(carb)6                         -8.557 *
                                        (3.653)
  factor(carb)8                        -10.389 *
                                        (4.268)
                 ───────────────────────────────────
  N                    32               32
  R2                    0.718            0.828
  logLik              -82.105          -74.186
  AIC                 170.209          168.372
────────────────────────────────────────────────────
  *** p < 0.001; ** p < 0.01; * p < 0.05.

Column names: names, model1, model2
</code>```

Here is the desired output:

```<code>────────────────────────────────────────────────────
                        (1)              (2)
                 ───────────────────────────────────
  (Intercept)          29.600 ***       25.533 ***
                       (1.230)          (2.996)
  disp                 -0.041 ***       -0.018
                       (0.005)          (0.011)
                 ───────────────────────────────────
  Gear FE                No               Yes
  Carb FE                No               Yes
                 ───────────────────────────────────
  N                    32               32
  R2                    0.718            0.828
  logLik              -82.105          -74.186
  AIC                 170.209          168.372
────────────────────────────────────────────────────
  *** p < 0.001; ** p < 0.01; * p < 0.05.

Column names: names, model1, model2
</code>```

I know I could simply edit the huxtable using add_rows(), but I am looking for a more robust solution that would allow to find rownames using regular expressions (like stargazer's omit.labels option).

答:
I wrote the answer myself, using this as inspiration.

The function check_factors() determines if the particular variables are present in the model, and then sapply() is used to create the rows that are added in the table. This is not fully automatic, though, since I still have to check if all the variables listed for omit_coef were later tested by check_factors(). It is possible to omit a variable and then forget to add a corresponding row.

```<code>library(huxtable)

reg1 <- lm(mpg ~ disp, data = mtcars)
reg2 <- lm(mpg ~ disp + factor(gear) + factor(carb), data = mtcars)
huxreg(reg1, reg2)

gear_factors <- tidy(reg2) %>%
  filter(str_detect(term, "factor\\(gear\\)")) %>% ## in R, you have to escape the escape, hence \\
  pull(term)

carb_factors <- tidy(reg2) %>%
  filter(str_detect(term, "factor\\(carb\\)")) %>%
  pull(term)

check_factors <- function(model, factors) {
  return(all(factors %in% (tidy(model) %>% pull(term))))
}

models_report <- list(reg1 , reg2)
huxreg(models_report,
       omit_coefs = c(gear_factors, carb_factors)) %>%
  # add the rows with with True/false returned by check_factors() replased with "Yes"/"No"
  add_rows(rbind(c("Gear FE",
                   ifelse(sapply(models_report,
                                 check_factors,
                                 factors=gear_factors),
                          "Yes", "No")),
                 c("Carb FE",
                   ifelse(sapply(models_report,
                                 check_factors,
                                 factors=carb_factors),
                          "Yes", "No"))),
                 copy_cell_props = FALSE, # this will prevent horizontal lines from appearing
           after = nrow(.) - 5)

</code>```

This produces the following table:

```<code>────────────────────────────────────────────────────
                        (1)              (2)
                 ───────────────────────────────────
  (Intercept)          29.600 ***       25.533 ***
                       (1.230)          (2.996)
  disp                 -0.041 ***       -0.018
                       (0.005)          (0.011)
                 ───────────────────────────────────
  Gear FE          No               Yes
  Carb FE          No               Yes
  N                    32               32
  R2                    0.718            0.828
  logLik              -82.105          -74.186
  AIC                 170.209          168.372
────────────────────────────────────────────────────
  *** p < 0.001; ** p < 0.01; * p < 0.05.

Column names: names, model1, model2
</code>```

Title: Omit factor variables in `huxreg`

Body:
I am running a regression in R with a lot of time and location fixed effects. I try to output a nice summary table into Latex. I switched from stargazer package to huxtable because stargazer does not behave consistently when omitting fixed effects (see this question).

Here is a simple example:

library(huxtable)

reg1 <- lm(mpg ~ disp, data = mtcars)
reg2 <- lm(mpg ~ disp + factor(gear) + factor(carb), data = mtcars)
huxreg(reg1, reg2)

The output of huxreg is:

> huxreg(reg1, reg2)
────────────────────────────────────────────────────
                        (1)              (2)
                 ───────────────────────────────────
  (Intercept)          29.600 ***       25.533 ***
                       (1.230)          (2.996)
  disp                 -0.041 ***       -0.018
                       (0.005)          (0.011)
  factor(gear)4                          3.988
                                        (2.495)
  factor(gear)5                          5.391 *
                                        (2.591)
  factor(carb)2                         -1.979
                                        (1.667)
  factor(carb)3                         -4.161
                                        (2.131)
  factor(carb)4                         -6.199 *
                                        (2.221)
  factor(carb)6                         -8.557 *
                                        (3.653)
  factor(carb)8                        -10.389 *
                                        (4.268)
                 ───────────────────────────────────
  N                    32               32
  R2                    0.718            0.828
  logLik              -82.105          -74.186
  AIC                 170.209          168.372
────────────────────────────────────────────────────
  *** p < 0.001; ** p < 0.01; * p < 0.05.

Column names: names, model1, model2

Here is the desired output:

────────────────────────────────────────────────────
                        (1)              (2)
                 ───────────────────────────────────
  (Intercept)          29.600 ***       25.533 ***
                       (1.230)          (2.996)
  disp                 -0.041 ***       -0.018
                       (0.005)          (0.011)
                 ───────────────────────────────────
  Gear FE                No               Yes
  Carb FE                No               Yes
                 ───────────────────────────────────
  N                    32               32
  R2                    0.718            0.828
  logLik              -82.105          -74.186
  AIC                 170.209          168.372
────────────────────────────────────────────────────
  *** p < 0.001; ** p < 0.01; * p < 0.05.

Column names: names, model1, model2

I know I could simply edit the huxtable using add_rows(), but I am looking for a more robust solution that would allow to find rownames using regular expressions (like stargazer's omit.labels option).

Body:
I wrote the answer myself, using this as inspiration.

The function check_factors() determines if the particular variables are present in the model, and then sapply() is used to create the rows that are added in the table. This is not fully automatic, though, since I still have to check if all the variables listed for omit_coef were later tested by check_factors(). It is possible to omit a variable and then forget to add a corresponding row.

library(huxtable)

reg1 <- lm(mpg ~ disp, data = mtcars)
reg2 <- lm(mpg ~ disp + factor(gear) + factor(carb), data = mtcars)
huxreg(reg1, reg2)

gear_factors <- tidy(reg2) %>%
  filter(str_detect(term, "factor\\(gear\\)")) %>% ## in R, you have to escape the escape, hence \\
  pull(term)

carb_factors <- tidy(reg2) %>%
  filter(str_detect(term, "factor\\(carb\\)")) %>%
  pull(term)

check_factors <- function(model, factors) {
  return(all(factors %in% (tidy(model) %>% pull(term))))
}

models_report <- list(reg1 , reg2)
huxreg(models_report,
       omit_coefs = c(gear_factors, carb_factors)) %>%
  # add the rows with with True/false returned by check_factors() replased with "Yes"/"No"
  add_rows(rbind(c("Gear FE",
                   ifelse(sapply(models_report,
                                 check_factors,
                                 factors=gear_factors),
                          "Yes", "No")),
                 c("Carb FE",
                   ifelse(sapply(models_report,
                                 check_factors,
                                 factors=carb_factors),
                          "Yes", "No"))),
                 copy_cell_props = FALSE, # this will prevent horizontal lines from appearing
           after = nrow(.) - 5)

This produces the following table:

────────────────────────────────────────────────────
                        (1)              (2)
                 ───────────────────────────────────
  (Intercept)          29.600 ***       25.533 ***
                       (1.230)          (2.996)
  disp                 -0.041 ***       -0.018
                       (0.005)          (0.011)
                 ───────────────────────────────────
  Gear FE          No               Yes
  Carb FE          No               Yes
  N                    32               32
  R2                    0.718            0.828
  logLik              -82.105          -74.186
  AIC                 170.209          168.372
────────────────────────────────────────────────────
  *** p < 0.001; ** p < 0.01; * p < 0.05.

Column names: names, model1, model2


问:
Insert a variable in-between ' ' in a shell osascript command?
I am using a MacOS osascript command in a shell script and I try to run the following command:

```<code>APPNAME=$@

if pgrep -x "$APPNAME" > /dev/null # checking if app is open
then
  echo "Closing..."
  osascript -e 'quit app $APPNAME'

else
  echo "*** The app is not open"
fi
</code>```

Ideally, the command would be osascript -e 'quit app "Calendar"' as an example of a working solution. However, I can't seem to insert a variable in-between ' ' quotation marks.

What would be a workaround?

答:
The point (one of the points, anyway) of single quotes is to prevent variable interpolation.  It sounds like what you really want is a way to get double quotes into a string.  There are lots of ways to do that.  A common one is:</p>

```<code>osascript -e "quit app \"$appname\""
</code>```

Body:
I am using a MacOS osascript command in a shell script and I try to run the following command:

APPNAME=$@

if pgrep -x "$APPNAME" > /dev/null # checking if app is open
then
  echo "Closing..."
  osascript -e 'quit app $APPNAME'

else
  echo "*** The app is not open"
fi

Ideally, the command would be osascript -e 'quit app "Calendar"' as an example of a working solution. However, I can't seem to insert a variable in-between ' ' quotation marks.

What would be a workaround?

Body:
The point (one of the points, anyway) of single quotes is to prevent variable interpolation.  It sounds like what you really want is a way to get double quotes into a string.  There are lots of ways to do that.  A common one is:

osascript -e "quit app \"$appname\""


问:
Sending an email using php shows a blank page
I'm trying to collect some informations from an html form and send them to an e-mail using php.
but all i get is a blank page. i looked to similar questions but i couldn't find the problem.
this is my code:

```<code><?php

     if(isset($_POST['submit'])){
         $Fname=$_POST['First'];
         $Lname=$_POST['Last'];
         $email=$_POST['email'];
         $code=$_POST['countryCode'];
         $phone=$_POST['phone'];
         $Pname=$_POST['ProjectName'];
         $Ptype=$_POST['ProjectType'];
         $Pdisplay=$_POST['ProjectDisplay'];
         $Powner=$_POST['ProjectOwner'];
         $Plang=$_POST['ProjectLang'];
         $Gender=$_POST['Gender'];
         $Vitess=$_POST['Vitesse'];
         $Style=$_POST['Style'];
         $Duration=$_POST['Duration'];
         $Script=$_POST['Script'];
         $Cmnt=$_POST['Cmnt'];

        $to='myAdredd';
        $subject='Order';
        $message="First Name: ".$Fname." "."Last Name: ".$Lname." "."\n"."E-mail: ".$email."\n"."Phone: ".$code." ".$phone."\n"."Project Name: ".$Pname."\n"."Project Type: ".$Ptype."\n"."Project Display: ".$Pdisplay."\n"."Owner: ".$Powner."\n"."Language: ".$Plang."\n"."Gender Voice: ".$Gender."\n"."Vitess: ".$Vitess."\n"."Style: ".$Style."\n"."Duration: ".$Duration."\n"."Script: "."\n\n".".$Script."."Message: ".$Cmnt."\n";

        $headers="From: ".$email;

         if(mail($to,$subject,$message,$headers)){
             echo "sent";
         }else{
             echo "problem ";
        }

 }

?>
</code>```

after submitting the form i don t see neither of : "sent" or "problem"

the site is hosted on bluehost

this is my first time ever using php

答:
Use try catch for identify the error in script like-:

```<code><?php
    try{
        if(isset($_POST['submit'])){
            $Fname=$_POST['First'];
            $Lname=$_POST['Last'];
            $email=$_POST['email'];
            $code=$_POST['countryCode'];
            $phone=$_POST['phone'];
            $Pname=$_POST['ProjectName'];
            $Ptype=$_POST['ProjectType'];
            $Pdisplay=$_POST['ProjectDisplay'];
            $Powner=$_POST['ProjectOwner'];
            $Plang=$_POST['ProjectLang'];
            $Gender=$_POST['Gender'];
            $Vitess=$_POST['Vitesse'];
            $Style=$_POST['Style'];
            $Duration=$_POST['Duration'];
            $Script=$_POST['Script'];
            $Cmnt=$_POST['Cmnt'];

            $to='myAdredd';
            $subject='Order';
            $message="First Name: ".$Fname." "."Last Name: ".$Lname." "."\n"."E-mail: ".$email."\n"."Phone: ".$code." ".$phone."\n"."Project Name: ".$Pname."\n"."Project Type: ".$Ptype."\n"."Project Display: ".$Pdisplay."\n"."Owner: ".$Powner."\n"."Language: ".$Plang."\n"."Gender Voice: ".$Gender."\n"."Vitess: ".$Vitess."\n"."Style: ".$Style."\n"."Duration: ".$Duration."\n"."Script: "."\n\n".".$Script."."Message: ".$Cmnt."\n";

            $headers="From: ".$email;

            if(mail($to,$subject,$message,$headers)){
                echo "sent";
            }else{
                echo "problem ";
            }
        }
    }
    catch(Exception $e){
        echo $e;
    }
?>
</code>```

Make sure configure SMTP configuration in php.ini file before run mail().

SMTP configuration look like-:

Body:
I'm trying to collect some informations from an html form and send them to an e-mail using php.
but all i get is a blank page. i looked to similar questions but i couldn't find the problem.
this is my code:

<?php

     if(isset($_POST['submit'])){
         $Fname=$_POST['First'];
         $Lname=$_POST['Last'];
         $email=$_POST['email'];
         $code=$_POST['countryCode'];
         $phone=$_POST['phone'];
         $Pname=$_POST['ProjectName'];
         $Ptype=$_POST['ProjectType'];
         $Pdisplay=$_POST['ProjectDisplay'];
         $Powner=$_POST['ProjectOwner'];
         $Plang=$_POST['ProjectLang'];
         $Gender=$_POST['Gender'];
         $Vitess=$_POST['Vitesse'];
         $Style=$_POST['Style'];
         $Duration=$_POST['Duration'];
         $Script=$_POST['Script'];
         $Cmnt=$_POST['Cmnt'];

        $to='myAdredd';
        $subject='Order';
        $message="First Name: ".$Fname." "."Last Name: ".$Lname." "."\n"."E-mail: ".$email."\n"."Phone: ".$code." ".$phone."\n"."Project Name: ".$Pname."\n"."Project Type: ".$Ptype."\n"."Project Display: ".$Pdisplay."\n"."Owner: ".$Powner."\n"."Language: ".$Plang."\n"."Gender Voice: ".$Gender."\n"."Vitess: ".$Vitess."\n"."Style: ".$Style."\n"."Duration: ".$Duration."\n"."Script: "."\n\n".".$Script."."Message: ".$Cmnt."\n";

        $headers="From: ".$email;

         if(mail($to,$subject,$message,$headers)){
             echo "sent";
         }else{
             echo "problem ";
        }

 }

?>

after submitting the form i don t see neither of : "sent" or "problem"

the site is hosted on bluehost

this is my first time ever using php

Body:
Use try catch for identify the error in script like-:

<?php
    try{
        if(isset($_POST['submit'])){
            $Fname=$_POST['First'];
            $Lname=$_POST['Last'];
            $email=$_POST['email'];
            $code=$_POST['countryCode'];
            $phone=$_POST['phone'];
            $Pname=$_POST['ProjectName'];
            $Ptype=$_POST['ProjectType'];
            $Pdisplay=$_POST['ProjectDisplay'];
            $Powner=$_POST['ProjectOwner'];
            $Plang=$_POST['ProjectLang'];
            $Gender=$_POST['Gender'];
            $Vitess=$_POST['Vitesse'];
            $Style=$_POST['Style'];
            $Duration=$_POST['Duration'];
            $Script=$_POST['Script'];
            $Cmnt=$_POST['Cmnt'];

            $to='myAdredd';
            $subject='Order';
            $message="First Name: ".$Fname." "."Last Name: ".$Lname." "."\n"."E-mail: ".$email."\n"."Phone: ".$code." ".$phone."\n"."Project Name: ".$Pname."\n"."Project Type: ".$Ptype."\n"."Project Display: ".$Pdisplay."\n"."Owner: ".$Powner."\n"."Language: ".$Plang."\n"."Gender Voice: ".$Gender."\n"."Vitess: ".$Vitess."\n"."Style: ".$Style."\n"."Duration: ".$Duration."\n"."Script: "."\n\n".".$Script."."Message: ".$Cmnt."\n";

            $headers="From: ".$email;

            if(mail($to,$subject,$message,$headers)){
                echo "sent";
            }else{
                echo "problem ";
            }
        }
    }
    catch(Exception $e){
        echo $e;
    }
?>

Make sure configure SMTP configuration in php.ini file before run mail().

SMTP configuration look like-:


答:
Since you didn't say exactly what you realy want... If you want to print the individual characters,

```<code>let exampleValue = 'abcdef';
for(var j = 0; j < exampleValue.length; j++){
    console.log(exampleValue[j]);
}
</code>```

And if you are just interested in the number of elements:

```<code>int i = exampleValue.length;
console.log(i)
</code>```

Title: Javascript - Loop string until null character found

Body:
I want to iterate through a string until a null character is found (\0), like how we do in C language. I have listed down the steps which I have tried below.

let exampleValue = 'abcdef';
let i = 0;

// Trial 1
while (exampleValue[i] !== '\0') {
  i++;
  // This seems to go on infinitely
}

// Trial 2
while (exampleValue[i] !== '\0'.charCodeAt(0)) {
  i++;
  // This seems to go on infinitely
}

// Trial 3
while (exampleValue[i] !== \0) {
  i++;
  // This throws an invalid character error
}

// Trial 4
while (exampleValue[i] !== undefined) {
  i++;
  // This seems to work
}

Based on the above samples, Trial 4 seems to work. Can I continue using Trial 4 for my desired output or is there a better way to solve my problem?

EDIT:
I apologize for not specifying my problem, I want to print each letter of the string by iterating through it without using exampleValue.length

EDIT 2:
After I read tadman's comment, I got to know Javascript's do not terminate their string using a null character but instead it stores it's keeps track of it characters and stores the length seperately.

Body:
Since you didn't say exactly what you realy want... If you want to print the individual characters,

let exampleValue = 'abcdef';
for(var j = 0; j < exampleValue.length; j++){
    console.log(exampleValue[j]);
}

And if you are just interested in the number of elements:

int i = exampleValue.length;
console.log(i)


问:
http get from assets not work in published app Angular 9
i worked with Angular +9 and i've a problem when read json file from assets folder.

i am using the http module and the call works fine when the application is run locally, but when i run ng-build and publish the application on a server, the call to the json file doesn't work indicating the following message:

ERROR Http failure response for assets/resources/fakeData.json: 0 Unknown Error

My code:

What could be the problem? Why can't I access the assets folder directly?

答:
Your problem is that you are trying to access your file system with the HttpClient. You can't do that. You could of course make an API Endpoint that returns your json file, but you can't access it directly like that with the HttpClient module.

Here what I would do instead:

```<code>import * as myJson from '<path to fakeData.json>';
...
getData(): any {
   return myJson;
}
</code>```

If you are just trying to mess around with HttpClient module and need some json to play with, you use JSON Placeholder API:

this.http.get('https://jsonplaceholder.typicode.com/todos/1');

According to the below SOF Question, it looks like you can get your local json files to be hosted along with the angular dev server if you wanted to:

Load json from local file with http.get() in angular 2

Body:
Your problem is that you are trying to access your file system with the HttpClient. You can't do that. You could of course make an API Endpoint that returns your json file, but you can't access it directly like that with the HttpClient module.

Here what I would do instead:

import * as myJson from '<path to fakeData.json>';
...
getData(): any {
   return myJson;
}

If you are just trying to mess around with HttpClient module and need some json to play with, you use JSON Placeholder API:

this.http.get('https://jsonplaceholder.typicode.com/todos/1');

According to the below SOF Question, it looks like you can get your local json files to be hosted along with the angular dev server if you wanted to:

Load json from local file with http.get() in angular 2


问:
Add button to a dynamically created table row
so Iam trying to add this button to a dynamically created table row. But I honestly don't know how to get this working. The code is a mess, because Iam trying so many things in order to get this going.

I need to append this button (element) to the table row where the function is called, is there any smart way to do this. If i change my structure of the table, thats okay.

```<code>function getPerson(){
//addButton.value = "+";
//addButton.class = "btn btn-success";
$("#output1 tbody tr").remove();
fetch(url)
    .then(res => res.json())
    .then(data => {

        console.log(data);

        var temp = "";
        data.forEach((person) => {
            temp += "<tr>";
            temp += "<td>" +person.id+"</td>";
            console.log(person.id);
            temp += "<td>" +person.vorname+"</td>";
            temp += "<td>" +person.nachname+"</td>";
            temp += "<td>"
            person.projectList.forEach((project) => {
              temp += project.name+"<br>";
            });
            temp += "</td>"

            temp += "<td>"
            person.technoList.forEach((techno) => {
              temp += techno.name+"<br>";
            });
            temp += "</td>"

            temp += "<td id='addButton" + x + "' >" + addButton(person.id)+ "</td>"
             //this.parentElement.appendChild(this)
             x++;

            //document.getElementById('personDetail_Button').addEventListener('click', this.personDetail(person.id));
            temp += "</tr>"

        });

        document.getElementById("tableOutput").innerHTML= temp;

    });
}

function addButton(person_id){
  var person_id_onclick = person_id
  var element = document.createElement("input");
  element.type = 'button';
  element.value = 'test123';
  element.onclick = function(){
    personDetail(person_id_onclick);
  }
  $(element).addClass('btn btn-primary');
  //$(this).appendChild(element);
  document.body.appendChild(element);

}
</code>```

```<code><table class="table" id="output1">
        <thead class="thead-dark">
            <tr>
                <th scope="">ID</th>
                <th scope="col">Vorname</th>
                <th scope="col">Nachname</th>
                <th scope="col">Projekte</th>
                <th scope="col">Technologien</th>
                <th scope="col">Button</th>
            </tr>
        </thead>
        <tbody id="tableOutput">

        </tbody>

    </table>
</code>```

答:
You can try replacing document.body.appendChild(element); with return element; I also updated the function to remove the random jquery class.

function addButton(person_id){
  var element = document.createElement("input");
  element.type = 'button';
  element.value = 'test123';
  element.setAttribute("data-person_id",person_id);
  element.setAttribute("class","btn-viewdetail btn btn-primary");

  var _wrap = document.createElement("div");
  _wrap.appendChild(element);

 return _wrap.innerHTML;

}

var _btns = document.querySelectorAll(".btn-viewdetail");
_btns.forEach(function(el){
  el.addEventListener("click",function(evt){
    personDetail(evt.target.getAttribute("data-person_id"));
  });
});

document.body.innerHTML += addButton(4);```

Body:
so Iam trying to add this button to a dynamically created table row. But I honestly don't know how to get this working. The code is a mess, because Iam trying so many things in order to get this going.

I need to append this button (element) to the table row where the function is called, is there any smart way to do this. If i change my structure of the table, thats okay.

function getPerson(){
//addButton.value = "+";
//addButton.class = "btn btn-success";
$("#output1 tbody tr").remove();
fetch(url)
    .then(res => res.json())
    .then(data => {

        console.log(data);

        var temp = "";
        data.forEach((person) => {
            temp += "
";
            temp += "" +person.id+"	";
            console.log(person.id);
            temp += "" +person.vorname+"	";
            temp += "" +person.nachname+"	";
            temp += ""
            person.projectList.forEach((project) => {
              temp += project.name+"
";
            });
            temp += "	"

            temp += ""
            person.technoList.forEach((techno) => {
              temp += techno.name+"
";
            });
            temp += "	"

            temp += "" + addButton(person.id)+ "	"
             //this.parentElement.appendChild(this)
             x++;

            //document.getElementById('personDetail_Button').addEventListener('click', this.personDetail(person.id));
            temp += "
"

        });

        document.getElementById("tableOutput").innerHTML= temp;

    });
}

function addButton(person_id){
  var person_id_onclick = person_id
  var element = document.createElement("input");
  element.type = 'button';
  element.value = 'test123';
  element.onclick = function(){
    personDetail(person_id_onclick);
  }
  $(element).addClass('btn btn-primary');
  //$(this).appendChild(element);
  document.body.appendChild(element);

}

                ID
                Vorname
                Nachname
                Projekte
                Technologien
                Button


问:
Laravel 7: How to prevent middleware Authenticate from redirecting when user is not authenticated?
I have implemented the middleware Authenticate with $this->middleware('auth:api');.

The application is a REST API so I don't need Laravel to redirect the client. I need it to return a JSON response.

There is a method redirectTo inside App\Http\Middleware\Authenticate.php;. This method only accepts a route, therefore I cannot add the JSON response to this method.

How can I use the middleware Authenticate (auth:api) and return a JSON Response when the user is not authenticated?

答:
```<code><?php

namespace App\Http\Middleware;

use Illuminate\Auth\Middleware\Authenticate as Middleware;

class Authenticate extends Middleware
{
    /**
     * Get the path the user should be redirected to when they are not authenticated.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return string|null
     */
    protected function redirectTo($request)
    {
        if (! $request->expectsJson()) {
            return route('login');
        }
    }
}
</code>```

This class is extending Illuminate\Auth\Middleware\Authenticate - and it overrides redirectTo method. You need to write down your own handle method. If you want you may remove extends part if you don't need framework's authenticate method.

```<code>public function handle($request, Closure $next, ...$guards)
{
    if (Auth::guest()) {
        return response()->json(['message' => 'you shall not pass']);
    }

    // other checks

    return $next($request);
}
</code>```

Another option would be keeping the extends and calling parent method after doing your regular checks if you need some of the functionality from base class.

```<code>public function handle($request, Closure $next, ...$guards)
{
    if (Auth::guest()) {
        return response()->json(['message' => 'you shall not pass']);
    }

    return parent::handle($request, $next, $guards);
}
</code>```

Body:
<?php

namespace App\Http\Middleware;

use Illuminate\Auth\Middleware\Authenticate as Middleware;

class Authenticate extends Middleware
{
    /**
     * Get the path the user should be redirected to when they are not authenticated.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return string|null
     */
    protected function redirectTo($request)
    {
        if (! $request->expectsJson()) {
            return route('login');
        }
    }
}

This class is extending Illuminate\Auth\Middleware\Authenticate - and it overrides redirectTo method. You need to write down your own handle method. If you want you may remove extends part if you don't need framework's authenticate method.

public function handle($request, Closure $next, ...$guards)
{
    if (Auth::guest()) {
        return response()->json(['message' => 'you shall not pass']);
    }

    // other checks

    return $next($request);
}

Another option would be keeping the extends and calling parent method after doing your regular checks if you need some of the functionality from base class.

public function handle($request, Closure $next, ...$guards)
{
    if (Auth::guest()) {
        return response()->json(['message' => 'you shall not pass']);
    }

    return parent::handle($request, $next, $guards);
}


问:
How to change a range of array with one value Javascript?
I have an array like below let's say

```<code>var myArray = ["1", "", "", "2","3","","","8"];
</code>```

And I want to fill each " " value with previous not null value

According to that expectation should be like below

```<code>var myArray = ["1", "2", "2", "2","3","8","8","8"];
</code>```

Here what I tried but didn't work

    var myArray = ["1", "", "", "2","3","","","8"];

    function myFunction() {
      let currentEl=myArray [0];
      let prevIndex=0;
      fruits.map((e,a)=>{
      if(e!="" && myArray[a-1]==""){
       currentEl=e;
       let interval=arrayGenerate(a-currentIndex-1,currentEl);
       fruits.splice(currentIndex-1, currentEl+1, interval);
       currentIndex=a;
      }
      })
    }
    function arrayGenerate(iteration,value){
      let arr=[];
      for(var i=0;i<iteration;i++){
      arr.push(value);
      }
      return arr;
    }

console.log(myArray)```

答:
It's interesting how many different ways this can be done. Just another slightly ugly way to do the same thing:

const fill = (arr, lastVal) => (
  arr.reverse()
  .map(el => el.length > 0 ? lastVal = el : lastVal)
  .reverse()
);

console.log(fill(["1", "", "", "2","3","","","8"]));```

Body:
I have an array like below let's say

var myArray = ["1", "", "", "2","3","","","8"];

And I want to fill each " " value with previous not null value

According to that expectation should be like below

var myArray = ["1", "2", "2", "2","3","8","8","8"];

Here what I tried but didn't work

    var myArray = ["1", "", "", "2","3","","","8"];

    function myFunction() {
      let currentEl=myArray [0];
      let prevIndex=0;
      fruits.map((e,a)=>{
      if(e!="" && myArray[a-1]==""){
       currentEl=e;
       let interval=arrayGenerate(a-currentIndex-1,currentEl);
       fruits.splice(currentIndex-1, currentEl+1, interval);
       currentIndex=a;
      }
      })
    }
    function arrayGenerate(iteration,value){
      let arr=[];
      for(var i=0;i<iteration;i++){
      arr.push(value);
      }
      return arr;
    }

console.log(myArray)


问:
How can i make a code run automatically every 30 mins in shell script or PHP?
I have a code which I want to run every 30mins. Since it is not possible to do it manually over 30 days I wanted to make it an automated process. Please suggest me how to do it. I want to execute this command in Putty. </p>

```<code>--user root --host 10.0.2.140 --port 3306 --socket /var/lib/mysql/mysql.sock
</code>```

答:
Use crontab, your entry would look like this:

*/30 * * * * /path/to/your/command

Body:
I have a code which I want to run every 30mins. Since it is not possible to do it manually over 30 days I wanted to make it an automated process. Please suggest me how to do it. I want to execute this command in Putty.

--user root --host 10.0.2.140 --port 3306 --socket /var/lib/mysql/mysql.sock


问:
Center text in rounded border
I want to create a rounded border, and put some text in the middle of the top border like this:

I tried altering the solution posted on this previous question, but I couldn't get the bottom border of the text to match up with the border of the div below (the snippet below is using tailwindcss, but you get the idea):

<link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"/>

    SOME TEXT

```

How can I accomplish this?

答:
If you want to use only HTML and CSS then you can do it like:

div {
  height: 60px;
  width: 200px;
  border: 2px solid black;
  border-radius: 10px;
}

h3 {
  width: 35px;
  margin-top: -10px;
  margin-left: 80px;
  background: white;
  padding:0px 2px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
    <h3>Text</h1>
</div></code>```

Title: Center text in rounded border

Body:
I want to create a rounded border, and put some text in the middle of the top border like this:

I tried altering the solution posted on this previous question, but I couldn't get the bottom border of the text to match up with the border of the div below (the snippet below is using tailwindcss, but you get the idea):

<link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"/>

    SOME TEXT

How can I accomplish this?

Body:
If you want to use only HTML and CSS then you can do it like:

div {
  height: 60px;
  width: 200px;
  border: 2px solid black;
  border-radius: 10px;
}

h3 {
  width: 35px;
  margin-top: -10px;
  margin-left: 80px;
  background: white;
  padding:0px 2px;
}

<div>
    <h3>Text</h1>
</div>


问:
why should i use @classmethod when i can call the constructor in the without the annotation?
I was looking into the advantages of @classmethods and figured that we can directly call the constructor from any method, in that case, why do we need a class method. Are there some advantages which i have missed.

Why this code, what are the advantages?

```<code>class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    @classmethod
    def fromBirthYear(cls, name, year):
        return cls(name, date.today().year - year)
</code>```

and not this code :-

```<code>class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def fromBirthYear(name, year):
        return Person(name, date.today().year - year)
</code>```

答:
Because if you derive from Person, fromBirthYear will always return a Person object and not the derived class.

```<code>class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def fromBirthYear(name, year):
        return Person(name, year)

class Fred(Person):
    pass
print(Fred.fromBirthYear('bob', 2019))
</code>```

Output:

```<code><__main__.Person object at 0x6ffffcd7c88>
</code>```

You would want Fred.fromBirthYear to return a Fred object.

In the end the language will let you do a lot of things that you shouldn't do.

Body:
I was looking into the advantages of @classmethods and figured that we can directly call the constructor from any method, in that case, why do we need a class method. Are there some advantages which i have missed.

Why this code, what are the advantages?

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    @classmethod
    def fromBirthYear(cls, name, year):
        return cls(name, date.today().year - year)

and not this code :-

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def fromBirthYear(name, year):
        return Person(name, date.today().year - year)

Body:
Because if you derive from Person, fromBirthYear will always return a Person object and not the derived class.

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def fromBirthYear(name, year):
        return Person(name, year)

class Fred(Person):
    pass
print(Fred.fromBirthYear('bob', 2019))

Output:

<__main__.Person object at 0x6ffffcd7c88>

You would want Fred.fromBirthYear to return a Fred object.

In the end the language will let you do a lot of things that you shouldn't do.


问:
How to reuse a single class within multiple projects, with minor modifications in functionality?
I have a common library where I've put classes that are used between multiple Android projects. However, now I encountered a situation where I have to make minor changes to the functionality of the class in one project. How should I organize the classes, keeping in mind easy readability of code and future extension possibilities?

Should I

Extend the class (MyClass) with modifications that are special to the subproject (MyClassSub extends MyClass)? What about if I have references to MyClass in the library classes, but in this special subproject MyClassSub should be called?

Have switch OR if clauses for each special part in the class file? And then pass some variable to the class?

Some other option?

This is probably a trivial question, but I am quite new to java and can't quite figure it out.

答:
Unfortunately the answer is "it depends."

Specifically, a class hierarchy should be designed such that the behavior of the base class holds for all subclasses of the class. One way to look at this is to say that the subclass may expand the behavior of the base class. The corollary is that a subclass should not restrict the behavior of the base class. So a Square IS NOT A Rectangle.

Also consider "favor composition over inheritance" unless the base class is specifically designed for inheritance, as a change to the base class might BREAK the subclass.

Have fun!


问:
Where can I find the new Layout Inspector from Android Studio 2.2 Preview 1
Just wondering where I can find the new Layout Inspector feature in Android Studio 2.2 released yesterday.</p>

答:
None of the above worked in android 4. I've found that it has been moved to View / Tool Windows/ Layout Inspector

Animation


问:
Performance issues using DialContext in Go
I did a quick benchmark using Go's built-in http.Client and net. It resulted in some noticeable performance issues when using DialContext as opposed to when not using it.

I am basically trying to imitate a use case we have in my company where that http.Client setup is way less performant than the default configuration when used exactly for the same things. And I noticed commenting the DialContext part made it go faster.

The benchmark just opens a pool of threads (8 in the example) to create connections to a simple URL, using a buffered channel of the same size as number of threads (8).

Here is the code with DialContext (2.266333805s):

```<code>func main() {
    var httpClient *http.Client

    httpClient = &http.Client{
        Transport: &http.Transport{
            DialContext: (&net.Dialer{
                Timeout:   3 * time.Second,
                KeepAlive: 30 * time.Second,
                DualStack: true,
            }).DialContext,
        },
    }

    url := "https://stackoverflow.com/"
    wg := sync.WaitGroup{}
    threads := 8
    wg.Add(threads)
    c := make(chan struct{}, threads)

    start := time.Now()
    for i := 0; i < threads; i++ {
        go func() {
            for range c {
                req, _ := http.NewRequest(http.MethodGet, url, nil)
                resp, err := httpClient.Do(req)
                if err == nil {
                    resp.Body.Close()
                }
            }
            wg.Done()
        }()
    }

    for i := 0; i < 200; i++ {
        c <- struct{}{}
    }
    close(c)
    wg.Wait()

    fmt.Println(time.Since(start))
}
</code>```

The outputed time was 2.266333805s

And here is the code without DialContext (731.154103ms):

```<code>func main() {
    var httpClient *http.Client

    httpClient = &http.Client{
        Transport: &http.Transport{
        },
    }

    url := "https://stackoverflow.com/"
    wg := sync.WaitGroup{}
    threads := 8
    wg.Add(threads)
    c := make(chan struct{}, threads)

    start := time.Now()
    for i := 0; i < threads; i++ {
        go func() {
            for range c {
                req, _ := http.NewRequest(http.MethodGet, url, nil)
                resp, err := httpClient.Do(req)
                if err == nil {
                    resp.Body.Close()
                }
            }
            wg.Done()
        }()
    }

    for i := 0; i < 200; i++ {
        c <- struct{}{}
    }
    close(c)
    wg.Wait()

    fmt.Println(time.Since(start))
}
</code>```

The outputed time was 731.154103ms

The difference between results was consistent among several runs of the program.

Does anyone has a clue about why this is happening?

Thanks!

EDIT: So I tried net/http/httptrace and I made sure the body of the response was fully read and closed:

```<code>go func() {
    for range c {
        req, _ := http.NewRequest(http.MethodGet, url, nil)
        req = req.WithContext(httptrace.WithClientTrace(req.Context(), &httptrace.ClientTrace{
            GotConn: t.gotConn,
        }))
        resp, _ := httpClient.Do(req)
        ioutil.ReadAll(resp.Body)
        resp.Body.Close()
    }
    wg.Done()
}()
</code>```

The findings where interesting when using DialContext vs not using it.

NOT USING DialContext:

```<code>time taken to run 200 requests: 5.639808793s
new connections: 1
reused connections: 199
</code>```

USING DialContext:

```<code>time taken to run 200 requests: 5.682882723s
new connections: 8
reused connections: 192
</code>```

It is faster... But why one opens 8 new connections, and the other one just 1?

答:
The only way you would be getting such large differences is if one transport is reusing the connections, and the other is not. In order to ensure you can reuse the connection, you must always read the response body. It is possible that in some cases the connection would be reused without explicitly reading the body, but it's never guaranteed and depends on many things like the remote server closing the connection, whether the response was fully buffered by the Transport, and if there was a context on the request.

The net/http/httptrace package can give you insight into a lot of the request internals, including whether the connections were reused or not. See https://blog.golang.org/http-tracing for examples.

Setting DisableKeepAlive will always prevent the connections from being reused, making both similarly slow. Always reading the response like so will make both similarly fast:

```<code>req, _ := http.NewRequest(http.MethodGet, url, nil)
resp, err := httpClient.Do(req)
if err != nil {
    // handle error
    continue
}
io.Copy(ioutil.Discard, resp.Body)
resp.Body.Close()
</code>```

If you want a cap on how much can be read before dropping the connection, you can simply wrap the body in an io.LimitedReader

Body:
I did a quick benchmark using Go's built-in http.Client and net. It resulted in some noticeable performance issues when using DialContext as opposed to when not using it.

I am basically trying to imitate a use case we have in my company where that http.Client setup is way less performant than the default configuration when used exactly for the same things. And I noticed commenting the DialContext part made it go faster.

The benchmark just opens a pool of threads (8 in the example) to create connections to a simple URL, using a buffered channel of the same size as number of threads (8).

Here is the code with DialContext (2.266333805s):

func main() {
    var httpClient *http.Client

    httpClient = &http.Client{
        Transport: &http.Transport{
            DialContext: (&net.Dialer{
                Timeout:   3 * time.Second,
                KeepAlive: 30 * time.Second,
                DualStack: true,
            }).DialContext,
        },
    }

    url := "https://stackoverflow.com/"
    wg := sync.WaitGroup{}
    threads := 8
    wg.Add(threads)
    c := make(chan struct{}, threads)

    start := time.Now()
    for i := 0; i < threads; i++ {
        go func() {
            for range c {
                req, _ := http.NewRequest(http.MethodGet, url, nil)
                resp, err := httpClient.Do(req)
                if err == nil {
                    resp.Body.Close()
                }
            }
            wg.Done()
        }()
    }

    for i := 0; i < 200; i++ {
        c <- struct{}{}
    }
    close(c)
    wg.Wait()

    fmt.Println(time.Since(start))
}

The outputed time was 2.266333805s

And here is the code without DialContext (731.154103ms):

func main() {
    var httpClient *http.Client

    httpClient = &http.Client{
        Transport: &http.Transport{
        },
    }

    url := "https://stackoverflow.com/"
    wg := sync.WaitGroup{}
    threads := 8
    wg.Add(threads)
    c := make(chan struct{}, threads)

    start := time.Now()
    for i := 0; i < threads; i++ {
        go func() {
            for range c {
                req, _ := http.NewRequest(http.MethodGet, url, nil)
                resp, err := httpClient.Do(req)
                if err == nil {
                    resp.Body.Close()
                }
            }
            wg.Done()
        }()
    }

    for i := 0; i < 200; i++ {
        c <- struct{}{}
    }
    close(c)
    wg.Wait()

    fmt.Println(time.Since(start))
}

The outputed time was 731.154103ms

The difference between results was consistent among several runs of the program.

Does anyone has a clue about why this is happening?

Thanks!

EDIT: So I tried net/http/httptrace and I made sure the body of the response was fully read and closed:

go func() {
    for range c {
        req, _ := http.NewRequest(http.MethodGet, url, nil)
        req = req.WithContext(httptrace.WithClientTrace(req.Context(), &httptrace.ClientTrace{
            GotConn: t.gotConn,
        }))
        resp, _ := httpClient.Do(req)
        ioutil.ReadAll(resp.Body)
        resp.Body.Close()
    }
    wg.Done()
}()

The findings where interesting when using DialContext vs not using it.

NOT USING DialContext:

time taken to run 200 requests: 5.639808793s
new connections: 1
reused connections: 199

USING DialContext:

time taken to run 200 requests: 5.682882723s
new connections: 8
reused connections: 192

It is faster... But why one opens 8 new connections, and the other one just 1?

Body:
The only way you would be getting such large differences is if one transport is reusing the connections, and the other is not. In order to ensure you can reuse the connection, you must always read the response body. It is possible that in some cases the connection would be reused without explicitly reading the body, but it's never guaranteed and depends on many things like the remote server closing the connection, whether the response was fully buffered by the Transport, and if there was a context on the request.

The net/http/httptrace package can give you insight into a lot of the request internals, including whether the connections were reused or not. See https://blog.golang.org/http-tracing for examples.

Setting DisableKeepAlive will always prevent the connections from being reused, making both similarly slow. Always reading the response like so will make both similarly fast:

req, _ := http.NewRequest(http.MethodGet, url, nil)
resp, err := httpClient.Do(req)
if err != nil {
    // handle error
    continue
}
io.Copy(ioutil.Discard, resp.Body)
resp.Body.Close()

If you want a cap on how much can be read before dropping the connection, you can simply wrap the body in an io.LimitedReader


问:
OpenCV Video capture using keyboard to start/stop
I have a running script capable of starting/stopping a video stream using 2 different keys;

Program runs and shows the live stream.

When ESC is hit, the program exits.

When SPACE is hit, the video stream is captured.

However, when a video is captured it stores all the stream from the beginning of script execution.

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

    capture = cv2.VideoCapture(1)
    codec = cv2.VideoWriter_fourcc(*'XVID')
    output = cv2.VideoWriter('CAPTURE.avi', codec, 30, (640, 480))

    while True:
        ret, frame_temp = capture.read()
        cv2.imshow('FRAME', frame_temp)
        key=cv2.waitKey(1)
        if key%256 == 27:
            break
        elif key%256 == 32:
            output.write(frame_temp)

    capture.release()
    output.release()
    cv2.destroyAllWindows()
</code>```

So, instead when the program runs I would like;

Program runs and shows the live stream.

Begin recording the stream when SPACE is hit and stop the recording when SPACE is hit once more.

Any suggestions would be much appreciated.

答:
You need an extra variable to figure out if you are recording. I made a variable called recording_flag

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

capture = cv2.VideoCapture(1)
codec = cv2.VideoWriter_fourcc(*'XVID')

recording_flag = False

while True:
    ret, frame_temp = capture.read()
    cv2.imshow('FRAME', frame_temp)
    key=cv2.waitKey(1)
    if key%256 == 27:
        break
    elif key%256 == 32:
        if recording_flag == False:
            # we are transitioning from not recording to recording
            output = cv2.VideoWriter('CAPTURE.avi', codec, 30, (640, 480))
            recording_flag = True
        else:
            # transitioning from recording to not recording
            recording_flag = False

    if recording_flag:
        output.write(frame_temp)

capture.release()
output.release()
cv2.destroyAllWindows()
</code>```

Body:
I have a running script capable of starting/stopping a video stream using 2 different keys;

Program runs and shows the live stream.

When ESC is hit, the program exits.

When SPACE is hit, the video stream is captured.

However, when a video is captured it stores all the stream from the beginning of script execution.

    import cv2
    import numpy as np

    capture = cv2.VideoCapture(1)
    codec = cv2.VideoWriter_fourcc(*'XVID')
    output = cv2.VideoWriter('CAPTURE.avi', codec, 30, (640, 480))

    while True:
        ret, frame_temp = capture.read()
        cv2.imshow('FRAME', frame_temp)
        key=cv2.waitKey(1)
        if key%256 == 27:
            break
        elif key%256 == 32:
            output.write(frame_temp)

    capture.release()
    output.release()
    cv2.destroyAllWindows()

So, instead when the program runs I would like;

Program runs and shows the live stream.

Begin recording the stream when SPACE is hit and stop the recording when SPACE is hit once more.

Any suggestions would be much appreciated.

Body:
You need an extra variable to figure out if you are recording. I made a variable called recording_flag

import cv2
import numpy as np

capture = cv2.VideoCapture(1)
codec = cv2.VideoWriter_fourcc(*'XVID')

recording_flag = False

while True:
    ret, frame_temp = capture.read()
    cv2.imshow('FRAME', frame_temp)
    key=cv2.waitKey(1)
    if key%256 == 27:
        break
    elif key%256 == 32:
        if recording_flag == False:
            # we are transitioning from not recording to recording
            output = cv2.VideoWriter('CAPTURE.avi', codec, 30, (640, 480))
            recording_flag = True
        else:
            # transitioning from recording to not recording
            recording_flag = False

    if recording_flag:
        output.write(frame_temp)

capture.release()
output.release()
cv2.destroyAllWindows()


问:
How to get an ID from Ref in fauna?
I'm fetching documents from faunadb and I would like their ID to be in the payload that I send to the client.

This is how I fetch the documents and return their data as a collection

serverClient.query(
  q.Map(
    q.Paginate(q.Documents(q.Collection('Portfolio')), { size: 999999 }),
      q.Lambda(x => q.Get(x))
    )
  )
  .then((ret) => ret.data.map(x => ({ ...x.data, _id: x.ref })))
```

<p>Now <code>_id</code> is a Ref. Looking like this when I log it to the console:</p>

```Ref(Collection("Portfolio"), "266565241615155713")
```

<p>And like this when JSON Stringifying it:</p>

```{"@ref":{"id":"266565241615155713","collection":{"@ref":{"id":"Portfolio","collection":{"@ref":{"id":"collections"}}}}}}
```

I basically need to get the ID 266565241615155713 from that Ref. How can I do that?
I tried x.ref['@ref'].id but @ref is undefined.
The documentation did not help me here

Thanks in advance for any hints.

答: You can also return an array with the id and the expanded ref, with that, you are not committing to the json format (that could change in the future). You can achieve that, updating your lambda to Lambda(x => [ Select('id', x), Get(x) ])

Title: How to get an ID from Ref in fauna?

Body:
I'm fetching documents from faunadb and I would like their ID to be in the payload that I send to the client.

This is how I fetch the documents and return their data as a collection

serverClient.query(
  q.Map(
    q.Paginate(q.Documents(q.Collection('Portfolio')), { size: 999999 }),
      q.Lambda(x => q.Get(x))
    )
  )
  .then((ret) => ret.data.map(x => ({ ...x.data, _id: x.ref })))

Now _id is a Ref. Looking like this when I log it to the console:

Ref(Collection("Portfolio"), "266565241615155713")

And like this when JSON Stringifying it:

{"@ref":{"id":"266565241615155713","collection":{"@ref":{"id":"Portfolio","collection":{"@ref":{"id":"collections"}}}}}}

I basically need to get the ID 266565241615155713 from that Ref. How can I do that?
I tried x.ref['@ref'].id but @ref is undefined.
The documentation did not help me here

Thanks in advance for any hints.


问:
Python connecting SSAS with pyadomd
I've connected to my SSAS Cube using Python, however I'm having some problems with executing the MDX query. Here is the code that I've used:

```<code>from sys import path

path.append('\\Program Files\\Microsoft.NET\\ADOMD.NET\\140')

from pyadomd import Pyadomd

conn_str = 'connection_str'
query = """mdx_query"""

with Pyadomd(conn_str) as conn:
    with conn.cursor().execute(query) as cur:
        print(cur.fetchall())
</code>```

I've checked connection using print(conn.state) and everything is ok.

The error that I'm getting:

```<code>Traceback (most recent call last):
  File "C:/Users/kkrukows/PycharmProjects/test/main.py", line 22, in <module>
    with conn.cursor().execute(query) as cur:
  File "C:\Users\kkrukows\Anaconda3\envs\test\lib\site-packages\pyadomd\pyadomd.py", line 71, in execute
    adomd_type_map[self._reader.GetFieldType(i).ToString()].type_name
KeyError: 'System.Object'
</code>```

Anyone able to help?

答:
Please upgrade the package to version 0.0.6 and try again.

You can do that using pip:

pip install pyadomd --upgrade

Title: Python connecting SSAS with pyadomd

Body:
I've connected to my SSAS Cube using Python, however I'm having some problems with executing the MDX query. Here is the code that I've used:

from sys import path

path.append('\\Program Files\\Microsoft.NET\\ADOMD.NET\\140')

from pyadomd import Pyadomd

conn_str = 'connection_str'
query = """mdx_query"""

with Pyadomd(conn_str) as conn:
    with conn.cursor().execute(query) as cur:
        print(cur.fetchall())

I've checked connection using print(conn.state) and everything is ok.

The error that I'm getting:

Traceback (most recent call last):
  File "C:/Users/kkrukows/PycharmProjects/test/main.py", line 22, in <module>
    with conn.cursor().execute(query) as cur:
  File "C:\Users\kkrukows\Anaconda3\envs\test\lib\site-packages\pyadomd\pyadomd.py", line 71, in execute
    adomd_type_map[self._reader.GetFieldType(i).ToString()].type_name
KeyError: 'System.Object'

Anyone able to help?