问:
Read data from DynamoDB in Alexa Skill
I would like to create simple skill, where the user will be able to find out where the teacher has it´s cabinet. So basically something like this: "Alexa, where can i find teacher X?" "You can find teacher X in room Y".
I´ve managed to create DynamoDB table, where I have name of a teacher as primary key and room (their cabinet) as a primary sort key. It should be connected to lambda and my alexa skill correctly.
All I need is to tell Alexa which teacher I am looking for, teacher names are stored in the same intent in slots, then Alexa will check DynamoDB and search under the primary key for the name of a teacher pulled from slot and then tell me the room name from the primary sort key.
The code in Alexa is really troubling me.
I checked every answers and tutorials I could find on the Internet but either nothing worked for me, or it was too old, so that I couldn´t transform it into 2020 style of coding Alexa. My knowledge of json and backend programming in general is really minimal.
Can you give me some tips or some code i could follow? It seems to me, that something like this should be really simple, but it really isn´t, at least for me.
Thank you in advance for your help.</p>

答:
If I were to approach this design ....

Pre-Requisites :

AWS account : Lambda configured with the skill endpoint trigger and registered for the skill in the Alexa Developer Console

DynamoDB table with the schema you mentioned(primaryKey : teacherName, sortKey : room) in the same AWS account.

Looks like you are planning to create a composite primary key. It has it's benefits but go through here once for core components explanation to check if you do really need it.

https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.CoreComponents.html

SQS(optional)

https://aws.amazon.com/sqs/

Some suggestions on implementation :

Define good skill interaction model. Include AMAZON.Fallback Intent and implement that in your code. It will help in handling corner cases where you get slot values which you didn't expect or where your skill gets un-expected requests to handle. This will make sure that you always send graceful response to the customer.

Define slots with proper slot value types.

In code, when the lambda is triggered for your skill, after checking the canHandle method for your main functionality and validating that you have recieved request for the correct Intent - First make sure that the slot value is interpreted with good confidence ER MATCH. Here's an article for details on that :

https://developer.amazon.com/blogs/alexa/post/cfbd2f5e-c72f-4b03-8040-8628bbca204c/alexa-skill-teardown-understanding-entity-resolution-with-pet-match

I would advise you to create a data model to map your teacher-room data stored in DDB to your code.

This will help you in creating records programmatically in a clean way from code itself, also it defines kindof a contract for the DDB table access from your code.

Post that you can create a DDB Client in your handler method which will query the data from the teacher-room table and return a response to the customer with the room number if the entry is present else, will send graceful response to the customer.

You can follow here to understand programmatic access to DDB using java(or whatever you prefer, you'll find here) :

https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GettingStarted.Java.html

https://docs.amazonaws.cn/en_us/amazondynamodb/latest/developerguide/JavaDocumentAPICRUDExample.html

Once you get the valid data from DDB you can build and send the response to the customer with the same.

Also implement Fallback Intent in your code to handle situations you are not handling ion your custom defined intents.

(optional) You can use SQS to store erroneous events(that you catch from Fallback or are just exceptions), which you can later revisit, to debug and fix the issues in your service.

I hope this answer gives you some overview for the design and some basic practices to follow for a skill for this use-case.

Title: Read data from DynamoDB in Alexa Skill


来源: stackexchange

问:
Database Mirroring / Postgres Streaming Replication
I am not a DBA; I'm the primary developer of an enterprise database based application.

I'm currently specing out some new machines to upgrade our existing enterprise database. Currently we're running Postgres 8.4 with a database at our DR site that receives updates at intervals via some custom rsync work a former employee performed.

One of the major issues we're trying to tackle is latency between two global offices. We have staff in NY and staff in London. Currently, the London staffers suffer the fate of our VPN pipe. I'm not really in a position to change that infrastructure.

What I'd like to do is move to Postgres 9 and setup streaming replication. The slave would be in the London office, which would alleviate read problems for users. The problem I foresee is writes to the slave (not sure how PG handles this, my understanding is the slave is in read-only mode). Ideally, writes would be sent to the master in NY (writes are very infrequent from London, but necessary) by the database itself. Furthermore, I can setup fallover to have it act as a hot swappable backup (replacing the DR). Again, all contained within Postgres configuration with no additional code.

That's my idealized solution. How far off am I? Is this at all possible?

I'm a little overwhelmed by the breadth of this topic and Google is not really helping me. I would appreciate any advice from some experienced DBAs, with anecdotes, relevant documentation or examples.

Currently we're using SQLAlchemy as the primary interface to the database, if that's relevant. It does mean we're not tied to Postgres.

Thanks everyone.

答:
The PostgreSQL 9 documentation gives a nice overview of the options available.

http://www.postgresql.org/docs/9.0/static/different-replication-solutions.html

You might want to look at Slony if you do not mind having to write to the master and not the slave, or if you want, check out any of the multi-master replication technologies available.

ContentLicense: CC BY-SA 3.0


问:
How to display alert box with Xamarin.Forms for validation?
How to display alert box with Xamarin.Forms for validation?

I know that we can display alert using below code from ContentView code behind but I want to display alertbox from my ViewModel.

```<code>DisplayAlert ("Alert", "You have been alerted", "OK");
</code>```

I've registered my ViewModel against View with below code.

```<code>ViewFactory.Register<[ContentPage], [ContentPageViewModel]> ();
</code>```

答:
Using Rg.Plugins.Popup Nuget

(https://www.nuget.org/packages/Rg.Plugins.Popup/)

Define the popup like this:

>

```<code><popup:PopupPage xmlns="http://xamarin.com/schemas/2014/forms"
                 xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                 xmlns:popup="clr-namespace:Rg.Plugins.Popup.Pages;assembly=Rg.Plugins.Popup"...
</code>```

And in ViewModel (Using Prism):

>

```<code>await NavigationService.NavigateAsync("NavigationPage/[View]");
</code>```

Body:
How to display alert box with Xamarin.Forms for validation?

I know that we can display alert using below code from ContentView code behind but I want to display alertbox from my ViewModel.

DisplayAlert ("Alert", "You have been alerted", "OK");

I've registered my ViewModel against View with below code.

ViewFactory.Register<[ContentPage], [ContentPageViewModel]> ();

Body:
Using Rg.Plugins.Popup Nuget

(https://www.nuget.org/packages/Rg.Plugins.Popup/)

Define the popup like this:

>

<popup:PopupPage xmlns="http://xamarin.com/schemas/2014/forms"
                 xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                 xmlns:popup="clr-namespace:Rg.Plugins.Popup.Pages;assembly=Rg.Plugins.Popup"...

And in ViewModel (Using Prism):

>

await NavigationService.NavigateAsync("NavigationPage/[View]");

ContentLicense: CC BY-SA 4.0


问:
Calculate unit value based multiple conditions and columns in Python
Given a dataframe as follows:

```<code>   id    area  total_price unit
0   1  185.00        14840    m
1   2  215.00        15050    m
2   3  233.23        46799    d
3   4  122.00        17000    d
4   5  540.00        70000    d
5   6  415.00        78000    d
6   7  170.00        12270    m
7   8  410.00        30750    m
8   9  196.00        13787    m
9  10   55.00         3100    m
</code>```

I would like to create a new column unit_price with numerical value based on the following conditions:

a. if unit is m, then unit_price is calculated by total_price/area/30;

b. if unit is d, then unit_price is calculated by total_price/area

This code works:

```<code>m = (df['unit'] == 'm')
df['unit_price'] = np.where(m, df['total_price']/df['area']/30, df['total_price']/df['area'])
</code>```

I have used also the code below but it raises an error: ValueError: Wrong number of items passed 256, placement implies 1

```<code>def unit_price(x):
    if x['unit'] == 'm':
        return x['total_price']/x['area']/30
    if x['unit'] == 'd':
        return x['total_price']/x['area']

df['unit_price'] = df.apply(unit_price, axis = 1)
</code>```

Anyone know why I get this error, and how to fix it? Thanks.

Body:
Given a dataframe as follows:

   id    area  total_price unit
0   1  185.00        14840    m
1   2  215.00        15050    m
2   3  233.23        46799    d
3   4  122.00        17000    d
4   5  540.00        70000    d
5   6  415.00        78000    d
6   7  170.00        12270    m
7   8  410.00        30750    m
8   9  196.00        13787    m
9  10   55.00         3100    m

I would like to create a new column unit_price with numerical value based on the following conditions:

a. if unit is m, then unit_price is calculated by total_price/area/30;

b. if unit is d, then unit_price is calculated by total_price/area

This code works:

m = (df['unit'] == 'm')
df['unit_price'] = np.where(m, df['total_price']/df['area']/30, df['total_price']/df['area'])

I have used also the code below but it raises an error: ValueError: Wrong number of items passed 256, placement implies 1

def unit_price(x):
    if x['unit'] == 'm':
        return x['total_price']/x['area']/30
    if x['unit'] == 'd':
        return x['total_price']/x['area']

df['unit_price'] = df.apply(unit_price, axis = 1)

Anyone know why I get this error, and how to fix it? Thanks.

Body:
With np.select you can do:

c1, c2 = df['unit']=='m', df['unit']=='d'

df['unit_price'] = np.select((c1,c2),
                             (df['total_price']/df['area']/30, df['total_price']/df['area']),
                             np.nan)

However, with this case, it's better to do a map:

units = {'m':30, 'd':1, 'y':365}

df['unit_price'] = df['total_price']/df['area'] / df['unit'].map(units)

Output:

   id    area  total_price unit  unit_price
0   1  185.00        14840    m    2.673874
1   2  215.00        15050    m    2.333333
2   3  233.23        46799    d  200.656005
3   4  122.00        17000    d  139.344262
4   5  540.00        70000    d  129.629630
5   6  415.00        78000    d  187.951807
6   7  170.00        12270    m    2.405882
7   8  410.00        30750    m    2.500000
8   9  196.00        13787    m    2.344728
9  10   55.00         3100    m    1.878788


问:
Flutter - Pop until a screen without route
I have a Flutter app that starts like this :

```<code>void main() async {

  // Check if user is logged in

  runApp(
    MaterialApp(
      home: (isLoggedIn) ? MainPage() : PageLogin(),
    ),
  );
}
</code>```

My MainPage (and my LoginPage) are just 2 regular Stateful Widgets.

```<code>class MainPage extends StatefulWidget {
  MainPage({Key key, this.selectedPageDefault = 0}) : super(key: key);

  @override
  _MainPageState createState() => _MainPageState();
}
</code>```

Let's say I have 2 more pages, just like MainPage : PageOne and PageTwo.

When I click on a button on MainPage, it takes me to PageOne, and when I click on a button on PageOne, it takes me to PageTwo.

I go to them using :

```<code>Navigator.of(context).push(
  MaterialPageRoute(
    builder: (context) => PageOne(), // Or PageTwo
  ),
);
</code>```

Now, when I click on a button in PageTwo, I want to go back to MainPage.

I could use Navigator.of(context).popUntil(...), however it needs to use routes, and I did not go to MainPage using a route.

This is just an example, but on the real app I have more than just 2 pages after MainPage, so I can't just use pushReplacement or a tricky way to achieve this.

How can I go back to MainPage ?

答:
You need to add settings like this

```<code>
Navigator.of(context).push(
  MaterialPageRoute(
    builder: (context) => MainPage(),
    settings : RouteSettings()..name = 'MainPage',
  ),
);
Navigator.of(context).push(
  MaterialPageRoute(
    builder: (context) => PageOne(),
    settings : RouteSettings()..name = 'PageOne',
  ),
);
Navigator.of(context).push(
  MaterialPageRoute(
    builder: (context) => PageTwo(),
    settings : RouteSettings()..name = 'PageTwo',
  ),
);
</code>```

and you can use this

```<code> Navigator.of(context).popUntil(ModalRoute.withName('MainPage'));
</code>```

Body:
I have a Flutter app that starts like this :

void main() async {

  // Check if user is logged in

  runApp(
    MaterialApp(
      home: (isLoggedIn) ? MainPage() : PageLogin(),
    ),
  );
}

My MainPage (and my LoginPage) are just 2 regular Stateful Widgets.

class MainPage extends StatefulWidget {
  MainPage({Key key, this.selectedPageDefault = 0}) : super(key: key);

  @override
  _MainPageState createState() => _MainPageState();
}

Let's say I have 2 more pages, just like MainPage : PageOne and PageTwo.

When I click on a button on MainPage, it takes me to PageOne, and when I click on a button on PageOne, it takes me to PageTwo.

I go to them using :

Navigator.of(context).push(
  MaterialPageRoute(
    builder: (context) => PageOne(), // Or PageTwo
  ),
);

Now, when I click on a button in PageTwo, I want to go back to MainPage.

I could use Navigator.of(context).popUntil(...), however it needs to use routes, and I did not go to MainPage using a route.

This is just an example, but on the real app I have more than just 2 pages after MainPage, so I can't just use pushReplacement or a tricky way to achieve this.

How can I go back to MainPage ?

Body:
You need to add settings like this

Navigator.of(context).push(
  MaterialPageRoute(
    builder: (context) => MainPage(),
    settings : RouteSettings()..name = 'MainPage',
  ),
);
Navigator.of(context).push(
  MaterialPageRoute(
    builder: (context) => PageOne(),
    settings : RouteSettings()..name = 'PageOne',
  ),
);
Navigator.of(context).push(
  MaterialPageRoute(
    builder: (context) => PageTwo(),
    settings : RouteSettings()..name = 'PageTwo',
  ),
);

and you can use this

 Navigator.of(context).popUntil(ModalRoute.withName('MainPage'));


问:
Sort List in Descending Order via Array Count
I'm trying to sort a list of data I get from my database in descending order by the amount of upvotes held in each record. This is what I have currently but does not work. NOTE: the upvotes field is a string[] array within the model class.

```<code>//Method to get all popular posts and display them in a list
    public async void GetPostInfo()
    {
        PostsMod = new ObservableCollection<IPosts>();
        var temp = await _postsProxy.GetAllPosts();

        if (temp != null)
        {
            if (temp.Count > 0)
            {
                var orderedList = temp.OrderByDescending(x => x.UpVoteId.Count()).ToList(); //Orders the records in descending order based on how many upvotes they contain, puts it into a new list

                foreach (var item in orderedList)
                {
                    PostsMod.Add(item);
                }
            }
            else
                PostsMod.Add(temp[0]);
        }
    }
</code>```

All posts are put into a var temp and then the temp list is supposed to be ordered in descending order via the amount of upvotes counted.Keep in mind that again the upvote field is a string[] array in the model class.

It comes up with an error message: System.ArgumentNullException: 'Value cannot be null. Parameter name: source'

EDIT: Sorry it was a mistake on my part, I made the stupid mistake of the fields in the model class not matching. Therefore resulting in my upvotes being null.

答:
System.ArgumentNullException: 'Value cannot be null. Parameter name: source' comes from a null IEnumerable<T> passed to a Linq extension method, the only one from your code being Count.

Try this:

var orderedList = temp.OrderByDescending(x => x.UpVoteId?.Count()).ToList();
```

<p>This will fail since <code>temp.Count</code> will be 0:</p>

```else
    PostsMod.Add(temp[0]);
```

<p>That being said and althought not part of the problem, you should not return a null here. You should always get a collection, empty or not or throw an exception instead of swallowing it.</p>

<pre class="lang-cs prettyprint-override"><code>if (temp != null)
</code>```

Body:
I'm trying to sort a list of data I get from my database in descending order by the amount of upvotes held in each record. This is what I have currently but does not work. NOTE: the upvotes field is a string[] array within the model class.

//Method to get all popular posts and display them in a list
    public async void GetPostInfo()
    {
        PostsMod = new ObservableCollection<IPosts>();
        var temp = await _postsProxy.GetAllPosts();

        if (temp != null)
        {
            if (temp.Count > 0)
            {
                var orderedList = temp.OrderByDescending(x => x.UpVoteId.Count()).ToList(); //Orders the records in descending order based on how many upvotes they contain, puts it into a new list

                foreach (var item in orderedList)
                {
                    PostsMod.Add(item);
                }
            }
            else
                PostsMod.Add(temp[0]);
        }
    }

All posts are put into a var temp and then the temp list is supposed to be ordered in descending order via the amount of upvotes counted.Keep in mind that again the upvote field is a string[] array in the model class.

It comes up with an error message: System.ArgumentNullException: 'Value cannot be null. Parameter name: source'

EDIT: Sorry it was a mistake on my part, I made the stupid mistake of the fields in the model class not matching. Therefore resulting in my upvotes being null.

Body:
System.ArgumentNullException: 'Value cannot be null. Parameter name: source' comes from a null IEnumerable<T> passed to a Linq extension method, the only one from your code being Count.

Try this:

var orderedList = temp.OrderByDescending(x => x.UpVoteId?.Count()).ToList();

This will fail since temp.Count will be 0:

else
    PostsMod.Add(temp[0]);

That being said and althought not part of the problem, you should not return a null here. You should always get a collection, empty or not or throw an exception instead of swallowing it.

if (temp != null)


问:
How can i run a function in azure using my own custom AuthorizationLevel?
I have published a Function App in Azure with AuthorizationLevel of Function. So i access the endpoint the user needs to have a key.
Can I change this so that I have my own key ?
The code i am using in the app is

```<code>        [FunctionName("MyFunction")]
        public static async Task<IActionResult> Run(
        [HttpTrigger(**"myownazurekey"**, "get", "post", Route = null)] HttpRequest req,
        ILogger log)
    {   .....
</code>```

So can i set myownazurekey in azure to be retrieved instead of using the defined master / default keys ?

答:
UPDATE

You need to read the offical document first.

You can use to send http requests in your C # code to obtain or modify the function key and host key (which can also include deletion, etc.). The use and storage of function key and host key are handled according to your business.

If u need HttpHelper.cs, you can see my code. https://github.com/Jason446620/ConsoleProj/blob/master/ODatafilter/HttpHelper.cs

Test in Postman

PRIVIOUS

You don't need **"myownazurekey"**,  in your code.  You can follow my step to create your custom key to access your function app.

Create function app in portal.

Go to resource, find Functions -> App Keys -> + New host key, then input name custonkey and value 0510wxwc.

Deploy your function apps.

Sample function code:

```<code>[FunctionName("MyFunction")]
public static async Task<IActionResult> Run1([HttpTrigger(AuthorizationLevel.Function,"get", "post", Route = null)] HttpRequest req,ILogger log)
{
    log.LogInformation("C# HTTP trigger function processed a request.");

    string name = req.Query["test"];

    return new OkObjectResult(name);
}
</code>```

Copy Url from portal like pic

.

Test in postman.

Body:
I have published a Function App in Azure with AuthorizationLevel of Function. So i access the endpoint the user needs to have a key.
Can I change this so that I have my own key ?
The code i am using in the app is

        [FunctionName("MyFunction")]
        public static async Task<IActionResult> Run(
        [HttpTrigger(**"myownazurekey"**, "get", "post", Route = null)] HttpRequest req,
        ILogger log)
    {   .....

So can i set myownazurekey in azure to be retrieved instead of using the defined master / default keys ?

Body:
UPDATE

You need to read the offical document first.

You can use to send http requests in your C # code to obtain or modify the function key and host key (which can also include deletion, etc.). The use and storage of function key and host key are handled according to your business.

If u need HttpHelper.cs, you can see my code. https://github.com/Jason446620/ConsoleProj/blob/master/ODatafilter/HttpHelper.cs

Test in Postman

PRIVIOUS

You don't need **"myownazurekey"**,  in your code.  You can follow my step to create your custom key to access your function app.

Create function app in portal.

Go to resource, find Functions -> App Keys -> + New host key, then input name custonkey and value 0510wxwc.

Deploy your function apps.

Sample function code:

[FunctionName("MyFunction")]
public static async Task<IActionResult> Run1([HttpTrigger(AuthorizationLevel.Function,"get", "post", Route = null)] HttpRequest req,ILogger log)
{
    log.LogInformation("C# HTTP trigger function processed a request.");

    string name = req.Query["test"];

    return new OkObjectResult(name);
}

Copy Url from portal like pic

.

Test in postman.


问:
File.readlines() not returning any strings; possible file not opening
I'm working on building a script for configuring disks automatically on linux systems. One of my functions is not working and for the life of me I cannot figure out why.

I've tested the code on pythontutor.com with no errors. When I run the code on my machine, I get no errors, but instead of the function returning data from the file "disks.txt" I get empty dictionaries.

I have tried to add print statements at different points in the process to see what is going on, but nothing prints.

Here is my function:

```<code>def check_for_disks():
    cmd = 'lsblk -l -o name,mountpoint'.split()
    driveDict = {}
    finalDict = {}
    diskFile = open("disks.txt", "w+")
    subprocess.Popen(cmd, stdout=diskFile)
    diskFile.close()
    diskFile = open("disks.txt", "r+")
    for line in diskFile.readlines():
        dictItem = line.split()
        try:
            driveDict[dictItem[0]] = dictItem[1]
        except(IndexError):
            driveDict[dictItem[0]] = "No MountPoint Defined"
    diskFile.close()
    for k, v in driveDict.items():
        if 'sd' in k:
            finalDict[k] = v
        else:
            pass
    return finalDict
</code>```

This part works flawlessly and creates the file I want, with the relevant information:

```<code>def check_for_disks():
    cmd = 'lsblk -l -o name,mountpoint'.split()
    driveDict = {}
    finalDict = {}
    diskFile = open("disks.txt", "w+")
    subprocess.Popen(cmd, stdout=diskFile)
    diskFile.close()
</code>```

This part fails:

```<code>diskFile = open("disks.txt", "r+")
for line in diskFile.readlines():
</code>```

It is seemingly just not opening the file. I've checked the file with ls -la and seen its permissions are fine aka -rw-rw-r--

I've tried with open("disks.txt", "a+") as diskFile:

I've tried the options "r", "r+", "a+"

I've run the script sudo

Any help is appreciated

PLEASE SAVE ME I'M GOING NUTS

答:
TLDR: the file is empty when you open it.

The following command opens a new thread, and the new thread, starts to write this file.

```<code>subprocess.Popen(cmd, stdout=diskFile)
</code>```

But at the same time, as the file is begin created you start to read the file. Two threads makes this command faster, but I don't think you need that. Simply, wait until the file is finished before reading it.

something like this, should do what you want

```<code>p = subprocess.Popen(cmd, stdout=diskFile)
p_status = p.wait() #finish writing the file before starting to read it
</code>```

Let me know if you really need to multiple threads, or if this snippet has any issues.

Body:
I'm working on building a script for configuring disks automatically on linux systems. One of my functions is not working and for the life of me I cannot figure out why.

I've tested the code on pythontutor.com with no errors. When I run the code on my machine, I get no errors, but instead of the function returning data from the file "disks.txt" I get empty dictionaries.

I have tried to add print statements at different points in the process to see what is going on, but nothing prints.

Here is my function:

def check_for_disks():
    cmd = 'lsblk -l -o name,mountpoint'.split()
    driveDict = {}
    finalDict = {}
    diskFile = open("disks.txt", "w+")
    subprocess.Popen(cmd, stdout=diskFile)
    diskFile.close()
    diskFile = open("disks.txt", "r+")
    for line in diskFile.readlines():
        dictItem = line.split()
        try:
            driveDict[dictItem[0]] = dictItem[1]
        except(IndexError):
            driveDict[dictItem[0]] = "No MountPoint Defined"
    diskFile.close()
    for k, v in driveDict.items():
        if 'sd' in k:
            finalDict[k] = v
        else:
            pass
    return finalDict

This part works flawlessly and creates the file I want, with the relevant information:

def check_for_disks():
    cmd = 'lsblk -l -o name,mountpoint'.split()
    driveDict = {}
    finalDict = {}
    diskFile = open("disks.txt", "w+")
    subprocess.Popen(cmd, stdout=diskFile)
    diskFile.close()

This part fails:

diskFile = open("disks.txt", "r+")
for line in diskFile.readlines():

It is seemingly just not opening the file. I've checked the file with ls -la and seen its permissions are fine aka -rw-rw-r--

I've tried with open("disks.txt", "a+") as diskFile:

I've tried the options "r", "r+", "a+"

I've run the script sudo

Any help is appreciated

PLEASE SAVE ME I'M GOING NUTS

Body:
TLDR: the file is empty when you open it.

The following command opens a new thread, and the new thread, starts to write this file.

subprocess.Popen(cmd, stdout=diskFile)

But at the same time, as the file is begin created you start to read the file. Two threads makes this command faster, but I don't think you need that. Simply, wait until the file is finished before reading it.

something like this, should do what you want

p = subprocess.Popen(cmd, stdout=diskFile)
p_status = p.wait() #finish writing the file before starting to read it

Let me know if you really need to multiple threads, or if this snippet has any issues.


问:
NodeJS vs Laravel with Mysql Database which one better in term of performance
I am developing a REST Back-End with MYSQL database,now i need to choose between which server side language its better in term of less server resources (CPU and Ram) consuming .

Let say for example, i have a POST end point for (register a new user account) and another GET end point for (getting the user info in JSON format). and i am expecting a high traffic on my website, which programming language will consume more server resources ?

I have googled to compare between both NodejS and Laravel, i found some websites showing a benchmark test with a favor of laravel and other website showing that NodeJS is better.

答:
With basic get/set DB operations there isn't going to be significant time in whichever language you choose.

Choose a language based on non-performance criteria and solve specific performance problems as they arise.

As you've tag load-balancing I assume you application is already horizontally scaleable.


问:
bouncing balls never stay calm on the ground
I try to create a very simple physics engine for my study (processing used for a interactive installation).

The target is to have a ground covered with balls that you can throw around with gestures (based on Kinect information).

Therefor I need to do some basic physic simulation like bouncing and thats what I started with. So there are just balls falling down and bouncing. I simulated the air resistance with a simple 0.995f multiplication on the speed if the ball moves up. Works nice and looks realistic. The main problem is, that the balls never stay calm on the ground. Instead they start to tremble on the ground. That means there is a movement of 1 or 2 pixels up and down.

How can I prevent that without implementing some "borders" on which I set the position directly to the bottom and the speed to zero?

My applet:

```<code>public class BubblePhysicApplet extends PApplet {
    public static int width = 640;
    public static int height = 480;
    long lastTime = -1;
    Bubble[] mBubbles = new Bubble[10];
    Random mRandom = new Random();

    public void setup() {
//      size(width, height, OPENGL);
        size(width, height, P2D);
        for (int i = 0; i < mBubbles.length; i++) {
            mBubbles[i] = new Bubble(mRandom.nextInt(width), mRandom.nextInt(height), 50);
        }
        lastTime = System.currentTimeMillis();
    }

    public void draw() {
        background(0);
        long tmp = System.currentTimeMillis();
        long elapsed = tmp - lastTime;
        for (Bubble bubble : mBubbles) {
            bubble.animate(elapsed);
            bubble.draw(this);
        }
        lastTime = System.currentTimeMillis();
    }
}
</code>```

The ball/bubble:

```<code>public class Bubble {
    float mX;
    float mY;
    float mSize;
    float mSpeedX = 0;
    float mSpeedY = 0;

    public Bubble(int x, int y, int size) {
        mX = x;
        mY = y;
        mSize = size;
    }

    public void draw(PApplet applet) {
        applet.stroke(255);
        applet.noFill();
        applet.ellipseMode(PApplet.CENTER);
        applet.ellipse(mX, mY, mSize, mSize);
    }

    public void animate(long elapsed) {
        updateSpeedY(elapsed);
        if (mSpeedX != 0 || mSpeedY != 0) {
            checkBorders();
        }
    }

    private void checkBorders() {
        if (mY > BubblePhysicApplet.height - mSize / 2) {
            mY = 2 * BubblePhysicApplet.height - (mY + mSize);
            mSpeedY = -mSpeedY;
        }
        if (mX > BubblePhysicApplet.width) {
            mX = BubblePhysicApplet.width - (mX - BubblePhysicApplet.width);
            mSpeedX = -mSpeedX;
        }
    }

    private void updateSpeedX() {

    }

    private void updateSpeedY(long elapsed) {
        mSpeedY += (elapsed / 1000f) * 9.81f;
        if (mSpeedY < 0) {
            mSpeedY *= 0.95f;
        }

        mY += mSpeedY;
    }
}
</code>```

答: in the same fashion you used a friction factor for the air, you can also include a friction factor for the contact with the ground, and which even higher values, so at each contact, it starts to lose eneger rapidly and finally stops</p>

Body:
I try to create a very simple physics engine for my study (processing used for a interactive installation).

The target is to have a ground covered with balls that you can throw around with gestures (based on Kinect information).

Therefor I need to do some basic physic simulation like bouncing and thats what I started with. So there are just balls falling down and bouncing. I simulated the air resistance with a simple 0.995f multiplication on the speed if the ball moves up. Works nice and looks realistic. The main problem is, that the balls never stay calm on the ground. Instead they start to tremble on the ground. That means there is a movement of 1 or 2 pixels up and down.

How can I prevent that without implementing some "borders" on which I set the position directly to the bottom and the speed to zero?

My applet:

public class BubblePhysicApplet extends PApplet {
    public static int width = 640;
    public static int height = 480;
    long lastTime = -1;
    Bubble[] mBubbles = new Bubble[10];
    Random mRandom = new Random();

    public void setup() {
//      size(width, height, OPENGL);
        size(width, height, P2D);
        for (int i = 0; i < mBubbles.length; i++) {
            mBubbles[i] = new Bubble(mRandom.nextInt(width), mRandom.nextInt(height), 50);
        }
        lastTime = System.currentTimeMillis();
    }

    public void draw() {
        background(0);
        long tmp = System.currentTimeMillis();
        long elapsed = tmp - lastTime;
        for (Bubble bubble : mBubbles) {
            bubble.animate(elapsed);
            bubble.draw(this);
        }
        lastTime = System.currentTimeMillis();
    }
}

The ball/bubble:

public class Bubble {
    float mX;
    float mY;
    float mSize;
    float mSpeedX = 0;
    float mSpeedY = 0;

    public Bubble(int x, int y, int size) {
        mX = x;
        mY = y;
        mSize = size;
    }

    public void draw(PApplet applet) {
        applet.stroke(255);
        applet.noFill();
        applet.ellipseMode(PApplet.CENTER);
        applet.ellipse(mX, mY, mSize, mSize);
    }

    public void animate(long elapsed) {
        updateSpeedY(elapsed);
        if (mSpeedX != 0 || mSpeedY != 0) {
            checkBorders();
        }
    }

    private void checkBorders() {
        if (mY > BubblePhysicApplet.height - mSize / 2) {
            mY = 2 * BubblePhysicApplet.height - (mY + mSize);
            mSpeedY = -mSpeedY;
        }
        if (mX > BubblePhysicApplet.width) {
            mX = BubblePhysicApplet.width - (mX - BubblePhysicApplet.width);
            mSpeedX = -mSpeedX;
        }
    }

    private void updateSpeedX() {

    }

    private void updateSpeedY(long elapsed) {
        mSpeedY += (elapsed / 1000f) * 9.81f;
        if (mSpeedY < 0) {
            mSpeedY *= 0.95f;
        }

        mY += mSpeedY;
    }
}


问:
How to subscribe to an observable once?
My function access() needs to subscribe once, each and every call.

In the snippet below, $valueChanges emits data to each change made. Calling access() without const $ = ... and  $.unsubscribe(), $valueChanges observable emits unnecessary streams of values.

Is there an rxjs operator/function that emits once in subscription inside a function? Even if the function is called multiple times the subscription emits once?

```<code>access() {
  const $ = $valueChanges.pipe(
    map((res) =>
      ...
    ),
  ).subscribe((res) => {

    ...

    $.unsubscribe();
  });
}
</code>```

答:
You can consider using the take() operator, and emit only the first value before completing.

According to the documentation, the take operator

```<code>Emit provided number of values before completing.
</code>```

This is how you can use it:

```<code>access() {
  valueChanges
    .pipe(
      map((res) =>
        ...
      ),
      take(1),
    ).subscribe((res) => {

      ...

    });
}
</code>```

Title: How to subscribe to an observable once?

Body:
My function access() needs to subscribe once, each and every call.

In the snippet below, $valueChanges emits data to each change made. Calling access() without const $ = ... and  $.unsubscribe(), $valueChanges observable emits unnecessary streams of values.

Is there an rxjs operator/function that emits once in subscription inside a function? Even if the function is called multiple times the subscription emits once?

access() {
  const $ = $valueChanges.pipe(
    map((res) =>
      ...
    ),
  ).subscribe((res) => {

    ...

    $.unsubscribe();
  });
}

Body:
You can consider using the take() operator, and emit only the first value before completing.

According to the documentation, the take operator

Emit provided number of values before completing.

This is how you can use it:

access() {
  valueChanges
    .pipe(
      map((res) =>
        ...
      ),
      take(1),
    ).subscribe((res) => {

      ...

    });
}


问:
member function referring to an object's member function
I'm a c++ noob so apologies in advance if this question is not properly structured.

I have a class which instantiates an object of a different class, I'd like for the member function of the main class (excuse my naive language) to be in turn referring to the member function of the object instantiated in the main class.

I've attached a snippet for reference

foo.h

```<code>class foo {
public :

int data;
void printFunc(){
cout<< "data is"<< data;
}

};
</code>```

bar.h

```<code>class bar {

public:
void updatebarr ();
}
</code>```

bar.cpp

```<code>bar::bar()
{
foo foo1;
foo1.data = 1;
// the line below is flagged as syntax error
// I want the object of type bar's updatebarr() function to be essentially be calling
// foo::PrintFunc(). I figured this "should" work as the signatures are identical.
this->updatebarr = &foo1.printFunc();
}
</code>```

The error I get is "Reference to non-static member function must be called",

答:
Pointers to member methods do not work the way you are trying.  Not only what you have is a syntax error, but it is also a logic error since foo1 will go out of scope and be destroyed when bar() exits, thus leaving updatebarr to call printFunc() on an invalid foo object.

For what you are attempting, you would need something more like this:

foo.h

class foo {
public :
    int data;
    void printFunc(){
        cout << "data is " << data;
    }
};
```

<p>bar.h</p>

<pre class="lang-cpp prettyprint-override"><code>#include "foo.h"

class bar {
private:
    foo foo1;
public:
    bar();
    void updatebarr();
};
</code>```

bar.cpp

#include "bar.h"

bar::bar()
{
    foo1.data = 1;
}

void bar::updatebarr()
{
    foo1.printFunc();
}
```

<p>main.cpp</p>

<pre class="lang-cpp prettyprint-override"><code>#include "bar.h"

int main()
{
    bar b;
    b.updatebarr();
    return 0;
}
</code>```

Live Demo

Alternatively, you can make updatebarr() be a std::function that calls printFunc() via a lambda, eg:

foo.h

class foo {
public :
    int data;
    void printFunc(){
      cout << "data is " << data;
    }
};
```

<p>bar.h</p>

<pre class="lang-cpp prettyprint-override"><code>#include <functional>
#include "foo.h"

class bar {
private:
    foo foo1;
public:
    bar();
    std::function<void()> updatebarr;
};
</code>```

bar.cpp

#include "bar.h"

bar::bar()
{
    foo1.data = 1;
    updatebarr = [&](){ foo1.printFunc(); };
}
```

<p>main.cpp</p>

<pre class="lang-cpp prettyprint-override"><code>#include "bar.h"

int main()
{
    bar b;
    b.updatebarr();
    return 0;
}
</code>```

Live Demo

In which case, you could then have the lambda capture a copy of the foo object instead, which will give you a result very close to your original attempt, eg:

foo.h

class foo {
public :
    int data;
    void printFunc() const {
      cout << "data is " << data;
    }
};
```

<p>bar.h</p>

<pre class="lang-cpp prettyprint-override"><code>#include <functional>

class bar {
public:
    bar();
    std::function<void()> updatebarr;
};
</code>```

bar.cpp

#include "bar.h"
#include "foo.h"

bar::bar()
{
    foo foo1;
    foo1.data = 1;
    updatebarr = [foo1](){ foo1.printFunc(); };
}
```

<p>main.cpp</p>

<pre class="lang-cpp prettyprint-override"><code>#include "bar.h"

int main()
{
    bar b;
    b.updatebarr();
    return 0;
}
</code>```

Live Demo

Body:
I'm a c++ noob so apologies in advance if this question is not properly structured.

I have a class which instantiates an object of a different class, I'd like for the member function of the main class (excuse my naive language) to be in turn referring to the member function of the object instantiated in the main class.

I've attached a snippet for reference

foo.h

class foo {
public :

int data;
void printFunc(){
cout<< "data is"<< data;
}

};

bar.h

class bar {

public:
void updatebarr ();
}

bar.cpp

bar::bar()
{
foo foo1;
foo1.data = 1;
// the line below is flagged as syntax error
// I want the object of type bar's updatebarr() function to be essentially be calling
// foo::PrintFunc(). I figured this "should" work as the signatures are identical.
this->updatebarr = &foo1.printFunc();
}

The error I get is "Reference to non-static member function must be called",

Body:
Pointers to member methods do not work the way you are trying.  Not only what you have is a syntax error, but it is also a logic error since foo1 will go out of scope and be destroyed when bar() exits, thus leaving updatebarr to call printFunc() on an invalid foo object.

For what you are attempting, you would need something more like this:

foo.h

class foo {
public :
    int data;
    void printFunc(){
        cout << "data is " << data;
    }
};

bar.h

#include "foo.h"

class bar {
private:
    foo foo1;
public:
    bar();
    void updatebarr();
};

bar.cpp

#include "bar.h"

bar::bar()
{
    foo1.data = 1;
}

void bar::updatebarr()
{
    foo1.printFunc();
}

main.cpp

#include "bar.h"

int main()
{
    bar b;
    b.updatebarr();
    return 0;
}

Live Demo

Alternatively, you can make updatebarr() be a std::function that calls printFunc() via a lambda, eg:

foo.h

class foo {
public :
    int data;
    void printFunc(){
      cout << "data is " << data;
    }
};

bar.h

#include <functional>
#include "foo.h"

class bar {
private:
    foo foo1;
public:
    bar();
    std::function<void()> updatebarr;
};

bar.cpp

#include "bar.h"

bar::bar()
{
    foo1.data = 1;
    updatebarr = [&](){ foo1.printFunc(); };
}

main.cpp

#include "bar.h"

int main()
{
    bar b;
    b.updatebarr();
    return 0;
}

Live Demo

In which case, you could then have the lambda capture a copy of the foo object instead, which will give you a result very close to your original attempt, eg:

foo.h

class foo {
public :
    int data;
    void printFunc() const {
      cout << "data is " << data;
    }
};

bar.h

#include <functional>

class bar {
public:
    bar();
    std::function<void()> updatebarr;
};

bar.cpp

#include "bar.h"
#include "foo.h"

bar::bar()
{
    foo foo1;
    foo1.data = 1;
    updatebarr = [foo1](){ foo1.printFunc(); };
}

main.cpp

#include "bar.h"

int main()
{
    bar b;
    b.updatebarr();
    return 0;
}

Live Demo


问:
How can I loop a jsonlite function on a data frame of urls?
I am trying to run a jsonlite function on a set of API URLs I accumulated. Specifically, I have a dataframe called url_df which has a column called URL with 162800 rows of API URLs. When I write a script and manually insert the each URL at a time it works perfectly fine. This is the script I use to run it manually on one URL at a time:

```<code>May28 <- 'https://example.example.com/example'.
May28 <- httr::GET(May28)
May28 <- httr::content(May28, as = 'text')
May28 <- jsonlite::fromJSON(May28)
dplyr::glimpse(May28)
May28 <- as.data.frame(May28)
write.table(May28, file="May28.csv", sep=",")
</code>```

However, because I have over 100K lines of API URLs to go through, I wanted to create a loop function that repeats the above function to each row (each API URL) in the column URL so that I don't have to manually cut and paste each URL to the script 100K+ times. So I saved this information to the dataframe called "url_df" and attempted the following code:

```<code>j <- 1

for (j in 1:nrow(url_df)){
    url <- url_df$URL[[j]] %>%
  getdata <- GET(url) %>%
  rawdata <- httr::content(getdata, as='text') %>%
  data <- jsonlite::fromJSON(rawdata)
  data_df <- as.data.frame(data)
    print(j)
  j <- j+1
  Sys.sleep(0.5)
}
</code>```

For some reason, it will not run. One of the errors I got were:

Error in jsonlite::fromJSON(rawdata) : object 'rawdata' not found.

One caveat that might be important: each API URL doesn't return just 1 data point value (e.g., 1). Instead, it returns a list of values (e.g., Sunday, 1, Tuesday, 2, etc).

Any ideas on why this might be happening or how I can overcome this?

After solving this first issue, I'd like to then rbind all of the data I collected if possible.

答:
Did you try without the %>%?
Also, you could try a reproducible example with mock api urls like https://jsonplaceholder.typicode.com/todos/1

Body:
I am trying to run a jsonlite function on a set of API URLs I accumulated. Specifically, I have a dataframe called url_df which has a column called URL with 162800 rows of API URLs. When I write a script and manually insert the each URL at a time it works perfectly fine. This is the script I use to run it manually on one URL at a time:

May28 <- 'https://example.example.com/example'.
May28 <- httr::GET(May28)
May28 <- httr::content(May28, as = 'text')
May28 <- jsonlite::fromJSON(May28)
dplyr::glimpse(May28)
May28 <- as.data.frame(May28)
write.table(May28, file="May28.csv", sep=",")

However, because I have over 100K lines of API URLs to go through, I wanted to create a loop function that repeats the above function to each row (each API URL) in the column URL so that I don't have to manually cut and paste each URL to the script 100K+ times. So I saved this information to the dataframe called "url_df" and attempted the following code:

j <- 1

for (j in 1:nrow(url_df)){
    url <- url_df$URL[[j]] %>%
  getdata <- GET(url) %>%
  rawdata <- httr::content(getdata, as='text') %>%
  data <- jsonlite::fromJSON(rawdata)
  data_df <- as.data.frame(data)
    print(j)
  j <- j+1
  Sys.sleep(0.5)
}

For some reason, it will not run. One of the errors I got were:

Error in jsonlite::fromJSON(rawdata) : object 'rawdata' not found.

One caveat that might be important: each API URL doesn't return just 1 data point value (e.g., 1). Instead, it returns a list of values (e.g., Sunday, 1, Tuesday, 2, etc).

Any ideas on why this might be happening or how I can overcome this?

After solving this first issue, I'd like to then rbind all of the data I collected if possible.


问:
NoSQL database design problem for notice management app?
I am trying to make a database in NoSQL for learning purpose

Its a simple Notice management (Add/ edit/ Delete notice from notice borad) application in PHP.

I have Memcached (Membase actually) where I can store data as key value pair.

For adding a notice, I am generating a unique id {using uniqueid()function} and storing notice detail in it. But the problem is,
1. How to list all the notices?

I also want to add serial key to Notices. To do that, I need to know the serial key of last inserted data. 2. How do I find out the last inserted Notice?

If find this question inappropriate, cuz this is somewhat relational datamodel (or you may say, it should be implemented in relational database), please let me know any use case scenario where I can use NoSQL to learn more about it.

答:
Natural connections between entities are relational - so every data model is well designed using relational schema. Almost every nosql schema could be represented in relational data model.

You use NoSQL where using standard relational model is not comfortable (for example when foreign components need to add their own data and you don't know it in advance) or you need better performance and scaling - then you denormalize your data in NoSQL schema.

MongoDB (http://www.mongodb.org/) is a good start point in NoSQL data because it allows you to mix denormalized schema with (almost) relational design.

Nice use case is to implement data model for custom form data storing - where number of fields and type of fields isn't known upfront

And about your questions:

I don't know membase well but if it's a simple key-value store the only solution is to create another key at which you store list of all id's - but concurrent updates are a big concern here

You can also store last insert id somewhere else (at other key) - here concurrent updates are easier to master


问:
Unity clamped UI Image is shaking
I am using the followng script to clamp the UI Image to the player in 2D game, but when the player is moving, the image is shaking a little. What am I doing wrong?</p>

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class HealthBarClamp : MonoBehaviour
{

    public Transform targetToFollow;
    Transform thisTransform;

    void Start()
    {
        thisTransform = transform;
    }

    void Update()
    {
        thisTransform.position = new Vector3(targetToFollow.position.x,
            targetToFollow.position.y + 1.5f, thisTransform.position.z);
    }
}
</code>```

答: You can try to make the health bar children of your target in the gameObject hierarchy, so that it moves along with it with no need of updating its position in a script. You can then enable/disable the health bar upon your needs if you need it to be seen or not</p>

Title: Unity clamped UI Image is shaking

Body:
I am using the followng script to clamp the UI Image to the player in 2D game, but when the player is moving, the image is shaking a little. What am I doing wrong?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class HealthBarClamp : MonoBehaviour
{

    public Transform targetToFollow;
    Transform thisTransform;

    void Start()
    {
        thisTransform = transform;
    }

    void Update()
    {
        thisTransform.position = new Vector3(targetToFollow.position.x,
            targetToFollow.position.y + 1.5f, thisTransform.position.z);
    }
}


问:
Python invalid syntax questions
Why does the code below return the error "SyntaxError: invalid syntax"

If(amount_paid==12):

I know it's basic but just starting out learning Python in Visual Studio Code

Thanks for any help,

Phil

答:
The issue in the upper case "If". Change to "if"

Parentheses are not mandatory, although, they should not affect anything in your case: if amount_paid == 12:

Title: Python invalid syntax questions


问:
How do I count conditionally in R
I have a list </p>

```<code>x <- c(1,2,3,4,5)
</code>```

<p>How do I count how many elements are over 3. So the output would be 2. </p>

答:
You can do like this:</p>

```<code>x <- list(1, 2, 3, 4, 5)
sum( x > 3 )
#Output: [1] 2
</code>```

Title: How do I count conditionally in R

Body:
I have a list

x <- c(1,2,3,4,5)

How do I count how many elements are over 3. So the output would be 2.

Body:
You can do like this:

x <- list(1, 2, 3, 4, 5)
sum( x > 3 )
#Output: [1] 2


问:
Creating a new dataframe based on unique columns
I have a dataframe-

```<code>df=pd.DataFrame({'city':['a','a','a','b','b','b'],'V':[1,2,3,1,2,3],'O':[33,44,55,66,77,88]})
</code>```

Now I wanted to create a new dataframe which has unique elements of column V along with the corresponding values from the 'O' column.
Output-

```<code>   city   1   2   3
0   a    33  44  55
1   b    66  77  88
</code>```

答:
You can use pivot_table for this:

```<code>df = df.pivot_table('O', ['city'], 'V')
print(df)

V      1   2   3
city
a     33  44  55
b     66  77  88
</code>```

Body:
I have a dataframe-

df=pd.DataFrame({'city':['a','a','a','b','b','b'],'V':[1,2,3,1,2,3],'O':[33,44,55,66,77,88]})

Now I wanted to create a new dataframe which has unique elements of column V along with the corresponding values from the 'O' column.
Output-

   city   1   2   3
0   a    33  44  55
1   b    66  77  88

Body:
You can use pivot_table for this:

df = df.pivot_table('O', ['city'], 'V')
print(df)

V      1   2   3
city
a     33  44  55
b     66  77  88


问:
How to get an object of Devcon output using PowerShell (winpe)?
I would like to select an object from Devcon.exe output.

```<code>PCI\VEN_8086&DEV_2822&SUBSYS_1790103C&REV_04\3&11583659&0&FA
    Name: Intel(R) Chipset SATA/PCIe RST Premium Controller
Driver node #0:
    Inf file is C:\Windows\INF\iastorav.inf
    Inf section is iaStorAVC_inst
    Driver description is Intel Chipset SATA RAID Controller
    Manufacturer name is Intel Corporation
    Provider name is Intel Corporation
    Driver date is 2/7/2018
    Driver version is 15.44.0.1010
    Driver node rank is 16711683
    Driver node flags are 00102044
        Inf is digitally signed
Driver node #1:
    Inf file is C:\Windows\INF\oem9.inf
    Inf section is iaStorAC_inst_8
    Driver description is Intel(R) Chipset SATA/PCIe RST Premium Controller
    Manufacturer name is Intel Corporation
    Provider name is Intel Corporation
    Driver date is 5/9/2019
    Driver version is 17.5.0.1017
    Driver node rank is 8388611
    Driver node flags are 00003044
        Inf is digitally signed
</code>```

I want to get the Driver version by mapping the Driver description .
I tried this way, but I can not get the Driver version.

```<code> $hardwareid = "PCI\VEN_8086&DEV_2822&SUBSYS_1790103C&REV_04"
 $Description = "Intel(R) Chipset SATA/PCIe RST Premium Controller"
 $DrNode = & .\devcon.exe /drivernodes "$hardwareid"
 $Ver = $DrNode | Where-Object {$_ -like "*$Description*"} | Select-Object Driver version
</code>```

Anyone can give idea please. Really appreciated!

答:
The trouble is devcon outputs text.  How about something like this using WMI?

```<code>Get-WmiObject Win32_PnPSignedDriver |
  where description -match 'apple solid state drive device' |
  select driverversion

driverversion
-------------
6.0.6400.0
</code>```

Ok, this worked for me in winpe.  I got it here:  https://superuser.com/questions/1438704/how-to-find-driver-version-for-all-devices-through-wmi/1438715#1438715  It gets the version of the driver from the file info.

```<code>get-wmiobject Win32_SystemDriver | select DisplayName,@{n="version";
  e={(get-item $_.pathname).VersionInfo.FileVersion}} |
  where displayname -match 'apple solid state drive'

DisplayName                    version
-----------                    -------
Apple Solid State Drive Device 6.0.6400.0
</code>```

Body:
I would like to select an object from Devcon.exe output.

PCI\VEN_8086&DEV_2822&SUBSYS_1790103C&REV_04\3&11583659&0&FA
    Name: Intel(R) Chipset SATA/PCIe RST Premium Controller
Driver node #0:
    Inf file is C:\Windows\INF\iastorav.inf
    Inf section is iaStorAVC_inst
    Driver description is Intel Chipset SATA RAID Controller
    Manufacturer name is Intel Corporation
    Provider name is Intel Corporation
    Driver date is 2/7/2018
    Driver version is 15.44.0.1010
    Driver node rank is 16711683
    Driver node flags are 00102044
        Inf is digitally signed
Driver node #1:
    Inf file is C:\Windows\INF\oem9.inf
    Inf section is iaStorAC_inst_8
    Driver description is Intel(R) Chipset SATA/PCIe RST Premium Controller
    Manufacturer name is Intel Corporation
    Provider name is Intel Corporation
    Driver date is 5/9/2019
    Driver version is 17.5.0.1017
    Driver node rank is 8388611
    Driver node flags are 00003044
        Inf is digitally signed

I want to get the Driver version by mapping the Driver description .
I tried this way, but I can not get the Driver version.

 $hardwareid = "PCI\VEN_8086&DEV_2822&SUBSYS_1790103C&REV_04"
 $Description = "Intel(R) Chipset SATA/PCIe RST Premium Controller"
 $DrNode = & .\devcon.exe /drivernodes "$hardwareid"
 $Ver = $DrNode | Where-Object {$_ -like "*$Description*"} | Select-Object Driver version

Anyone can give idea please. Really appreciated!

Body:
The trouble is devcon outputs text.  How about something like this using WMI?

Get-WmiObject Win32_PnPSignedDriver |
  where description -match 'apple solid state drive device' |
  select driverversion

driverversion
-------------
6.0.6400.0

Ok, this worked for me in winpe.  I got it here:  https://superuser.com/questions/1438704/how-to-find-driver-version-for-all-devices-through-wmi/1438715#1438715  It gets the version of the driver from the file info.

get-wmiobject Win32_SystemDriver | select DisplayName,@{n="version";
  e={(get-item $_.pathname).VersionInfo.FileVersion}} |
  where displayname -match 'apple solid state drive'

DisplayName                    version
-----------                    -------
Apple Solid State Drive Device 6.0.6400.0


问:
How do I augment images using keras ImageDataGenerator?
I have training set of 364 images stored in numpy array also its labels stored in a different numpy array(there are 8 labels to classify).The dataset being small I want to use augmentation but can only find resources which augment images if they are stored in specific folders according to the labels. So how can I augment images in real time using ImageDataGenerator. Thanks! </p>

答:
Solution

You should use flow instead of flow_from_directory. flow can take your numpy arrays. I am pasting code from coursera course.

training_images = training_images.reshape((27455,28,28,1))
testing_images = testing_images.reshape((7172,28,28,1))

# Create an ImageDataGenerator and do Image Augmentation
training_datagen = ImageDataGenerator(
      rescale = 1./255,
      rotation_range=40,
      width_shift_range=0.2,
      height_shift_range=0.2,
      shear_range=0.2,
      zoom_range=0.2,
      horizontal_flip=True,
      fill_mode='nearest')

validation_datagen = ImageDataGenerator(rescale = 1./255)

training_datagen.fit(training_images)
validation_datagen.fit(testing_images)

testing_labels = tf.one_hot(testing_labels, 25)
training_labels = tf.one_hot(training_labels, 25)

history = model.fit_generator(training_datagen.flow(
    training_images,
    y = training_labels,
    batch_size = 32
), epochs=15, validation_data = validation_datagen.flow(
    testing_images,
    y = testing_labels,
    batch_size = 32
), verbose = 1)
```
<h1>Edit 1</h1>
<p>Name of Coursera Course: <code>Convolutional Neural Networks in TensorFlow by deeplearning.ai</code></p>
<h3>How to know images increased or not</h3>
<p>fix <code>batch size</code> and see how many steps training takes to complete 1 epoch. From that you can infer, images are augmenting.</p>
<p>I believe this solution solves your problem. If yes accept it else comment below what's the problem?</p>
<h2>Edit 2</h2>
<pre class="lang-py prettyprint-override"><code># here's a more "manual" example
for e in range(epochs):
    print('Epoch', e)
    batches = 0
    for x_batch, y_batch in training_datagen.flow(x_train, y_train, batch_size=32):
        ##### Check each batch manually####
        batches += 1
</code>```

Augmenting particular images

check below article which will show you hoe to augment images one by one.

https://towardsdatascience.com/data-augmentation-techniques-in-python-f216ef5eed69

Body:
Solution

You should use flow instead of flow_from_directory. flow can take your numpy arrays. I am pasting code from coursera course.

training_images = training_images.reshape((27455,28,28,1))
testing_images = testing_images.reshape((7172,28,28,1))

# Create an ImageDataGenerator and do Image Augmentation
training_datagen = ImageDataGenerator(
      rescale = 1./255,
      rotation_range=40,
      width_shift_range=0.2,
      height_shift_range=0.2,
      shear_range=0.2,
      zoom_range=0.2,
      horizontal_flip=True,
      fill_mode='nearest')

validation_datagen = ImageDataGenerator(rescale = 1./255)

training_datagen.fit(training_images)
validation_datagen.fit(testing_images)

testing_labels = tf.one_hot(testing_labels, 25)
training_labels = tf.one_hot(training_labels, 25)

history = model.fit_generator(training_datagen.flow(
    training_images,
    y = training_labels,
    batch_size = 32
), epochs=15, validation_data = validation_datagen.flow(
    testing_images,
    y = testing_labels,
    batch_size = 32
), verbose = 1)

Edit 1

Name of Coursera Course: Convolutional Neural Networks in TensorFlow by deeplearning.ai

How to know images increased or not

fix batch size and see how many steps training takes to complete 1 epoch. From that you can infer, images are augmenting.

I believe this solution solves your problem. If yes accept it else comment below what's the problem?

Edit 2

# here's a more "manual" example
for e in range(epochs):
    print('Epoch', e)
    batches = 0
    for x_batch, y_batch in training_datagen.flow(x_train, y_train, batch_size=32):
        ##### Check each batch manually####
        batches += 1

Augmenting particular images

check below article which will show you hoe to augment images one by one.

https://towardsdatascience.com/data-augmentation-techniques-in-python-f216ef5eed69


问:
Spring boot 1.5.8 with jakson 2.10.0 object mapping issue
i have upgraded jakson api on spring boot 1.5.8 from jakson 2.8.0 to 2.10.0, since then mapping of object is behaving different.

when i am passing request body on springboot controller having propertyname cityCode
sample json

```<code>{
cityCode:DEL
}
</code>```

when adding jsonproperty mapping works fine

```<code>@JsonProperty("cityCode")
private String cityCode;
</code>```

but when i don't add @JsonProperty annotation
it looks for CityCode instead.
since json passed on request is

```<code>{
cityCode:DEL
}
</code>```

it assing

```<code>object{cityCode=null}
</code>```

please let me know if there is any property which i need to add on spring boot

because in most of my scenario i don't want to add @JsonProperty annotation to class fields

EDIT:

I enable log.level to trace i saw some message related to jackson

POJOPropertyBuilder - Unable to instantiate jackson 2.6 object. Using higher version of jackson.

EDIT2:

Adding Sample Model Class

```<code>import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

import java.io.Serializable;
import java.util.List;

@JsonIgnoreProperties(ignoreUnknown = true)
@ApiModel(value = "CityRequest")
public class CityRequest implements Serializable {
    private static final long serialVersionUID = 1L;

    @ApiModelProperty
    private String cityCode;

    @ApiModelProperty
    private String cityName;

    @ApiModelProperty
    private String area;

    @ApiModelProperty
    private List<String> areas;

    public String getCityCode() {
        return cityCode;
    }

    public void setCityCode(String cityCode) {
        this.cityCode = cityCode;
    }

    public String getCityName() {
        return cityName;
    }

    public void setCityName(String cityName) {
        this.cityName = cityName;
    }

    public String getArea() {
        return area;
    }

    public void setArea(String area) {
        this.area = area;
    }

    public List<String> getAreas() {
        return areas;
    }

    public void setAreas(List<String> areas) {
        this.areas = areas;
    }

    @Override
    public String toString() {
        return "CityRequest{" +
                "cityCode='" + cityCode + '\'' +
                ", cityName='" + cityName + '\'' +
                ", area='" + area + '\'' +
                ", areas=" + areas +
                '}';
    }
}
</code>```

on the controller method is being passed as

```<code>@ApiParam(value = "This field specifies the list of requests", required = true)
@Valid @RequestBody(required = true) CityRequest cityRequest
</code>```

答:
You might want to give this a try as an app property to configure Jackson globally.</p>

```<code>spring.jackson.property-naming-strategy=LOWER_CAMEL_CASE
</code>```

Body:
i have upgraded jakson api on spring boot 1.5.8 from jakson 2.8.0 to 2.10.0, since then mapping of object is behaving different.

when i am passing request body on springboot controller having propertyname cityCode
sample json

{
cityCode:DEL
}

when adding jsonproperty mapping works fine

@JsonProperty("cityCode")
private String cityCode;

but when i don't add @JsonProperty annotation
it looks for CityCode instead.
since json passed on request is

{
cityCode:DEL
}

it assing

object{cityCode=null}

please let me know if there is any property which i need to add on spring boot

because in most of my scenario i don't want to add @JsonProperty annotation to class fields

EDIT:

I enable log.level to trace i saw some message related to jackson

POJOPropertyBuilder - Unable to instantiate jackson 2.6 object. Using higher version of jackson.

EDIT2:

Adding Sample Model Class

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

import java.io.Serializable;
import java.util.List;

@JsonIgnoreProperties(ignoreUnknown = true)
@ApiModel(value = "CityRequest")
public class CityRequest implements Serializable {
    private static final long serialVersionUID = 1L;

    @ApiModelProperty
    private String cityCode;

    @ApiModelProperty
    private String cityName;

    @ApiModelProperty
    private String area;

    @ApiModelProperty
    private List<String> areas;

    public String getCityCode() {
        return cityCode;
    }

    public void setCityCode(String cityCode) {
        this.cityCode = cityCode;
    }

    public String getCityName() {
        return cityName;
    }

    public void setCityName(String cityName) {
        this.cityName = cityName;
    }

    public String getArea() {
        return area;
    }

    public void setArea(String area) {
        this.area = area;
    }

    public List<String> getAreas() {
        return areas;
    }

    public void setAreas(List<String> areas) {
        this.areas = areas;
    }

    @Override
    public String toString() {
        return "CityRequest{" +
                "cityCode='" + cityCode + '\'' +
                ", cityName='" + cityName + '\'' +
                ", area='" + area + '\'' +
                ", areas=" + areas +
                '}';
    }
}

on the controller method is being passed as

@ApiParam(value = "This field specifies the list of requests", required = true)
@Valid @RequestBody(required = true) CityRequest cityRequest

Body:
You might want to give this a try as an app property to configure Jackson globally.

spring.jackson.property-naming-strategy=LOWER_CAMEL_CASE


答:
I built myself sql script writer like this, it's pretty fast for my project since my previous PHP Backend is too slow (in my case)

```<code>const mysqlLib = require('mysql');
const ENV = require('../configs/env').ENV;
const database = ENV.database;
const mysql = mysqlLib.createPool(database);

function executeQuery(query) {
    return new Promise((resolve, reject) => {
        mysql.query(query, (err, result, fields) => {
            if (err) {
                console.log(query);
                return reject(err);
            }

            resolve(result);
        });
    });
}

function executeQueryGetFirst(query) {
    return new Promise((resolve, reject) => {
        mysql.query(query, (err, result, fields) => {
            if (err) {
                console.log(query);
                return reject(err);
            }

            result = JSON.parse(JSON.stringify(result));

            if (result.length == 0) {
                resolve(null);
            } else {
                resolve(result[0]);
            }
        });
    });
}

var Database = {
    getById(table, id) {
        var query = '';
        query += 'SELECT * FROM ' + table + ' ';
        query += 'WHERE Id = ' + id;
        query += ' LIMIT 1';

        return executeQueryGetFirst(query);
    },
    getAllById(table, id) {
        var query = '';
        query += 'SELECT * FROM ' + table + ' ';
        query += 'WHERE Id = ' + id;

        return executeQuery(query);
    },
    getByAttributes(table, attributes) {
        var query = 'SELECT * FROM ' + table;
        var whereQuery = '';

        for (prop in attributes) {
            if (whereQuery != '') {
                whereQuery += ' AND ';
            }

            if (attributes[prop] == null) {
                whereQuery += prop + ' IS NULL';
            } else {
                whereQuery += prop + ' = "' + attributes[prop] + '"';
            }
        }

        query += ' WHERE ' + whereQuery;
        query += ' LIMIT 1';

        return executeQueryGetFirst(query);
    },
    getAllByAttributes(table, attributes) {
        var query = 'SELECT * FROM ' + table;
        var whereQuery = '';

        for (prop in attributes) {
            if (whereQuery != '') {
                whereQuery += ' AND ';
            }

            if (attributes[prop] == null) {
                whereQuery += prop + ' IS NULL';
            } else {
                whereQuery += prop + ' = "' + attributes[prop] + '"';
            }
        }

        query += ' WHERE ' + whereQuery;

        return executeQuery(query);
    },
    getAll(table) {
        var query = 'SELECT * FROM ' + table;

        return executeQuery(query);
    },
    add(table, attributes) {
        var insertName = '(Id';
        var insertData = '(NULL';

        for (prop in attributes) {
            var value = attributes[prop];
            if (value != null) {
                value = '"' + value + '"';
            }

            insertName += ', ' + prop;
            insertData += ', ' + value;
        }

        insertName += ')';
        insertData += ')';

        var query = 'INSERT INTO ' + table + ' ' + insertName + ' VALUES ' + insertData;

        return executeQuery(query);
    },
    updateByID(table, id, attributes) {
        var query = 'UPDATE ' + table;
        var setQuery = '';

        for (prop in attributes) {
            if (setQuery != '') {
                setQuery += ', ';
            }

            setQuery += prop + ' = "' + attributes[prop] + '"';
        }

        query += ' SET ' + setQuery + ' WHERE Id = ' + id;

        return executeQuery(query);
    },
    updateByAttributes(table, findAttributes, attributes) {
        var query = 'UPDATE ' + table;
        var setQuery = '';
        var whereQuery = '';

        for (prop in attributes) {
            if (setQuery != '') {
                setQuery += ', ';
            }

            setQuery += prop + ' = "' + attributes[prop] + '"';
        }

        for (prop in findAttributes) {
            if (whereQuery != '') {
                whereQuery += ', ';
            }

            whereQuery += prop + ' = "' + findAttributes[prop] + '"';
        }

        query += ' SET ' + setQuery + ' WHERE ' + whereQuery;

        return executeQuery(query);
    },
    deleteById(table, id) {
        var query = 'DELETE FROM ' + table + ' WHERE Id = ' + id;

        return executeQuery(query);
    },
    deleteByAttributes(table, attributes) {
        var query = 'DELETE FROM ' + table;
        var whereQuery = '';

        for (prop in attributes) {
            if (whereQuery != '') {
                whereQuery += ' AND ';
            }

            whereQuery += prop + ' = "' + attributes[prop] + '"';
        }

        query += ' WHERE ' + whereQuery;

        return executeQuery(query);
    }
}

Database.executeQuery = executeQuery;
Database.executeQueryGetFirst = executeQueryGetFirst;

exports.Database = Database;
</code>```

Env config

```<code>var ENV = {
    isDev: true,
    database: {
        connectionLimit: 10,
        host: 'localhost',
        user: 'root',
        password: '',
        database: 'your_database'
    }
}

exports.ENV = ENV;
exports.ENV.port = ENV.isDev ? 15001 : 8887;
</code>```

Title: NodeJS vs Laravel with Mysql Database which one better in term of performance

Body:
I am developing a REST Back-End with MYSQL database,now i need to choose between which server side language its better in term of less server resources (CPU and Ram) consuming .

Let say for example, i have a POST end point for (register a new user account) and another GET end point for (getting the user info in JSON format). and i am expecting a high traffic on my website, which programming language will consume more server resources ?

I have googled to compare between both NodejS and Laravel, i found some websites showing a benchmark test with a favor of laravel and other website showing that NodeJS is better.

Body:
I built myself sql script writer like this, it's pretty fast for my project since my previous PHP Backend is too slow (in my case)

const mysqlLib = require('mysql');
const ENV = require('../configs/env').ENV;
const database = ENV.database;
const mysql = mysqlLib.createPool(database);

function executeQuery(query) {
    return new Promise((resolve, reject) => {
        mysql.query(query, (err, result, fields) => {
            if (err) {
                console.log(query);
                return reject(err);
            }

            resolve(result);
        });
    });
}

function executeQueryGetFirst(query) {
    return new Promise((resolve, reject) => {
        mysql.query(query, (err, result, fields) => {
            if (err) {
                console.log(query);
                return reject(err);
            }

            result = JSON.parse(JSON.stringify(result));

            if (result.length == 0) {
                resolve(null);
            } else {
                resolve(result[0]);
            }
        });
    });
}

var Database = {
    getById(table, id) {
        var query = '';
        query += 'SELECT * FROM ' + table + ' ';
        query += 'WHERE Id = ' + id;
        query += ' LIMIT 1';

        return executeQueryGetFirst(query);
    },
    getAllById(table, id) {
        var query = '';
        query += 'SELECT * FROM ' + table + ' ';
        query += 'WHERE Id = ' + id;

        return executeQuery(query);
    },
    getByAttributes(table, attributes) {
        var query = 'SELECT * FROM ' + table;
        var whereQuery = '';

        for (prop in attributes) {
            if (whereQuery != '') {
                whereQuery += ' AND ';
            }

            if (attributes[prop] == null) {
                whereQuery += prop + ' IS NULL';
            } else {
                whereQuery += prop + ' = "' + attributes[prop] + '"';
            }
        }

        query += ' WHERE ' + whereQuery;
        query += ' LIMIT 1';

        return executeQueryGetFirst(query);
    },
    getAllByAttributes(table, attributes) {
        var query = 'SELECT * FROM ' + table;
        var whereQuery = '';

        for (prop in attributes) {
            if (whereQuery != '') {
                whereQuery += ' AND ';
            }

            if (attributes[prop] == null) {
                whereQuery += prop + ' IS NULL';
            } else {
                whereQuery += prop + ' = "' + attributes[prop] + '"';
            }
        }

        query += ' WHERE ' + whereQuery;

        return executeQuery(query);
    },
    getAll(table) {
        var query = 'SELECT * FROM ' + table;

        return executeQuery(query);
    },
    add(table, attributes) {
        var insertName = '(Id';
        var insertData = '(NULL';

        for (prop in attributes) {
            var value = attributes[prop];
            if (value != null) {
                value = '"' + value + '"';
            }

            insertName += ', ' + prop;
            insertData += ', ' + value;
        }

        insertName += ')';
        insertData += ')';

        var query = 'INSERT INTO ' + table + ' ' + insertName + ' VALUES ' + insertData;

        return executeQuery(query);
    },
    updateByID(table, id, attributes) {
        var query = 'UPDATE ' + table;
        var setQuery = '';

        for (prop in attributes) {
            if (setQuery != '') {
                setQuery += ', ';
            }

            setQuery += prop + ' = "' + attributes[prop] + '"';
        }

        query += ' SET ' + setQuery + ' WHERE Id = ' + id;

        return executeQuery(query);
    },
    updateByAttributes(table, findAttributes, attributes) {
        var query = 'UPDATE ' + table;
        var setQuery = '';
        var whereQuery = '';

        for (prop in attributes) {
            if (setQuery != '') {
                setQuery += ', ';
            }

            setQuery += prop + ' = "' + attributes[prop] + '"';
        }

        for (prop in findAttributes) {
            if (whereQuery != '') {
                whereQuery += ', ';
            }

            whereQuery += prop + ' = "' + findAttributes[prop] + '"';
        }

        query += ' SET ' + setQuery + ' WHERE ' + whereQuery;

        return executeQuery(query);
    },
    deleteById(table, id) {
        var query = 'DELETE FROM ' + table + ' WHERE Id = ' + id;

        return executeQuery(query);
    },
    deleteByAttributes(table, attributes) {
        var query = 'DELETE FROM ' + table;
        var whereQuery = '';

        for (prop in attributes) {
            if (whereQuery != '') {
                whereQuery += ' AND ';
            }

            whereQuery += prop + ' = "' + attributes[prop] + '"';
        }

        query += ' WHERE ' + whereQuery;

        return executeQuery(query);
    }
}

Database.executeQuery = executeQuery;
Database.executeQueryGetFirst = executeQueryGetFirst;

exports.Database = Database;

Env config

var ENV = {
    isDev: true,
    database: {
        connectionLimit: 10,
        host: 'localhost',
        user: 'root',
        password: '',
        database: 'your_database'
    }
}

exports.ENV = ENV;
exports.ENV.port = ENV.isDev ? 15001 : 8887;


问:
Fetch new page when user clicks a button using Svelte and Sapper
I am stuck at the part that fetch more data when user clicks a button on bottom of a page using Svelte and Sapper.

Here is the code.

```<code> <script context="module">
  export function preload(page) {
    return this.fetch(`https://reqres.in/api/users?page=${$count}`) // I know this is not goint to work. but when the button is clicked, I want to fetch page 2 and merge it with page 1 data, show data in ascending order(page1, page2)
    .then(res1 => {
      return res1.json()
    }).then(res2 => {
      return {
        currentPage: res2.page,
        per_page: res2.per_page,
        notices: res2.data,
        total: res2.total,
        totalPage: res2.total_pages
      }
    })
  }
</script>

<script>
  import { count } from '../../store.js'; // export const count = writable(1); from store.js file
  export let currentPage; // 1
  export let per_page; // 6
  export let notices;
  export let total; // 12
  export let totalPage; // 2

  const handleClick= () => {
    if ($count < totalPage) {
      count.update(n => n + 1); // update count 1 to 2 and want to deliver changed value to fetch new page
    }
  }
</script>

<main>
  <div id="container">
    <h1 class="cont-tit">Notice Board</h1>

    <div class="noti-list-wrap">
    {#each notices as notice, i}
      <ul class="noti-list">
        <li>
          <a rel=prefetch href={`notice/${notice.id}`}>
            <p class="tit">{`${notice.first_name} ${notice.last_name}`}</p>
            <hr />
            <p class="date">
              {`notice no.${i}`}
            </p>
          </a>
        </li>
      </ul>
    {/each}
      <div class="show-more" on:click={handleClick}>show me more</div>
    </div>
  </div>
</main>

</code>```

At first I thought I could use $count to fetch page 2 data but import count store inside script context="module" won't work.

Is there a way to deliver changed value of store to function preload?

答:
Don't try to load the extra data inside preload. Instead, treat that as the initial data — which it is — and append to it the normal way.

This is a simplified version — it doesn't worry about error handling, race conditions, or an initial page other than 1 — to give a general idea of what I mean:

{#if currentPage < totalPage}
  <button on:click={load_more}>show me more</button>
{/if}
```

Body:
I am stuck at the part that fetch more data when user clicks a button on bottom of a page using Svelte and Sapper.

Here is the code.

Notice Board

    {#each notices as notice, i}

          <a rel=prefetch href={`notice/${notice.id}`}>

{`${notice.first_name} ${notice.last_name}`}

              {`notice no.${i}`}

    {/each}

show me more

At first I thought I could use $count to fetch page 2 data but import count store inside script context="module" won't work.

Is there a way to deliver changed value of store to function preload?

Body:
Don't try to load the extra data inside preload. Instead, treat that as the initial data — which it is — and append to it the normal way.

This is a simplified version — it doesn't worry about error handling, race conditions, or an initial page other than 1 — to give a general idea of what I mean:

<script context="module">
  export async function preload(page) {
    const res = await this.fetch('https://reqres.in/api/users?page=1');
    const data = await res.json();

    return {
      currentPage: data.page,
      per_page: data.per_page,
      notices: data.data,
      total: data.total,
      totalPage: data.total_pages
    };
  }
</script>

<script>
  export let currentPage;
  export let per_page;
  export let notices;
  export let total;
  export let totalPage;

  const load_more = async () => {
    currentPage += 1;
    const res = await fetch('https://reqres.in/api/users?page=' + currentPage);
    const data = await res.json();

    notices = notices.concat(data.data);
  };
</script>

<!-- other stuff -->
{#if currentPage < totalPage}
  <button on:click={load_more}>show me more</button>
{/if}


问:
WCF x509 Certificate Message Authentication works when built in VS 2019, but fails when self hosted
I've created a WCF service and a simple forms application to access it. So far, prior to adding the certificate stuff, it was all working perfectly and I was able to get a return from the service successfully.

After experimenting with certificates, I've been able to update the configs in the client and service so that when built from visual studio, the application works perfectly fine using the certificates.

My issue is when using a self hosting console app to host the service outside of visual studio, I get a "Secure channel cannot be opened because security negotiation with the endpoint has failed. This may be due to absent or incorrectly specified EndpointIdentity in the EndpointAddress used to create the channel." error.

Just wondering if anyone can see any glaring errors in my configs that could be causing this? Like I said, it works when visual studio mounts the service, but something in the self hosting causes the error.

FYI: The client trace just says the error i said above. Server trace doesn't even show up. WCFTestClient also says the service is being hosted.

Cheers!

Client:

```<code><configuration>
  <system.diagnostics>
    <sources>
      <source name="System.ServiceModel"
                 switchValue="Information, ActivityTracing"
                 propagateActivity="true">
        <listeners>
          <add name="traceListener"
              type="System.Diagnostics.XmlWriterTraceListener"
              initializeData="c:\Client.svclog"  />
        </listeners>
      </source>
    </sources>
  </system.diagnostics>
    <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
    </startup>
    <system.serviceModel>
      <behaviors>
        <endpointBehaviors>
          <behavior name="endpointCredentialsBehavior">
            <clientCredentials>
              <clientCertificate findValue="TraceCert"
                                 storeLocation="LocalMachine"
                                 x509FindType="FindBySubjectName"/>
            </clientCredentials>
          </behavior>
        </endpointBehaviors>
      </behaviors>
        <bindings>
            <wsHttpBinding>
                <binding name="clientBinding">
                    <security>
                        <message clientCredentialType="Certificate" />
                    </security>
                </binding>
            </wsHttpBinding>
        </bindings>
        <client>
            <endpoint address="http://localhost:8000/ContactTraceWCF" binding="wsHttpBinding"
                bindingConfiguration="clientBinding" contract="ContactTraceServer.IContactTraceServer"
                name="WSHttpBinding_IContactTraceWCF" behaviorConfiguration="endpointCredentialsBehavior">
                <identity>
                    <dns value="TraceRootCA" />
                </identity>
            </endpoint>
        </client>
    </system.serviceModel>
</configuration>
</code>```

Server:

```<code><configuration>
  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" />
  </system.web>
  <system.diagnostics>
    <sources>
      <source name="System.ServiceModel"
                 switchValue="Information, ActivityTracing"
                 propagateActivity="true">
        <listeners>
          <add name="traceListener"
              type="System.Diagnostics.XmlWriterTraceListener"
              initializeData= "c:\Server.svclog" />
        </listeners>
      </source>
    </sources>
  </system.diagnostics>
  <system.serviceModel>
    <services>
      <service name="ContactTraceWCF.ContactTraceServer">
        <endpoint address=""
                  binding="wsHttpBinding"
                  bindingConfiguration="WSHttpBinding_IContactTraceWCF"
                  contract="ContactTraceWCF.IContactTraceServer"
                  name="WSHttpBinding_IContactTraceWCF">
          <identity>
            <dns value="TraceRootCA" />
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8000/ContactTraceWCF" />
          </baseAddresses>
        </host>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata httpGetEnabled="True" httpsGetEnabled="True"/>
          <serviceDebug includeExceptionDetailInFaults="True" />
          <serviceCredentials>
            <serviceCertificate findValue="TraceRootCA"
                                storeLocation="CurrentUser"
                                x509FindType="FindBySubjectName"/>
            <clientCertificate>
              <authentication certificateValidationMode="None"/>
            </clientCertificate>
          </serviceCredentials>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <bindings>
      <wsHttpBinding>
        <binding name="WSHttpBinding_IContactTraceWCF">
          <security mode="Message">
            <message clientCredentialType="Certificate"/>
          </security>
        </binding>
      </wsHttpBinding>
    </bindings>
  </system.serviceModel>
</configuration>
</code>```

Host Console App:

```<code>    using (ServiceHost serviceHost = new ServiceHost(typeof(ContactTraceServer), new Uri("http://localhost:8000/ContactTraceWCF")))
    {
        try
        {
            serviceHost.AddServiceEndpoint(typeof(IContactTraceServer), new WSHttpBinding(), "");

            ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
            smb.HttpGetEnabled = true;
            serviceHost.Description.Behaviors.Add(smb);
            serviceHost.Open();

            Console.WriteLine("The service is ready.");
            Console.WriteLine("Press <ENTER> to terminate service.");
            Console.ReadLine();
            serviceHost.Close();
        }
        catch (TimeoutException timeProblem)
        {
            Console.WriteLine(timeProblem.Message);
            Console.ReadLine();
        }
        catch (CommunicationException commProblem)
        {
            Console.WriteLine(commProblem.Message);
            Console.ReadLine();
        }
    }
</code>```

答:
So after some testing, I found that when creating the self host, it doesn't pull from the WCF service's app.config, so you have to basically rewrite it when building the servicehost.

I've provided the code below that worked for me.

```<code>    using (ServiceHost serviceHost = new ServiceHost(typeof(ContactTraceServer), new Uri("http://localhost:8000/")))
    {
        try
        {
            var binding = new WSHttpBinding();
            binding.Security.Mode = SecurityMode.Message;
            binding.Security.Message.ClientCredentialType = MessageCredentialType.Certificate;
            serviceHost.AddServiceEndpoint(typeof(IContactTraceServer), binding, "ContactTraceWCF");
            serviceHost.Credentials.ServiceCertificate.SetCertificate(StoreLocation.CurrentUser, StoreName.My, X509FindType.FindBySubjectName, "TraceRootCA");
            serviceHost.Credentials.ClientCertificate.Authentication.CertificateValidationMode = System.ServiceModel.Security.X509CertificateValidationMode.None;
            ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
            smb.HttpGetEnabled = true;
            serviceHost.Description.Behaviors.Add(smb);
            serviceHost.Open();

            Console.WriteLine("The service is ready.");
            Console.WriteLine("Press <ENTER> to terminate service.");
            Console.ReadLine();
            serviceHost.Close();
        }
        catch (TimeoutException timeProblem)
        {
            Console.WriteLine(timeProblem.Message);
            Console.ReadLine();
        }
        catch (CommunicationException commProblem)
        {
            Console.WriteLine(commProblem.Message);
            Console.ReadLine();
        } catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
            Console.ReadLine();
        }
    }
</code>```

Body:
I've created a WCF service and a simple forms application to access it. So far, prior to adding the certificate stuff, it was all working perfectly and I was able to get a return from the service successfully.

After experimenting with certificates, I've been able to update the configs in the client and service so that when built from visual studio, the application works perfectly fine using the certificates.

My issue is when using a self hosting console app to host the service outside of visual studio, I get a "Secure channel cannot be opened because security negotiation with the endpoint has failed. This may be due to absent or incorrectly specified EndpointIdentity in the EndpointAddress used to create the channel." error.

Just wondering if anyone can see any glaring errors in my configs that could be causing this? Like I said, it works when visual studio mounts the service, but something in the self hosting causes the error.

FYI: The client trace just says the error i said above. Server trace doesn't even show up. WCFTestClient also says the service is being hosted.

Cheers!

Client:

<configuration>
  <system.diagnostics>
    <sources>
      <source name="System.ServiceModel"
                 switchValue="Information, ActivityTracing"
                 propagateActivity="true">
        <listeners>
          <add name="traceListener"
              type="System.Diagnostics.XmlWriterTraceListener"
              initializeData="c:\Client.svclog"  />
        </listeners>
      </source>
    </sources>
  </system.diagnostics>
    <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
    </startup>
    <system.serviceModel>
      <behaviors>
        <endpointBehaviors>
          <behavior name="endpointCredentialsBehavior">
            <clientCredentials>
              <clientCertificate findValue="TraceCert"
                                 storeLocation="LocalMachine"
                                 x509FindType="FindBySubjectName"/>
            </clientCredentials>
          </behavior>
        </endpointBehaviors>
      </behaviors>
        <bindings>
            <wsHttpBinding>
                <binding name="clientBinding">
                    <security>
                        <message clientCredentialType="Certificate" />
                    </security>
                </binding>
            </wsHttpBinding>
        </bindings>
        <client>
            <endpoint address="http://localhost:8000/ContactTraceWCF" binding="wsHttpBinding"
                bindingConfiguration="clientBinding" contract="ContactTraceServer.IContactTraceServer"
                name="WSHttpBinding_IContactTraceWCF" behaviorConfiguration="endpointCredentialsBehavior">
                <identity>
                    <dns value="TraceRootCA" />
                </identity>
            </endpoint>
        </client>
    </system.serviceModel>
</configuration>

Server:

<configuration>
  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" />
  </system.web>
  <system.diagnostics>
    <sources>
      <source name="System.ServiceModel"
                 switchValue="Information, ActivityTracing"
                 propagateActivity="true">
        <listeners>
          <add name="traceListener"
              type="System.Diagnostics.XmlWriterTraceListener"
              initializeData= "c:\Server.svclog" />
        </listeners>
      </source>
    </sources>
  </system.diagnostics>
  <system.serviceModel>
    <services>
      <service name="ContactTraceWCF.ContactTraceServer">
        <endpoint address=""
                  binding="wsHttpBinding"
                  bindingConfiguration="WSHttpBinding_IContactTraceWCF"
                  contract="ContactTraceWCF.IContactTraceServer"
                  name="WSHttpBinding_IContactTraceWCF">
          <identity>
            <dns value="TraceRootCA" />
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8000/ContactTraceWCF" />
          </baseAddresses>
        </host>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata httpGetEnabled="True" httpsGetEnabled="True"/>
          <serviceDebug includeExceptionDetailInFaults="True" />
          <serviceCredentials>
            <serviceCertificate findValue="TraceRootCA"
                                storeLocation="CurrentUser"
                                x509FindType="FindBySubjectName"/>
            <clientCertificate>
              <authentication certificateValidationMode="None"/>
            </clientCertificate>
          </serviceCredentials>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <bindings>
      <wsHttpBinding>
        <binding name="WSHttpBinding_IContactTraceWCF">
          <security mode="Message">
            <message clientCredentialType="Certificate"/>
          </security>
        </binding>
      </wsHttpBinding>
    </bindings>
  </system.serviceModel>
</configuration>

Host Console App:

    using (ServiceHost serviceHost = new ServiceHost(typeof(ContactTraceServer), new Uri("http://localhost:8000/ContactTraceWCF")))
    {
        try
        {
            serviceHost.AddServiceEndpoint(typeof(IContactTraceServer), new WSHttpBinding(), "");

            ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
            smb.HttpGetEnabled = true;
            serviceHost.Description.Behaviors.Add(smb);
            serviceHost.Open();

            Console.WriteLine("The service is ready.");
            Console.WriteLine("Press <ENTER> to terminate service.");
            Console.ReadLine();
            serviceHost.Close();
        }
        catch (TimeoutException timeProblem)
        {
            Console.WriteLine(timeProblem.Message);
            Console.ReadLine();
        }
        catch (CommunicationException commProblem)
        {
            Console.WriteLine(commProblem.Message);
            Console.ReadLine();
        }
    }

Body:
So after some testing, I found that when creating the self host, it doesn't pull from the WCF service's app.config, so you have to basically rewrite it when building the servicehost.

I've provided the code below that worked for me.

    using (ServiceHost serviceHost = new ServiceHost(typeof(ContactTraceServer), new Uri("http://localhost:8000/")))
    {
        try
        {
            var binding = new WSHttpBinding();
            binding.Security.Mode = SecurityMode.Message;
            binding.Security.Message.ClientCredentialType = MessageCredentialType.Certificate;
            serviceHost.AddServiceEndpoint(typeof(IContactTraceServer), binding, "ContactTraceWCF");
            serviceHost.Credentials.ServiceCertificate.SetCertificate(StoreLocation.CurrentUser, StoreName.My, X509FindType.FindBySubjectName, "TraceRootCA");
            serviceHost.Credentials.ClientCertificate.Authentication.CertificateValidationMode = System.ServiceModel.Security.X509CertificateValidationMode.None;
            ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
            smb.HttpGetEnabled = true;
            serviceHost.Description.Behaviors.Add(smb);
            serviceHost.Open();

            Console.WriteLine("The service is ready.");
            Console.WriteLine("Press <ENTER> to terminate service.");
            Console.ReadLine();
            serviceHost.Close();
        }
        catch (TimeoutException timeProblem)
        {
            Console.WriteLine(timeProblem.Message);
            Console.ReadLine();
        }
        catch (CommunicationException commProblem)
        {
            Console.WriteLine(commProblem.Message);
            Console.ReadLine();
        } catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
            Console.ReadLine();
        }
    }