问:
Markup for buttons in JS-based Web-App
I have seen it said that the distinction between anchors and input buttons is obvious. Often on simple webforms it's indeed pretty cut and dried. But when working with web applications, often a link (ie direct forwarding to another page) makes more sense as a button and sometimes it's not clear what something ought to be.

Following the basis of applications, where basically any command that does anything (moving to another screen, saving work, getting help etc) is a button.

There's the practical consideration of using anchors that don't redirect the user to another page seeming strange; but is it better to call javascript from an anchor element?

Often buttons in web-apps are nested in li items, and in stackoverflow notice the 'Ask Question' button/link is in a list even though it's the only item (I assume this is to grab the correct styling).

What options and considerations should I take into account in coding the html element side of things for an interactive JS app?

答:
IMO, anchors are for when you are moving to a different screen, especially if you are going to update the URL hash to enable back button support.  So if the action is to view an item, or go to the edit page, etc. use a link.

Otherwise for actions such as 'delete', 'save', 'cancel' etc. I would use buttons.

Title: Markup for buttons in JS-based Web-App


来源: stackexchange

问:
Javascript Changing button inner text without chaning the icon
I created the following button, and want to change the inner text "test" to other word.

```<code>            <button type="button" id="test"><i class="fa-2x fa-regular fa-floppy-disk"></i>test</button>
</code>```

I tried below method it can change the word but also deleted the icon.

```<code>$('button#bkmarktest').on('click', function(e){
e.preventDefault();
$(this).text("other");
});
</code>```

Is there any way that can only change the word, but keeping the icon, thanks!

答:
I haven't use jQuery since very long so here's an example in vanilla javascript.

const btn = document.querySelector('#test');

btn.addEventListener('click', (e) => {
  e.preventDefault();
  // selecting span tag -> you can also give it a specific id or class if you want
  btn.children[1].innerText = 'other';
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet"/>
<button type="button" id="test">
  <i class="fa-2x fa-regular fa-floppy-disk"></i>
  <span>test</span>
</button></code>```

ContentLicense: CC BY-SA 4.0

Body:
I created the following button, and want to change the inner text "test" to other word.

            <button type="button" id="test">test</button>

I tried below method it can change the word but also deleted the icon.

$('button#bkmarktest').on('click', function(e){
e.preventDefault();
$(this).text("other");
});

Is there any way that can only change the word, but keeping the icon, thanks!

Body:
I haven't use jQuery since very long so here's an example in vanilla javascript.

const btn = document.querySelector('#test');

btn.addEventListener('click', (e) => {
  e.preventDefault();
  // selecting span tag -> you can also give it a specific id or class if you want
  btn.children[1].innerText = 'other';
})

<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet"/>
<button type="button" id="test">
  <i class="fa-2x fa-regular fa-floppy-disk"></i>
  <span>test</span>
</button>


问:
An exception occurred while executing a query: SQLSTATE[42883]: Undefined function: 7 ERROR: operator does not exist: json
I'm using PostgreSQL with Symfony.

I have a user table which is as below:

```<code>id | email         | roles
---------------------------------------
1  | abc@gmail.com | ["ROLE_IVM_USER"]
</code>```

The roles column is JSON type as shown above.

I want to get user list which has role of ROLE_IVM_USER using code below:

```<code>$queryBuilder
            ->andWhere(sprintf('%s.roles IN (:roles)', $rootAlias))
            ->setParameter('roles', [User::ROLE_IVM_USER]);
</code>```

which results in the below error:

```<code>An exception occurred while executing a query: SQLSTATE[42883]: Undefined function: 7 ERROR: operator does not exist: json = unknown\nLINE 1: ... u0_ WHERE u0_.organization_id = $1 AND u0_.roles IN ($2) OR...\n ^\nHINT: No operator matches the given name and argument types. You might need to add explicit type casts."
</code>```

I'm new to PostgreSQL let me know how to get users with the role of ROLE_IVM_USER

答:
You can do a LIKE instead of an IN :

$queryBuilder
  ->andWhere(sprintf('%s.roles LIKE :roles', $rootAlias))
  ->setParameter('roles', '%' . User::ROLE_IVM_USER . '%');
```

Body:
I'm using PostgreSQL with Symfony.

I have a user table which is as below:

id | email         | roles
---------------------------------------
1  | abc@gmail.com | ["ROLE_IVM_USER"]

The roles column is JSON type as shown above.

I want to get user list which has role of ROLE_IVM_USER using code below:

$queryBuilder
            ->andWhere(sprintf('%s.roles IN (:roles)', $rootAlias))
            ->setParameter('roles', [User::ROLE_IVM_USER]);

which results in the below error:

An exception occurred while executing a query: SQLSTATE[42883]: Undefined function: 7 ERROR: operator does not exist: json = unknown\nLINE 1: ... u0_ WHERE u0_.organization_id = $1 AND u0_.roles IN ($2) OR...\n ^\nHINT: No operator matches the given name and argument types. You might need to add explicit type casts."

I'm new to PostgreSQL let me know how to get users with the role of ROLE_IVM_USER


问:
Count the number of occurrences different final word types succeeding the string
Suppose I have a list of lists like this

```<code>l = [['a', 'paragraph', 'is'],
     ['a', 'paragraph', 'can'],
     ['a', 'dog', 'barks']]
</code>```

also suppose I have this smaller list a = ['a', 'paragraph'] I want to count the number of occurrences different final word types succeeding the string. Therefore, the answer in this case should be 2 since 'is' and 'can' succeed the string 'a paragraph'.

I was trying to do something like this

```<code>l.count(a)
</code>```

but that did not work and gives me 0.

Ill try to spell this idea out more clearly, we basically have this substring 'a paragraph' and there are two occurrences that have 'a paragraph' namely 'is' and 'can', therefore since there is 2 unique cases the answer is 2.

答:
Make a set of all the desired words:

```<code>myset = {item[2] for item in l if item[:2] == ['a', 'paragraph']}
</code>```

Then use len() of the set.

Body:
Suppose I have a list of lists like this

l = [['a', 'paragraph', 'is'],
     ['a', 'paragraph', 'can'],
     ['a', 'dog', 'barks']]

also suppose I have this smaller list a = ['a', 'paragraph'] I want to count the number of occurrences different final word types succeeding the string. Therefore, the answer in this case should be 2 since 'is' and 'can' succeed the string 'a paragraph'.

I was trying to do something like this

l.count(a)

but that did not work and gives me 0.

Ill try to spell this idea out more clearly, we basically have this substring 'a paragraph' and there are two occurrences that have 'a paragraph' namely 'is' and 'can', therefore since there is 2 unique cases the answer is 2.

Body:
Make a set of all the desired words:

myset = {item[2] for item in l if item[:2] == ['a', 'paragraph']}

Then use len() of the set.


问:
Google app engine Big table database with Python desktop applications
Just out of curiosity, do Big table can be used as back-end for data storage for DESKTOP applications(stand alone applications).

Suppose a scenario:

Application start and check automatically for Internet access.

Once connection exists, we can perform CRUD operation on Big table through application.

Is this possible? If yes,is there any documents/link available on this.

Thanks,
Sunil

答:
There is nothing "out of the box" to do this for you, but in theory this is no different from having a web-based GUI performing CRUD operations against the datastore. Your desktop app will still be communicating with your appengine app via HTTP requests.

You would still have to decide on how to structure you data in the datastore.

Choose an authentication mechanism (take a look at OAuth)

Write an API to deal with your CRUD requests (checkout protorpc)

Choose a serialization format that you will be communicating with (probably JSON)

Write a python client to communicate with your app (protorpc makes this really easy)

ContentLicense: CC BY-SA 3.0


问:
How to show number counts on terminal in linux
Please how can I count the list of numbers in a file

```<code>awk '{for(i=1;i<=NF;i++){if($i>=0 && $i<=25){print $i}}}'
</code>```

Using the command above I can display the range of numbers on the terminal but if there are so many it will be difficult to count them.  Please how can I show the count of the numbers on the terminal for example

```<code>1-20,
2-22,
3-23,
4-24,
etc
</code>```

I know I can use wc but I don't know how to infuse it into the command above

答:
Pipe the output to sort -n and uniq -c

```<code>awk '{for(i=1;i<=NF;i++){if($i>=0 && $i<=25){print $i}}}' filename | sort -n | uniq -c
</code>```

You need to sort first because uniq requires all the same elements to be consecutive.

Body:
Please how can I count the list of numbers in a file

awk '{for(i=1;i<=NF;i++){if($i>=0 && $i<=25){print $i}}}'

Using the command above I can display the range of numbers on the terminal but if there are so many it will be difficult to count them.  Please how can I show the count of the numbers on the terminal for example

1-20,
2-22,
3-23,
4-24,
etc

I know I can use wc but I don't know how to infuse it into the command above

Body:
Pipe the output to sort -n and uniq -c

awk '{for(i=1;i<=NF;i++){if($i>=0 && $i<=25){print $i}}}' filename | sort -n | uniq -c

You need to sort first because uniq requires all the same elements to be consecutive.


问:
Is it possible or how to compute additional iterations in C# Rfc2898DeriveBytes
I'd like to increase iteration count for existing passwords. Is it possible with Rfc2898DeriveBytes? My weak attempt obviously doesn't work:

```<code>class Program
{
    static void Main(string[] args)
    {
        byte[] salt = new byte[16];
        using (var c = new RNGCryptoServiceProvider())
        {
            c.GetBytes(salt);
        }

        byte[] password = Encoding.UTF8.GetBytes("password");

        const int currentIterationCount = 100;
        const int newIterationCount = 1000;

        byte[] partialHash = Compute(password, salt, currentIterationCount, 32);
        byte[] finalHash = Compute(partialHash, salt, newIterationCount - currentIterationCount, 32);

        byte[] onetimeHash = Compute(password, salt, newIterationCount, 32);

        Console.WriteLine(Convert.ToBase64String(finalHash));   // N2HOBoubZfcOV9my3SIH8+KH9khvtCUSoRDDWkJJpMg=
        Console.WriteLine(Convert.ToBase64String(onetimeHash)); // EnBixdGRX+Y6P1qNcKGYrbzxusn3b4Yvo3Shw7/8L7Y=
        Console.WriteLine(finalHash == onetimeHash);            // False

        Console.ReadKey(true);
    }

    private static byte[] Compute(byte[] valueToHash, byte[] salt, int iterations, int hashSize)
    {
        using (var pbkdf2 = new Rfc2898DeriveBytes(valueToHash, salt, iterations))
        {
            return pbkdf2.GetBytes(hashSize);
        }
    }
}
</code>```

I am also currently limited to .net standard 2.0/.net framework 4.7.2

答:
You can't increase the number of rounds without knowing the password as in every round PBKDF2-HMAC-SHA1 computes HMAC-SHA1(password, H) where H is the output of HMAC-SHA1 from the previous round.

Hence, a common solution is to remove all the old passwords from your database and require users to create new ones.

Also, as Andrew Morton has suggested, new hashes could be created on the fly for a short period of time when users log in.

In any case, an iteration count of 1000 is not much nowadays. You should use a higher value if you can afford it. You should also consider moving to a better password-hashing functions such as Argon2id.

Body:
I'd like to increase iteration count for existing passwords. Is it possible with Rfc2898DeriveBytes? My weak attempt obviously doesn't work:

class Program
{
    static void Main(string[] args)
    {
        byte[] salt = new byte[16];
        using (var c = new RNGCryptoServiceProvider())
        {
            c.GetBytes(salt);
        }

        byte[] password = Encoding.UTF8.GetBytes("password");

        const int currentIterationCount = 100;
        const int newIterationCount = 1000;

        byte[] partialHash = Compute(password, salt, currentIterationCount, 32);
        byte[] finalHash = Compute(partialHash, salt, newIterationCount - currentIterationCount, 32);

        byte[] onetimeHash = Compute(password, salt, newIterationCount, 32);

        Console.WriteLine(Convert.ToBase64String(finalHash));   // N2HOBoubZfcOV9my3SIH8+KH9khvtCUSoRDDWkJJpMg=
        Console.WriteLine(Convert.ToBase64String(onetimeHash)); // EnBixdGRX+Y6P1qNcKGYrbzxusn3b4Yvo3Shw7/8L7Y=
        Console.WriteLine(finalHash == onetimeHash);            // False

        Console.ReadKey(true);
    }

    private static byte[] Compute(byte[] valueToHash, byte[] salt, int iterations, int hashSize)
    {
        using (var pbkdf2 = new Rfc2898DeriveBytes(valueToHash, salt, iterations))
        {
            return pbkdf2.GetBytes(hashSize);
        }
    }
}

I am also currently limited to .net standard 2.0/.net framework 4.7.2


问:
Is there a way to theoretically concatenate two names to make a variable name that is already defined?
The objective of this code is basically to create dynamically named variables automatically at runtime, more specifically lists then loop through range of values based on how many lists I have then display them out as such. It seems to work when I define the variable I'm printing out as such

```<code>listNum = int(input("how many lists?: "))
for i in range(listNum+1):
    globals()[f"my_list{i}"] = []

print(my_list0)
</code>```

But when I try to loop through them so that I can display them it doesn't seem to work, giving me an error NameError: name 'my_list' is not defined

```<code>listNum = int(input("how many lists?: "))
for i in range(listNum+1):
    globals()[f"my_list{i}"] = []

for i in range(listNum):
    print(f"{my_list}+{i}")
</code>```

What may I be missing, because i'm trying to concatenate my_list with the value in the range so it can print out the variable that is there?

答:
```<code>print(f"{my_list}+{i}")
</code>```

is printing a string and the string is formatted from 2 variables: my_list which does not exist and i which exists. You want

```<code>print(globals()[f"my_list{i}"])
</code>```

I hope that this is only a theoretical question. Never do this in real code that someone needs to maintain. Having lists and dictionaries is typically enough, like so with lists:

```<code>manylists = []
for i in range(0, listNum):
    manylists.append([1,2,3])  # adds a list into the list. Tricky ;-)

print(manylists[8])  # make sure you enter a number higher than 8 initially
</code>```

Or with dictionaries:

```<code>manylists = {}
for i in range(0, listNum):
    manylists[f"list{i}"] = [1,2,3]  # the list has a name in this case

print(manylists["list8"])  # make sure you enter a number higher than 8
</code>```

Body:
The objective of this code is basically to create dynamically named variables automatically at runtime, more specifically lists then loop through range of values based on how many lists I have then display them out as such. It seems to work when I define the variable I'm printing out as such

listNum = int(input("how many lists?: "))
for i in range(listNum+1):
    globals()[f"my_list{i}"] = []

print(my_list0)

But when I try to loop through them so that I can display them it doesn't seem to work, giving me an error NameError: name 'my_list' is not defined

listNum = int(input("how many lists?: "))
for i in range(listNum+1):
    globals()[f"my_list{i}"] = []

for i in range(listNum):
    print(f"{my_list}+{i}")

What may I be missing, because i'm trying to concatenate my_list with the value in the range so it can print out the variable that is there?

Body:
print(f"{my_list}+{i}")

is printing a string and the string is formatted from 2 variables: my_list which does not exist and i which exists. You want

print(globals()[f"my_list{i}"])

I hope that this is only a theoretical question. Never do this in real code that someone needs to maintain. Having lists and dictionaries is typically enough, like so with lists:

manylists = []
for i in range(0, listNum):
    manylists.append([1,2,3])  # adds a list into the list. Tricky ;-)

print(manylists[8])  # make sure you enter a number higher than 8 initially

Or with dictionaries:

manylists = {}
for i in range(0, listNum):
    manylists[f"list{i}"] = [1,2,3]  # the list has a name in this case

print(manylists["list8"])  # make sure you enter a number higher than 8


问:
Dynamics CRM 2011 form jscript to retrieve lookup data
What are my mistakes, why do I get the "object expected" error, and, eventually, how does one debug jScript ?

I am new to Dynamics CRM and I would like to do a small customisation, which seem to require jScript. The instance (version 2011)  is used mostly to manage client support.

There are 2 custom entities with relationships:  FundLegalEntity --> SubFund

The Case (Incident) form is linked to the FundLegalEntity and the SubFund.

When user enters a SubFund I would like to have the FundLegalEntity filled automatically (if   empty).

My question was: how do I code that ?

With the help of this great tutorial, and the very usefull oData Tool, and great help (below) from user @dub, here is my latest code:

function recalcParent()
{
    var lookupValue = Xrm.Page.getAttribute("new_subfundid").getValue();

    var subFundId= lookupValue[0].id;
    // alert(subFundId);

    var request =  Xrm.Page.context.getServerUrl() +
        "/xrmServices/2011/OrganizationData.svc/new_subfundSet?" +
        "$select=new_LegalEntityId&" +
        "$filter=new_subfundId eq guid'"+ subFundId+ "'";
    // alert(request);

$.ajax({
    type: "GET",
    contentType: "application/json; charset=utf-8",
    datatype: "json",
    url: request,
    async: false,
    beforeSend:
        function (XMLHttpRequest)
        {
            XMLHttpRequest.setRequestHeader("Accept", "application/json");
        },
    success:
        function (data, textStatus, XmlHttpRequest)
        {
            var result = data.d.results[0];
            alert(result);
            var parentFundLookup = [{ entityType : "new_fund", id : result.LegalEntityId, name : result.FundLegalEntity}];
            // Set the value of the parent fund lookup
        },
    error:
        function (XmlHttpRequest, textStatus, errorThrown)
        {
            alert('Failed');
        }
    });

}
```

<p>I have no more errors, the first 2 alerts (commente out) are giving me correct results.
THe 3rd alert displays "object Object", and the control I expect to update is not updated.<br>
Any hint please ?  I suppose the last problem is in the <code>var parentFundLookup =</code> line...<br>
I am a bit confused by all these different names.<br>
Thanks !  </p>

<hr>

<h2>Edit:</h2>

<p>It's nearly working now: when I modify the sub-fund in the Incident, the Legal Entity gets updated with the correct legal entity name, but the text box has a strange aspect, and the icon at the left of the text box is strange as well. Here is the latest bit of code:  </p>

<pre class="lang-js prettyprint-override"><code>success:
    function (data, textStatus, XmlHttpRequest)
    {
        var result = data.d.results[0];
        //alert(result.new_LegalEntityId.Name);
        var parentFundLookup = [{ entityType : "new_LegalEntity", id : result.new_LegalEntityId.Id, name : result.new_LegalEntityId.Name}];
        Xrm.Page.getAttribute("new_fundlegalentityid").setValue(parentFundLookup);
    },
</code>```

I suspect that the problem lies in the entityType : "new_LegalEntity", but I don't know what to put in there. Any clue on this ? What does that represent ?

Here is a screenshot of the Legal Entity after the Sub-Fund is updated and the script has run.

答:
You can use the Rest endpoint from your script to retrieve data from the organization service.  Here's an example to get you started.  You can also look at the SDK documentation there's a lot of useful information there.

var subfundid; // get the id from the lookup

var request =
    Xrm.Page.context.getServerUrl() +
    "/XRMServices/2011/OrganizationData.svc/new_subfundSet?" +
        "$select=ParentId&" +
        "$top=1&" +
        "$filter=new_subfundId eq guid'"+ subfundid + "'";

$.ajax({
    type: "GET",
    contentType: "application/json; charset=utf-8",
    datatype: "json",
    url: request,
    async: false,
    beforeSend:
        function (XMLHttpRequest)
        {
            XMLHttpRequest.setRequestHeader("Accept", "application/json");
        },
    success:
        function (data, textStatus, XmlHttpRequest)
        {
            var result = data.d.results[0];
            var parentFundLookup = [{ entityType : "new_fund", id : result.ParentId, name : result.FundName}];
            // Set the value of the parent fund lookup
        },
    error:
        function (XmlHttpRequest, textStatus, errorThrown)
        {
            alert('Failed');
        }
    });
```

Since this code uses JQuery, you'll need to add the JQuery library as a web resource and include it in your form.  See CRM 2011 "$ is undefined"

Body:
What are my mistakes, why do I get the "object expected" error, and, eventually, how does one debug jScript ?

I am new to Dynamics CRM and I would like to do a small customisation, which seem to require jScript. The instance (version 2011)  is used mostly to manage client support.

There are 2 custom entities with relationships:  FundLegalEntity --> SubFund

The Case (Incident) form is linked to the FundLegalEntity and the SubFund.

When user enters a SubFund I would like to have the FundLegalEntity filled automatically (if   empty).

My question was: how do I code that ?

With the help of this great tutorial, and the very usefull oData Tool, and great help (below) from user @dub, here is my latest code:

function recalcParent()
{
    var lookupValue = Xrm.Page.getAttribute("new_subfundid").getValue();

    var subFundId= lookupValue[0].id;
    // alert(subFundId);

    var request =  Xrm.Page.context.getServerUrl() +
        "/xrmServices/2011/OrganizationData.svc/new_subfundSet?" +
        "$select=new_LegalEntityId&" +
        "$filter=new_subfundId eq guid'"+ subFundId+ "'";
    // alert(request);

$.ajax({
    type: "GET",
    contentType: "application/json; charset=utf-8",
    datatype: "json",
    url: request,
    async: false,
    beforeSend:
        function (XMLHttpRequest)
        {
            XMLHttpRequest.setRequestHeader("Accept", "application/json");
        },
    success:
        function (data, textStatus, XmlHttpRequest)
        {
            var result = data.d.results[0];
            alert(result);
            var parentFundLookup = [{ entityType : "new_fund", id : result.LegalEntityId, name : result.FundLegalEntity}];
            // Set the value of the parent fund lookup
        },
    error:
        function (XmlHttpRequest, textStatus, errorThrown)
        {
            alert('Failed');
        }
    });

}

I have no more errors, the first 2 alerts (commente out) are giving me correct results.
THe 3rd alert displays "object Object", and the control I expect to update is not updated.

Any hint please ?  I suppose the last problem is in the var parentFundLookup = line...

I am a bit confused by all these different names.

Thanks !

Edit:

It's nearly working now: when I modify the sub-fund in the Incident, the Legal Entity gets updated with the correct legal entity name, but the text box has a strange aspect, and the icon at the left of the text box is strange as well. Here is the latest bit of code:

success:
    function (data, textStatus, XmlHttpRequest)
    {
        var result = data.d.results[0];
        //alert(result.new_LegalEntityId.Name);
        var parentFundLookup = [{ entityType : "new_LegalEntity", id : result.new_LegalEntityId.Id, name : result.new_LegalEntityId.Name}];
        Xrm.Page.getAttribute("new_fundlegalentityid").setValue(parentFundLookup);
    },

I suspect that the problem lies in the entityType : "new_LegalEntity", but I don't know what to put in there. Any clue on this ? What does that represent ?

Here is a screenshot of the Legal Entity after the Sub-Fund is updated and the script has run.

Body:
You can use the Rest endpoint from your script to retrieve data from the organization service.  Here's an example to get you started.  You can also look at the SDK documentation there's a lot of useful information there.

var subfundid; // get the id from the lookup

var request =
    Xrm.Page.context.getServerUrl() +
    "/XRMServices/2011/OrganizationData.svc/new_subfundSet?" +
        "$select=ParentId&" +
        "$top=1&" +
        "$filter=new_subfundId eq guid'"+ subfundid + "'";

$.ajax({
    type: "GET",
    contentType: "application/json; charset=utf-8",
    datatype: "json",
    url: request,
    async: false,
    beforeSend:
        function (XMLHttpRequest)
        {
            XMLHttpRequest.setRequestHeader("Accept", "application/json");
        },
    success:
        function (data, textStatus, XmlHttpRequest)
        {
            var result = data.d.results[0];
            var parentFundLookup = [{ entityType : "new_fund", id : result.ParentId, name : result.FundName}];
            // Set the value of the parent fund lookup
        },
    error:
        function (XmlHttpRequest, textStatus, errorThrown)
        {
            alert('Failed');
        }
    });

Since this code uses JQuery, you'll need to add the JQuery library as a web resource and include it in your form.  See CRM 2011 "$ is undefined"


问:
how to solve this startActivityForResult
how to solve this kind of problem starActivityForResult please any budy guide me to solve this</p>

答:
startActivityForResult is deprecated, meaning that it will no longer be supported going forward. That is why Android Studio is showing you the lines through the code. Instead, review this Stackoverflow post on alternative options:
OnActivityResult method is deprecated, what is the alternative?


问:
For which reason this Angular Service is not working?
I created an Angular app with controller. I can successfully use the controller (with Postman, see screenshot below).

At the fronted I implemented a new component including service to show the data from controller (see code below). The service is not working. No data are shown at the application.

I made a breakpoint in feedback.service.ts/getFeedbacks() and in feedback.component.ts/ngOnInit(). Both are reached.

I mad a breakpoint at my controller and this one is never reached (except using postman).

Why doesn't the data from the controller reach the GUI?

feedback.component.html:

Feedback List:

       {{feedback.comment}}

Count: {{feedbacks.length}}

```
<p>feedback.component.ts:</p>
```import { Component, OnInit } from '@angular/core';
import { Feedback } from './feedback';
import { FeedbackService } from './feedback.service';

@Component({
  selector: 'app-feedback',
  templateUrl: './feedback.component.html',
  styleUrls: ['./feedback.component.css']
})
export class FeedbackComponent implements OnInit {
  feedbacks: Feedback[] = [];
    objects: any;

  constructor(private feedbackService: FeedbackService) { }

  ngOnInit(): void {
    this.feedbackService
      .getFeedbacks()
      .subscribe(feedbacks => this.feedbacks = feedbacks);
  }
}
```
<p>feedback.service.ts:</p>
```import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { Feedback } from './feedback';

@Injectable({
  providedIn: 'root'
})
export class FeedbackService {

  constructor(private http: HttpClient) { }

  getFeedbacks(): Observable<Feedback[]> {
    let result: Observable<Feedback[]>;
    result = this.http.get<Feedback[]>('/feedback');
    return result;
  }
}
```
<p>feedback.ts:</p>
```export interface Feedback {
    id:      number;
    comment: string;
    userId:  number;
}
```
<p>app.modules.ts:</p>
```// other imports ...
import { FeedbackComponent } from './feedback/feedback.component';
import { FeedbackService } from './feedback/feedback.service';

@NgModule({
  declarations: [
    AppComponent,
    NavMenuComponent,
    HomeComponent,
    FeedbackComponent
  ],
  imports: [
    BrowserModule.withServerTransition({ appId: 'ng-cli-universal' }),
    HttpClientModule,
    FormsModule,
    RouterModule.forRoot([
      { path: '', component: FeedbackComponent, pathMatch: 'full' }
    ]),
    BrowserAnimationsModule,
    MatToolbarModule
  ],
  providers: [FeedbackService],
  bootstrap: [AppComponent]
})
export class AppModule { }
```

Screenshot from browser:

答:
I changed the path to https://localhost:7235/feedback
and now the breakpoint at the controller is reached.

launchSettings.json:

{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:51641",
      "sslPort": 44377
    }
  },
  "profiles": {
    "Test3": {
      "commandName": "Project",
      "launchBrowser": true,
      "applicationUrl": "https://localhost:7235;http://localhost:5235",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development",
        "ASPNETCORE_HOSTINGSTARTUPASSEMBLIES": "Microsoft.AspNetCore.SpaProxy"
      }
    }, // .....```
</div>
</div>
</p>
<p>package.json:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>{
  "name": "test3",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "prestart": "node aspnetcore-https",
    "start": "run-script-os",
    "start:windows": "ng serve --port 44477 --ssl --ssl-cert %APPDATA%\\ASP.NET\\https\\%npm_package_name%.pem --ssl-key %APPDATA%\\ASP.NET\\https\\%npm_package_name%.key",
    "start:default": "ng serve --port 44477 --ssl --ssl-cert $HOME/.aspnet/https/${npm_package_name}.pem --ssl-key $HOME/.aspnet/https/${npm_package_name}.key",
    "build": "ng build",
    "build:ssr": "ng run Test3:server:dev",
    "watch": "ng build --watch --configuration development",
    "test": "ng test"
  },//...</code>```

app.csproj:

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>net6.0</TargetFramework>
    <Nullable>enable</Nullable>
    <IsPackable>false</IsPackable>
    <SpaRoot>ClientApp\</SpaRoot>
    <SpaProxyServerUrl>https://localhost:44477</SpaProxyServerUrl>
    <SpaProxyLaunchCommand>npm start</SpaProxyLaunchCommand>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup> // ...```

Body:
I created an Angular app with controller. I can successfully use the controller (with Postman, see screenshot below).

At the fronted I implemented a new component including service to show the data from controller (see code below). The service is not working. No data are shown at the application.

I made a breakpoint in feedback.service.ts/getFeedbacks() and in feedback.component.ts/ngOnInit(). Both are reached.

I mad a breakpoint at my controller and this one is never reached (except using postman).

Why doesn't the data from the controller reach the GUI?

feedback.component.html:

Feedback List:

       {{feedback.comment}}

Count: {{feedbacks.length}}

feedback.component.ts:

import { Component, OnInit } from '@angular/core';
import { Feedback } from './feedback';
import { FeedbackService } from './feedback.service';

@Component({
  selector: 'app-feedback',
  templateUrl: './feedback.component.html',
  styleUrls: ['./feedback.component.css']
})
export class FeedbackComponent implements OnInit {
  feedbacks: Feedback[] = [];
    objects: any;

  constructor(private feedbackService: FeedbackService) { }

  ngOnInit(): void {
    this.feedbackService
      .getFeedbacks()
      .subscribe(feedbacks => this.feedbacks = feedbacks);
  }
}

feedback.service.ts:

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { Feedback } from './feedback';

@Injectable({
  providedIn: 'root'
})
export class FeedbackService {

  constructor(private http: HttpClient) { }

  getFeedbacks(): Observable<Feedback[]> {
    let result: Observable<Feedback[]>;
    result = this.http.get<Feedback[]>('/feedback');
    return result;
  }
}

feedback.ts:

export interface Feedback {
    id:      number;
    comment: string;
    userId:  number;
}

app.modules.ts:

// other imports ...
import { FeedbackComponent } from './feedback/feedback.component';
import { FeedbackService } from './feedback/feedback.service';

@NgModule({
  declarations: [
    AppComponent,
    NavMenuComponent,
    HomeComponent,
    FeedbackComponent
  ],
  imports: [
    BrowserModule.withServerTransition({ appId: 'ng-cli-universal' }),
    HttpClientModule,
    FormsModule,
    RouterModule.forRoot([
      { path: '', component: FeedbackComponent, pathMatch: 'full' }
    ]),
    BrowserAnimationsModule,
    MatToolbarModule
  ],
  providers: [FeedbackService],
  bootstrap: [AppComponent]
})
export class AppModule { }

Screenshot from browser:

Body:
I changed the path to https://localhost:7235/feedback
and now the breakpoint at the controller is reached.

launchSettings.json:

{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:51641",
      "sslPort": 44377
    }
  },
  "profiles": {
    "Test3": {
      "commandName": "Project",
      "launchBrowser": true,
      "applicationUrl": "https://localhost:7235;http://localhost:5235",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development",
        "ASPNETCORE_HOSTINGSTARTUPASSEMBLIES": "Microsoft.AspNetCore.SpaProxy"
      }
    }, // .....

package.json:

{
  "name": "test3",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "prestart": "node aspnetcore-https",
    "start": "run-script-os",
    "start:windows": "ng serve --port 44477 --ssl --ssl-cert %APPDATA%\\ASP.NET\\https\\%npm_package_name%.pem --ssl-key %APPDATA%\\ASP.NET\\https\\%npm_package_name%.key",
    "start:default": "ng serve --port 44477 --ssl --ssl-cert $HOME/.aspnet/https/${npm_package_name}.pem --ssl-key $HOME/.aspnet/https/${npm_package_name}.key",
    "build": "ng build",
    "build:ssr": "ng run Test3:server:dev",
    "watch": "ng build --watch --configuration development",
    "test": "ng test"
  },//...

app.csproj:

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>net6.0</TargetFramework>
    <Nullable>enable</Nullable>
    <IsPackable>false</IsPackable>
    <SpaRoot>ClientApp\</SpaRoot>
    <SpaProxyServerUrl>https://localhost:44477</SpaProxyServerUrl>
    <SpaProxyLaunchCommand>npm start</SpaProxyLaunchCommand>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup> // ...


问:
parsing XML configuration file using Etree in python
Please help me parse a configuration file of the below prototype using lxml etree. I tried with for event, element with tostring.  Unfortunately I don't need the text, but the XML between

```<code><template name>
   <config>
 </template>
</code>```

for a given attribute.

I started with this code, but get a key error while searching for the attribute since it scans from start

```<code>config_tree = etree.iterparse(token_template_file)
for event, element in config_tree:

    if element.attrib['name']=="ad auth":
        print ("attrib reached. get XML before child ends")
</code>```

Since I am a newbie to XML and python, I am not sure how to go about it. Here is the config file:

```<code><Templates>

  <template name="config1">

    <request>

      <password>pass</password>

      <userName>username</userName>

      <appID>someapp</appID>

    </request>

  </template>

  <template name="config2">

    <request>

      <password>pass1</password>

      <userName>username1</userName>

      <appID>someapp</appID>

    </request>

  </template>

</Templates>
</code>```

Thanks in advance!

Expected Output:

Say the user requests the config2- then the output should look like:

```<code>   <request>

      <password>pass1</password>

      <userName>username1</userName>

      <appID>someapp</appID>

    </request>
</code>```

(I send this XML using httplib2 to a server for initial authentication)

FINAL CODE:

thanks to FC and Constantnius. Here is the final code:

```<code>    config_tree = etree.parse(token_template_file)
    for template in config_tree.iterfind("template"):

        if template.get("name") == "config2":
            element = etree.tostring(template.find("request"))

            print (template.get("name"))
            print (element)
</code>```

output:

```<code>     config2

    <request>

         <password>pass1</password>

          <userName>username1</userName>

          <appID>someapp</appID>

    </request>
</code>```

答:
You could try to iterate over all template elements in the XML and parse them with the following code:

```<code>for template in root.iterfind("template"):
    name = template.get("name")
    request = template.find(requst)
    password = template.findtext("request/password")
    username = ...
    ...
    # Do something with the values
</code>```

Body:
Please help me parse a configuration file of the below prototype using lxml etree. I tried with for event, element with tostring.  Unfortunately I don't need the text, but the XML between

<template name>
   <config>
 </template>

for a given attribute.

I started with this code, but get a key error while searching for the attribute since it scans from start

config_tree = etree.iterparse(token_template_file)
for event, element in config_tree:

    if element.attrib['name']=="ad auth":
        print ("attrib reached. get XML before child ends")

Since I am a newbie to XML and python, I am not sure how to go about it. Here is the config file:

<Templates>

  <template name="config1">

    <request>

      <password>pass</password>

      <userName>username</userName>

      <appID>someapp</appID>

    </request>

  </template>

  <template name="config2">

    <request>

      <password>pass1</password>

      <userName>username1</userName>

      <appID>someapp</appID>

    </request>

  </template>

</Templates>

Thanks in advance!

Expected Output:

Say the user requests the config2- then the output should look like:

   <request>

      <password>pass1</password>

      <userName>username1</userName>

      <appID>someapp</appID>

    </request>

(I send this XML using httplib2 to a server for initial authentication)

FINAL CODE:

thanks to FC and Constantnius. Here is the final code:

    config_tree = etree.parse(token_template_file)
    for template in config_tree.iterfind("template"):

        if template.get("name") == "config2":
            element = etree.tostring(template.find("request"))

            print (template.get("name"))
            print (element)

output:

     config2

    <request>

         <password>pass1</password>

          <userName>username1</userName>

          <appID>someapp</appID>

    </request>

Body:
You could try to iterate over all template elements in the XML and parse them with the following code:

for template in root.iterfind("template"):
    name = template.get("name")
    request = template.find(requst)
    password = template.findtext("request/password")
    username = ...
    ...
    # Do something with the values


问:
I get http://localhost:3000/api/auth/error in my NextJs application using google signin. Why?
Here is my [...nextauth].js file ...

```<code>import NextAuth from "next-auth";
import Providers from "next-auth/providers";

export default NextAuth({
  providers: [
    Providers.Google({
      clientId: process.env.GOOGLE_ID,
      clientSecret: process.env.GOOGLE_SECRET,
    }),
  ],
});
</code>```

Here is my header component where I want to pass the signin function...

```<code>import { signIn, signOut, useSession } from "next-auth/client";

function Header() {
    return(
     <div onClick={signIn}>
          <p>Sign In</p>
     </div>
    )
</code>```

When I click on it, it returns a 404 response yet I am supposed to see this below:

What am I missing?

答: I thing you should logout and try again , I clear session and cookies and resolved problem</p>

Body:
Here is my [...nextauth].js file ...

import NextAuth from "next-auth";
import Providers from "next-auth/providers";

export default NextAuth({
  providers: [
    Providers.Google({
      clientId: process.env.GOOGLE_ID,
      clientSecret: process.env.GOOGLE_SECRET,
    }),
  ],
});

Here is my header component where I want to pass the signin function...

import { signIn, signOut, useSession } from "next-auth/client";

function Header() {
    return(

Sign In

    )

When I click on it, it returns a 404 response yet I am supposed to see this below:

What am I missing?


问:
Custom Google Analytics API script is working, but running extremely slow
I am working on a project using the Google Analytics API for PHP.

Here is what I need to do: We have about 320 client websites that we track in our Google Analytics account. We are running into an issue where the Google Analytics code stops tracking (for various reasons) on some sites, and we would like to catch this issue before our clients catch it.

So, what I would like to accomplish is writing a script that checks all of our client sites within Google Analytics and calls the Reporting API and queries for the number of sessions for the last seven days. If there is no data over the last 7 days, the code is more than likely not tracking properly on the website.

I have created a new API project in Google and obtained a client email that I have added as a user with view permissions to each of my accounts within Google Analytics. I have a total of 63 accounts in my Google Analytics organized by state (New York Clients, Virginia Clients, Oregon Clients etc) and each of the accounts have multiple sub-accounts/profiles under each for a total of 320.

I have a script that is working, but it is taking a really long time to run. This script does work, as it gives me each profile in my Google Analytics that hasn’t had data over the last 7 days, but it takes about 65 seconds to run and sometimes I get a timeout error because of how long it is taking to run. I’m certain that this is because of the foreach loops that are making a TON of calls to the API. I feel like if I reduced the number of times I am calling the API, the script would run much faster. However, I’m not sure how I can code my script so that it makes fewer calls to the API.

Is there any way that I could speed up the script below by making fewer calls to the reporting API? Maybe I am going about this the wrong way and there is a more simple way to do what I want to accomplish?

Here is my working code currently:

```<code> // Load the Google API PHP Client Library.
 require_once __DIR__ . '/vendor/autoload.php';
 //initialize analytics
 $analytics = initializeAnalytics();
 //an array that I will be using below in the getProfileIds() function
 $ProfileIDWithDomain = array();
 //Calls a function to obtain all of the profile IDs to query against the Core reporting API
 $profiles = getProfileIds($analytics);
 //for each profile in the $ProfileIDWithDomain array query the reporting API to get data over
 last 7 days:

 foreach ($profiles as $key => $value){
     //$key is profile id $value is domain
     $results = getResults($analytics, $key);
     //print the results
     printResults($results,$key,$value);
 }

 function initializeAnalytics()
 {
   // Creates and returns the Analytics Reporting service object.

   // Use the developers console and download your service account
   // credentials in JSON format. Place them in this directory or
   // change the key file location if necessary.
   $KEY_FILE_LOCATION = __DIR__ . '/{KEY_FILE}';

   // Create and configure a new client object.
   $client = new Google_Client();
   $client->setApplicationName("GA Analytics Reporting");
   $client->setAuthConfig($KEY_FILE_LOCATION);
   $client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']);
   $analytics = new Google_Service_Analytics($client);

   return $analytics;
 }

 function getResults($analytics, $profileId) {
   // Calls the Core Reporting API and queries for the number of sessions
   // for the last seven days.
   return $analytics->data_ga->get(
        'ga:' . $profileId,
        '7daysAgo',
        'today',
        'ga:sessions');
 }

 function printResults($results, $profile,$domain) {
   // Parses the response from the Core Reporting API and prints
   // the profile name and total sessions.
   if (count($results->getRows()) < 1) {
     echo "<div class='item'>";
     print "No results found for $profile, domain name: $domain";
     echo "</div>";
   }
 }

 function getProfileIds($analytics) {

   // Get the list of accounts for the authorized user.
   $accounts = $analytics->management_accounts->listManagementAccounts();

   if (count($accounts->getItems()) > 0) {
     //get all 63 accounts in GA
     $items = $accounts->getItems();
     //array to store accounts
     $AccountIds = array();
     foreach ($items as $item) {
         //for each of the 63 accounts, store the account ID in an array
         $AccountIds[] = $item->getId();
     }
     //now for each Account ID, we will obtain the properties
     foreach ($AccountIds as $id){

         // Get the list of properties for the authorized user.
         $properties = $analytics->management_webproperties->listManagementWebproperties($id);
         //if there are more than on item in the properties list (multuple profiles under it)
         if (count($properties->getItems()) > 0) {
            $items = $properties->getItems();
            $i = 0;
            if(count($items) > 1){
            foreach($items as $item){
                  //for each item in the property list, get the id
                  $currentPropertyID = $item->getId();
                  //list management profiles for the id
                  $profiles = $analytics->management_profiles->listManagementProfiles($id, $currentPropertyID);
             if (count($profiles->getItems()) > 0) {
                  $user = $profiles->getItems();
                  // Store the ID with an associated URL/domain name
                  $ProfileIDWithDomain[$user[0]->getId()] = str_replace($removeChar, "", $items[$i]["websiteUrl"]);

                  } else {
                     throw new Exception('No views (profiles) found for this user.');
                  }
                  $i++;
              }
           }
           else{
              //only one item in the properties list
              $currentPropertyID = $items[0]->getId();
              //list management profiles for the id
              $profiles = $analytics->management_profiles->listManagementProfiles($id, $currentPropertyID);
              if (count($profiles->getItems()) > 0) {
                 $user = $profiles->getItems();
                 // Store the ID with an associated URL/domain name
                 $ProfileIDWithDomain[$user[0]->getId()] = str_replace($removeChar, "", $items[0]["websiteUrl"]);

              } else {
                 throw new Exception('No views (profiles) found for this user.');
              }
           }

         } else {
           throw new Exception('No properties found for this user.');
         }
     }
   } else {
     throw new Exception('No accounts found for this user.');
   }
   //return an associative array with ID => URL/Domain name for each profile
   return $ProfileIDWithDomain;
 }
</code>```

答:
+1 on using account summaries.

You might also reduce the number of calls by using the newer Analytics Reporting API v4

The reports.batchGet method can take 5 requests at a time. However I don't know if it is any faster than the v3 method you are using now.

Body:
I am working on a project using the Google Analytics API for PHP.

Here is what I need to do: We have about 320 client websites that we track in our Google Analytics account. We are running into an issue where the Google Analytics code stops tracking (for various reasons) on some sites, and we would like to catch this issue before our clients catch it.

So, what I would like to accomplish is writing a script that checks all of our client sites within Google Analytics and calls the Reporting API and queries for the number of sessions for the last seven days. If there is no data over the last 7 days, the code is more than likely not tracking properly on the website.

I have created a new API project in Google and obtained a client email that I have added as a user with view permissions to each of my accounts within Google Analytics. I have a total of 63 accounts in my Google Analytics organized by state (New York Clients, Virginia Clients, Oregon Clients etc) and each of the accounts have multiple sub-accounts/profiles under each for a total of 320.

I have a script that is working, but it is taking a really long time to run. This script does work, as it gives me each profile in my Google Analytics that hasn’t had data over the last 7 days, but it takes about 65 seconds to run and sometimes I get a timeout error because of how long it is taking to run. I’m certain that this is because of the foreach loops that are making a TON of calls to the API. I feel like if I reduced the number of times I am calling the API, the script would run much faster. However, I’m not sure how I can code my script so that it makes fewer calls to the API.

Is there any way that I could speed up the script below by making fewer calls to the reporting API? Maybe I am going about this the wrong way and there is a more simple way to do what I want to accomplish?

Here is my working code currently:

 // Load the Google API PHP Client Library.
 require_once __DIR__ . '/vendor/autoload.php';
 //initialize analytics
 $analytics = initializeAnalytics();
 //an array that I will be using below in the getProfileIds() function
 $ProfileIDWithDomain = array();
 //Calls a function to obtain all of the profile IDs to query against the Core reporting API
 $profiles = getProfileIds($analytics);
 //for each profile in the $ProfileIDWithDomain array query the reporting API to get data over
 last 7 days:

 foreach ($profiles as $key => $value){
     //$key is profile id $value is domain
     $results = getResults($analytics, $key);
     //print the results
     printResults($results,$key,$value);
 }

 function initializeAnalytics()
 {
   // Creates and returns the Analytics Reporting service object.

   // Use the developers console and download your service account
   // credentials in JSON format. Place them in this directory or
   // change the key file location if necessary.
   $KEY_FILE_LOCATION = __DIR__ . '/{KEY_FILE}';

   // Create and configure a new client object.
   $client = new Google_Client();
   $client->setApplicationName("GA Analytics Reporting");
   $client->setAuthConfig($KEY_FILE_LOCATION);
   $client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']);
   $analytics = new Google_Service_Analytics($client);

   return $analytics;
 }

 function getResults($analytics, $profileId) {
   // Calls the Core Reporting API and queries for the number of sessions
   // for the last seven days.
   return $analytics->data_ga->get(
        'ga:' . $profileId,
        '7daysAgo',
        'today',
        'ga:sessions');
 }

 function printResults($results, $profile,$domain) {
   // Parses the response from the Core Reporting API and prints
   // the profile name and total sessions.
   if (count($results->getRows()) < 1) {
     echo "
";
     print "No results found for $profile, domain name: $domain";
     echo "
";
   }
 }

 function getProfileIds($analytics) {

   // Get the list of accounts for the authorized user.
   $accounts = $analytics->management_accounts->listManagementAccounts();

   if (count($accounts->getItems()) > 0) {
     //get all 63 accounts in GA
     $items = $accounts->getItems();
     //array to store accounts
     $AccountIds = array();
     foreach ($items as $item) {
         //for each of the 63 accounts, store the account ID in an array
         $AccountIds[] = $item->getId();
     }
     //now for each Account ID, we will obtain the properties
     foreach ($AccountIds as $id){

         // Get the list of properties for the authorized user.
         $properties = $analytics->management_webproperties->listManagementWebproperties($id);
         //if there are more than on item in the properties list (multuple profiles under it)
         if (count($properties->getItems()) > 0) {
            $items = $properties->getItems();
            $i = 0;
            if(count($items) > 1){
            foreach($items as $item){
                  //for each item in the property list, get the id
                  $currentPropertyID = $item->getId();
                  //list management profiles for the id
                  $profiles = $analytics->management_profiles->listManagementProfiles($id, $currentPropertyID);
             if (count($profiles->getItems()) > 0) {
                  $user = $profiles->getItems();
                  // Store the ID with an associated URL/domain name
                  $ProfileIDWithDomain[$user[0]->getId()] = str_replace($removeChar, "", $items[$i]["websiteUrl"]);

                  } else {
                     throw new Exception('No views (profiles) found for this user.');
                  }
                  $i++;
              }
           }
           else{
              //only one item in the properties list
              $currentPropertyID = $items[0]->getId();
              //list management profiles for the id
              $profiles = $analytics->management_profiles->listManagementProfiles($id, $currentPropertyID);
              if (count($profiles->getItems()) > 0) {
                 $user = $profiles->getItems();
                 // Store the ID with an associated URL/domain name
                 $ProfileIDWithDomain[$user[0]->getId()] = str_replace($removeChar, "", $items[0]["websiteUrl"]);

              } else {
                 throw new Exception('No views (profiles) found for this user.');
              }
           }

         } else {
           throw new Exception('No properties found for this user.');
         }
     }
   } else {
     throw new Exception('No accounts found for this user.');
   }
   //return an associative array with ID => URL/Domain name for each profile
   return $ProfileIDWithDomain;
 }


问:
Getting empty file while converting XML to CSV file Pandas Python
This is my XML file

```<code><Lieferantenbestellungen>
  <Lieferantenbestellung>
    <Jahr>2021</Jahr>
    <Nummer>1</Nummer>
    <Datum>2021-01-07</Datum>
    <Lieferant_ID>459</Lieferant_ID>
    <Positionen>
      <Position Artikel="MCGPXO96" Bezeichnung="Refined Rubber Tuna" Menge="1" />
      <Position Artikel="IYTAFI28" Bezeichnung="Generic Cotton Chicken" Menge="8" />
    </Positionen>
  </Lieferantenbestellung>
</Lieferantenbestellungen>
</code>```

I want to extract the Lieferant_ID, Artikel, Bezeichnung, Bezeichnung and Menge from the file.

I have this python code:

```<code>with open('Lieferantenbestellungen.xml', 'r') as f:
    soup = BeautifulSoup(f.read(), 'lxml')

# Get the data you want
df = pd.DataFrame(list(zip(
  [el.text for el in soup.find_all('Lieferant_ID')],
  [el.text for el in soup.find_all('Artikel')],
  [el.text for el in soup.find_all('Bezeichnung')],
  [el.text for el in soup.find_all('Menge')]
)), columns=['Lieferant_ID', 'Artikel', 'Bezeichnung', 'Menge'])

# Dump to csv
df.to_csv('out.csv', index=False)
</code>```

When I run the code it generates the CSV file but it's empty. Does anyone have any idea of what am I doing wrong?

Expected CSV output:

Thanks in advance

答:
To parse xml, you need to do soup = BeautifulSoup(markup, "xml"), not "lxml".

When you do this, soup.find_all('Lieferant_ID') returns ['459'].

However, doing find_all() a bunch of times isn't a great idea because you have multiple Positionen tags per Lieferantenbestellung. Instead, I suggest you find_all("Lieferantenbestellung"), and then process each of these tags.

Also, for debugging, it's easier if you split your code over multiple lines instead of stuffing everything into a single line.

```<code>with open('Lieferantenbestellungen.xml', 'r') as f:
    soup = BeautifulSoup(f.read(), 'lxml')

rows = []
for tag in soup.find_all("Lieferantenbestellung")
    lief_id = tag.findChild("Lieferant_ID")
    if lief_id is None:
        continue
    for ptag in tag.findChild("Positionen").findChildren("Position"):
        row = dict() # Make a new row
        row["Lieferant_ID"] = lief_id.text
        row["Artikel"] = ptag.attrs["Artikel"]
        row["Bezeichnung"] = ptag.attrs["Bezeichnung"]
        row["Menge"] = ptag.attrs["Menge"]
        rows.append(row)
</code>```

Now, you can create your dataframe using pd.DataFrame.from_records()

```<code>pd.DataFrame.from_records(rows)

  Lieferant_ID   Artikel             Bezeichnung Menge
0          459  MCGPXO96     Refined Rubber Tuna     1
1          459  IYTAFI28  Generic Cotton Chicken     8

</code>```

Body:
This is my XML file

<Lieferantenbestellungen>
  <Lieferantenbestellung>
    <Jahr>2021</Jahr>
    <Nummer>1</Nummer>
    <Datum>2021-01-07</Datum>
    <Lieferant_ID>459</Lieferant_ID>
    <Positionen>
      <Position Artikel="MCGPXO96" Bezeichnung="Refined Rubber Tuna" Menge="1" />
      <Position Artikel="IYTAFI28" Bezeichnung="Generic Cotton Chicken" Menge="8" />
    </Positionen>
  </Lieferantenbestellung>
</Lieferantenbestellungen>

I want to extract the Lieferant_ID, Artikel, Bezeichnung, Bezeichnung and Menge from the file.

I have this python code:

with open('Lieferantenbestellungen.xml', 'r') as f:
    soup = BeautifulSoup(f.read(), 'lxml')

# Get the data you want
df = pd.DataFrame(list(zip(
  [el.text for el in soup.find_all('Lieferant_ID')],
  [el.text for el in soup.find_all('Artikel')],
  [el.text for el in soup.find_all('Bezeichnung')],
  [el.text for el in soup.find_all('Menge')]
)), columns=['Lieferant_ID', 'Artikel', 'Bezeichnung', 'Menge'])

# Dump to csv
df.to_csv('out.csv', index=False)

When I run the code it generates the CSV file but it's empty. Does anyone have any idea of what am I doing wrong?

Expected CSV output:

Thanks in advance

Body:
To parse xml, you need to do soup = BeautifulSoup(markup, "xml"), not "lxml".

When you do this, soup.find_all('Lieferant_ID') returns ['459'].

However, doing find_all() a bunch of times isn't a great idea because you have multiple Positionen tags per Lieferantenbestellung. Instead, I suggest you find_all("Lieferantenbestellung"), and then process each of these tags.

Also, for debugging, it's easier if you split your code over multiple lines instead of stuffing everything into a single line.

with open('Lieferantenbestellungen.xml', 'r') as f:
    soup = BeautifulSoup(f.read(), 'lxml')

rows = []
for tag in soup.find_all("Lieferantenbestellung")
    lief_id = tag.findChild("Lieferant_ID")
    if lief_id is None:
        continue
    for ptag in tag.findChild("Positionen").findChildren("Position"):
        row = dict() # Make a new row
        row["Lieferant_ID"] = lief_id.text
        row["Artikel"] = ptag.attrs["Artikel"]
        row["Bezeichnung"] = ptag.attrs["Bezeichnung"]
        row["Menge"] = ptag.attrs["Menge"]
        rows.append(row)

Now, you can create your dataframe using pd.DataFrame.from_records()

pd.DataFrame.from_records(rows)

  Lieferant_ID   Artikel             Bezeichnung Menge
0          459  MCGPXO96     Refined Rubber Tuna     1
1          459  IYTAFI28  Generic Cotton Chicken     8


问:
ModuleNotFoundError: No module named 'win32gui
sorry for potentially asking stupid questions but I am newbie, learning Python from YT videos.

I need to use Ptwin32 extension, and use the libraries there.

EDIT: using Windows 10

Dowloaded "pywin32-300.win-amd64-py3.9" from here "https://github.com/mhammond/pywin32/releases"

Using python 3.9.1 and PyCharm 2020.3.1.

On the beginning of my program I write:

import win32gui

import win32con

and then I get the message "ModuleNotFoundError: No module named 'win32gui'"

Tried to search for solutions but nothing worked so far.

Thx in advance for help.
Loonak

答:
I had the same problem & py -m pip install win32gui didn't solve it,
finally it was fixed using py -m pip install pywin32 as @Kenny Ostrom advised


问:
How to identify unique people in a MySQL table using more than one criteria
I have a ~200k record table dat of people with their identifying data as well as a test date and result, here's a dummy version:

```<code>+----+---------+----------+------------+----------+------------+--------+
| id | surname | forename | dob        | SchoolID | testDate   | result |
+----+---------+----------+------------+----------+------------+--------+
|  1 | Smith   | Mary     | 1980-04-11 | NULL     | 2005-10-12 |  14.32 |
|  2 | Smith   | Mary     | 1980-04-11 | 1234     | 2007-03-02 |   18.1 |
|  3 | Jones   | Kim      | 1978-10-24 | 4657     | 2002-04-14 |  24.31 |
|  4 | Jones   | Kim      | NULL       | 4567     | 2002-10-08 |  19.02 |
|  5 | Roberts | Kim      | 1978-10-24 | 4567     | 2003-12-18 |  14.19 |
|  6 | Roberts | Kim      | 1978-10-24 | 4567     | 2005-02-11 |  18.26 |
+----+---------+----------+------------+----------+------------+--------+
</code>```

I would like to identify people who have had more than one test, and create a new column uniqueID that gives unique people a new id. Sadly, my database is not very tidy so I need to use several criteria to separate these records into unique individuals:

surname, forename and dob are the same (since SchoolID is often missing or wrong)

surname, forename and SchoolID are the same (since D.O.B. is sometimes not entered, or
entered wrong)

forename, dob and SchoolID are the same (people sometimes get married)

etc.

In the example above, there are just two unique people in the table Mary Smith and Kim Roberts nee Jones, so this uniqueID column should end up being:

```<code>+----+----------+
| id | uniqueID |
+----+----------+
|  1 |        1 |
|  2 |        1 |
|  3 |        2 |
|  4 |        2 |
|  5 |        2 |
|  6 |        2 |
+----+----------+
</code>```

Although I've been dabbled a bit with MySQL for a few years I'm still a beginner. I've been searching and trying things for a few days, and so far I have managed this:

```<code>SELECT surname, forename, SchoolID
   FROM dat
   GROUP BY CONCAT(surname, forename, SchoolID);
</code>```

which is the second criterion, for example, (that I was planning to give an auto incrementing key to in a new table, then join back in as the unique ID), but I'm not getting very with these multiple criteria, so any help much appreciated!

Thanks
Nick

答: have you tried "SELECT distinct"?</p>

Body:
I have a ~200k record table dat of people with their identifying data as well as a test date and result, here's a dummy version:

+----+---------+----------+------------+----------+------------+--------+
| id | surname | forename | dob        | SchoolID | testDate   | result |
+----+---------+----------+------------+----------+------------+--------+
|  1 | Smith   | Mary     | 1980-04-11 | NULL     | 2005-10-12 |  14.32 |
|  2 | Smith   | Mary     | 1980-04-11 | 1234     | 2007-03-02 |   18.1 |
|  3 | Jones   | Kim      | 1978-10-24 | 4657     | 2002-04-14 |  24.31 |
|  4 | Jones   | Kim      | NULL       | 4567     | 2002-10-08 |  19.02 |
|  5 | Roberts | Kim      | 1978-10-24 | 4567     | 2003-12-18 |  14.19 |
|  6 | Roberts | Kim      | 1978-10-24 | 4567     | 2005-02-11 |  18.26 |
+----+---------+----------+------------+----------+------------+--------+

I would like to identify people who have had more than one test, and create a new column uniqueID that gives unique people a new id. Sadly, my database is not very tidy so I need to use several criteria to separate these records into unique individuals:

surname, forename and dob are the same (since SchoolID is often missing or wrong)

surname, forename and SchoolID are the same (since D.O.B. is sometimes not entered, or
entered wrong)

forename, dob and SchoolID are the same (people sometimes get married)

etc.

In the example above, there are just two unique people in the table Mary Smith and Kim Roberts nee Jones, so this uniqueID column should end up being:

+----+----------+
| id | uniqueID |
+----+----------+
|  1 |        1 |
|  2 |        1 |
|  3 |        2 |
|  4 |        2 |
|  5 |        2 |
|  6 |        2 |
+----+----------+

Although I've been dabbled a bit with MySQL for a few years I'm still a beginner. I've been searching and trying things for a few days, and so far I have managed this:

SELECT surname, forename, SchoolID
   FROM dat
   GROUP BY CONCAT(surname, forename, SchoolID);

which is the second criterion, for example, (that I was planning to give an auto incrementing key to in a new table, then join back in as the unique ID), but I'm not getting very with these multiple criteria, so any help much appreciated!

Thanks
Nick

Body: have you tried "SELECT distinct"?


答:
You want to match each item in the list against the smaller list. We start by subsetting the larger list to match the size of the smaller list. If it doesn't match, we continue, ignoring that item. If it does match, we add the next item to a set. The set is important because it handles uniqueness.</p>
```<code>items = [
    ['a', 'paragraph', 'is'],
    ['a', 'paragraph', 'can'],
    ['a', 'dog', 'barks']
]

check = ['a', 'paragraph']

check_len = len(check)
unique_words = set()
for item in items:
    if item[:check_len] != check:
        continue
    unique_words.add(item[-1])
print(len(unique_words))

2
</code>```

Title: Count the number of occurrences different final word types succeeding the string

Body:
Suppose I have a list of lists like this

l = [['a', 'paragraph', 'is'],
     ['a', 'paragraph', 'can'],
     ['a', 'dog', 'barks']]

also suppose I have this smaller list a = ['a', 'paragraph'] I want to count the number of occurrences different final word types succeeding the string. Therefore, the answer in this case should be 2 since 'is' and 'can' succeed the string 'a paragraph'.

I was trying to do something like this

l.count(a)

but that did not work and gives me 0.

Ill try to spell this idea out more clearly, we basically have this substring 'a paragraph' and there are two occurrences that have 'a paragraph' namely 'is' and 'can', therefore since there is 2 unique cases the answer is 2.

Body:
You want to match each item in the list against the smaller list. We start by subsetting the larger list to match the size of the smaller list. If it doesn't match, we continue, ignoring that item. If it does match, we add the next item to a set. The set is important because it handles uniqueness.

items = [
    ['a', 'paragraph', 'is'],
    ['a', 'paragraph', 'can'],
    ['a', 'dog', 'barks']
]

check = ['a', 'paragraph']

check_len = len(check)
unique_words = set()
for item in items:
    if item[:check_len] != check:
        continue
    unique_words.add(item[-1])
print(len(unique_words))

2


问:
Why VS Code contains emphasized items but no error?
I'm writing a React project in VS code. I met this problem in VS code. In my project, this folder shows Contains emphasized items and I know it means there is an error in my files. But in the picture:

,

I have checked all files but no error was found.  So this makes me feel confused.

I have searched this problem on google and found a similar GitHub issue. https://github.com/Microsoft/vscode/issues/54960

答: Select this tab from toolbar - View -> Problems  or  Ctrl + Shift + M and on bottom Terminal you will see whats problem is it.


问:
Ansible multiple inventory file
I am trying to use multiple inventory file and dynamic inventory with Ansible 1.4 and dev. Ansible returns No hosts matched.

I have a simulated scenario with two hosts file in a directory test the content of the directory is listed.

hosts1.ini

```<code>[group1]
test1    ansible_ssh_host=127.0.0.1
test2    ansible_ssh_host=127.0.0.2
[group2]
test3    ansible_ssh_host=127.0.0.3
</code>```

hosts2.ini

```<code>[group3]
test4     ansible_ssh_host=127.0.0.4
[group4]
test5    ansible_ssh_host=127.0.0.4
test6    ansible_ssh_host=127.0.0.5
</code>```

if I run ansible -i test --list-hosts all it returns No hosts matched.

I digged into the code and found dir.py with a small amended i got it too work. But I think i must have done something wrong and the hack is not required.
Any ideas on how to solve it ?

答:
You can also use INVENTORY_IGNORE_EXTS
i.e. in the ansible.cfg:

```<code>[inventory]
ignore_extensions = {{(REJECT_EXTS + ('.orig', '.cfg', '.retry'))}}
</code>```

or

```<code>[defaults]
inventory_ignore_extension = {{(REJECT_EXTS + ('.orig', '.cfg', '.retry'))}}
</code>```

or via environment variable

ANSIBLE_INVENTORY_IGNORE='{{(REJECT_EXTS + ('.orig', '.cfg', '.retry'))}}' ansible --list-hosts all
```

Title: Ansible multiple inventory file

Body:
I am trying to use multiple inventory file and dynamic inventory with Ansible 1.4 and dev. Ansible returns No hosts matched.

I have a simulated scenario with two hosts file in a directory test the content of the directory is listed.

hosts1.ini

[group1]
test1    ansible_ssh_host=127.0.0.1
test2    ansible_ssh_host=127.0.0.2
[group2]
test3    ansible_ssh_host=127.0.0.3

hosts2.ini

[group3]
test4     ansible_ssh_host=127.0.0.4
[group4]
test5    ansible_ssh_host=127.0.0.4
test6    ansible_ssh_host=127.0.0.5

if I run ansible -i test --list-hosts all it returns No hosts matched.

I digged into the code and found dir.py with a small amended i got it too work. But I think i must have done something wrong and the hack is not required.
Any ideas on how to solve it ?

Body:
You can also use INVENTORY_IGNORE_EXTS
i.e. in the ansible.cfg:

[inventory]
ignore_extensions = {{(REJECT_EXTS + ('.orig', '.cfg', '.retry'))}}

or

[defaults]
inventory_ignore_extension = {{(REJECT_EXTS + ('.orig', '.cfg', '.retry'))}}

or via environment variable

ANSIBLE_INVENTORY_IGNORE='{{(REJECT_EXTS + ('.orig', '.cfg', '.retry'))}}' ansible --list-hosts all


问:
Testing of existence of a repeated field in a protobuff message
I have a google protobuf message:

```<code>message Foo {
  required int bar = 1;
}
</code>```

I know that in order to test the fields of message, we can use:

```<code>foo.bar = 1
assert foo.HasField("bar")
</code>```

However "HasField" doesn't work for repeated field types.
How to test for existence of field for "repeated type" of fields?

```<code>message Foo {
  repeated int bar = 1;
}
</code>```

答:
Given a msg variable with a message, you can print only repeated fields like  that. from C# docs

for descr in msg.DESCRIPTOR.fields:
    if descr.label == descr.LABEL_REPEATED:
        print(f'{descr.name} is repeated')
        for i, v_i in enumerate(getattr(msg, descr.name)):
            print(f'{i}:{v_i}')
```

Body:
I have a google protobuf message:

message Foo {
  required int bar = 1;
}

I know that in order to test the fields of message, we can use:

foo.bar = 1
assert foo.HasField("bar")

However "HasField" doesn't work for repeated field types.
How to test for existence of field for "repeated type" of fields?

message Foo {
  repeated int bar = 1;
}


问:
Snowflake SQL stored procedure and save value from query with dynamic SQL
I am writing a SQL stored procedure in Snowflake (language SQL NOT Javascript).

I am trying to save a count from a SELECT statement into a variable and the table name for the select statement needs to come from a variable.

Here is what I have so far but this is failing.  I don't know where to put the USING or if I can even do this?  I feel like I just don't have it syntactically correct yet.

```<code>create or replace procedure myprocedure(DBNAME varchar(16777216))
  returns int
  language sql
  as
  $$
    DECLARE
        excludeCount int;
        fullyQualifiedProceduresTable  varchar(16777216);

    BEGIN
        fullyQualifiedProceduresTable := CONCAT(DBNAME, '.INFORMATION_SCHEMA.PROCEDURES');
        excludeCount := (SELECT count(*) as count from TABLE (?) WHERE PROCEDURE_OWNER = '<ROLE NAME>') USING fullyQualifiedProceduresTable ;

        IF (excludeCount > 0) THEN
            RETURN 1;
        ELSE
            RETURN 0;
        END IF;
    END;
$$;
</code>```

答:
try this</p>
```<code>call my_proc('bus_day');

create or replace procedure my_proc(table_name varchar)
returns table(a integer)
language sql
as
$$
  declare
    res RESULTSET;
    query varchar default 'SELECT count(*) FROM ' || :table_name ;
  begin
    res := (execute immediate :query);
    return table (res);
  end;
$$;
</code>```

Body:
I am writing a SQL stored procedure in Snowflake (language SQL NOT Javascript).

I am trying to save a count from a SELECT statement into a variable and the table name for the select statement needs to come from a variable.

Here is what I have so far but this is failing.  I don't know where to put the USING or if I can even do this?  I feel like I just don't have it syntactically correct yet.

create or replace procedure myprocedure(DBNAME varchar(16777216))
  returns int
  language sql
  as
  $$
    DECLARE
        excludeCount int;
        fullyQualifiedProceduresTable  varchar(16777216);

    BEGIN
        fullyQualifiedProceduresTable := CONCAT(DBNAME, '.INFORMATION_SCHEMA.PROCEDURES');
        excludeCount := (SELECT count(*) as count from TABLE (?) WHERE PROCEDURE_OWNER = '<ROLE NAME>') USING fullyQualifiedProceduresTable ;

        IF (excludeCount > 0) THEN
            RETURN 1;
        ELSE
            RETURN 0;
        END IF;
    END;
$$;

Body:
try this

call my_proc('bus_day');

create or replace procedure my_proc(table_name varchar)
returns table(a integer)
language sql
as
$$
  declare
    res RESULTSET;
    query varchar default 'SELECT count(*) FROM ' || :table_name ;
  begin
    res := (execute immediate :query);
    return table (res);
  end;
$$;


问:
build.gradle.kts - how to set compiler args correctly?
Got the following content:

```<code>val commonCompilerArgs = listOfNotNull(
    "-Dmicronaut.openapi.views.spec=rapidoc.enabled=true,swagger-ui.enabled=true,swagger-ui.theme=flattop",
)

tasks {
    compileKotlin {
        kotlinOptions {
            jvmTarget = "11"
            freeCompilerArgs = commonCompilerArgs
        }
    }
    compileTestKotlin {
        kotlinOptions {
            jvmTarget = "11"
        }
    }
}
</code>```

But got this error:

Invalid argument: -Dmicronaut.openapi.views.spec=rapidoc.enabled=true,swagger-ui.enabled=true,swagger-ui.theme=flattop

I guess it is simple, but I don't know how to set this compiler arguments correctly.

Any help appreciated!

答:
If you are using kapt in your Micronaut application gradle scripts then you can set it this way:

kapt {
    arguments {
        arg(
            "micronaut.openapi.views.spec",
            "rapidoc.enabled=true,swagger-ui.enabled=true,swagger-ui.theme=flattop"
        )
    }
}
```
<p>Open API definition files and Swagger UI are generated during annotation processing phase, where source code and resource files are generated. It means that it is before <strong>compileKotlin</strong> task.</p>
<p>Part of example build output:</p>
```...
> Task :my-app:kaptGenerateStubsKotlin
> Task :my-app:processResources
> Task :my-app:detekt
> Task :my-app:processTestResources NO-SOURCE
> Task :my-app:kaptKotlin
Note: Generating OpenAPI Documentation
Note: Writing OpenAPI YAML to destination: /home/me/prj/my-app/backend/build/tmp/kapt3/classes/main/META-INF/swagger/my-app-1.0.yml
Note: Writing OpenAPI View to destination: /home/me/prj/my-app/backend/build/tmp/kapt3/classes/main/META-INF/swagger/views/swagger-ui/index.html
Note: Creating bean classes for 9 type elements

> Task :my-app:compileKotlin
> Task :my-app:compileJava NO-SOURCE
> Task :my-app:classes
...
```
<p><strong>Update:</strong> You must also add <strong>micronaut.router.static-resources</strong> section for Swagger into <em>application.yaml</em> configuration file to map swagger static routes like this:</p>
<pre class="lang-yaml prettyprint-override"><code>micronaut:
  router:
    static-resources:
      swagger:
        paths: classpath:META-INF/swagger
        mapping: /swagger/**
      swagger-ui:
        paths: classpath:META-INF/swagger/views/swagger-ui
        mapping: /swagger-ui/**
</code>```

Then you can access OpenAPI definition file on http://localhost:8080/swagger/my-app-1.0.yml and Swagger UI should be available on http://localhost:8080/swagger-ui .

Body:
Got the following content:

val commonCompilerArgs = listOfNotNull(
    "-Dmicronaut.openapi.views.spec=rapidoc.enabled=true,swagger-ui.enabled=true,swagger-ui.theme=flattop",
)

tasks {
    compileKotlin {
        kotlinOptions {
            jvmTarget = "11"
            freeCompilerArgs = commonCompilerArgs
        }
    }
    compileTestKotlin {
        kotlinOptions {
            jvmTarget = "11"
        }
    }
}

But got this error:

Invalid argument: -Dmicronaut.openapi.views.spec=rapidoc.enabled=true,swagger-ui.enabled=true,swagger-ui.theme=flattop

I guess it is simple, but I don't know how to set this compiler arguments correctly.

Any help appreciated!

Body:
If you are using kapt in your Micronaut application gradle scripts then you can set it this way:

kapt {
    arguments {
        arg(
            "micronaut.openapi.views.spec",
            "rapidoc.enabled=true,swagger-ui.enabled=true,swagger-ui.theme=flattop"
        )
    }
}

Open API definition files and Swagger UI are generated during annotation processing phase, where source code and resource files are generated. It means that it is before compileKotlin task.

Part of example build output:

...
> Task :my-app:kaptGenerateStubsKotlin
> Task :my-app:processResources
> Task :my-app:detekt
> Task :my-app:processTestResources NO-SOURCE
> Task :my-app:kaptKotlin
Note: Generating OpenAPI Documentation
Note: Writing OpenAPI YAML to destination: /home/me/prj/my-app/backend/build/tmp/kapt3/classes/main/META-INF/swagger/my-app-1.0.yml
Note: Writing OpenAPI View to destination: /home/me/prj/my-app/backend/build/tmp/kapt3/classes/main/META-INF/swagger/views/swagger-ui/index.html
Note: Creating bean classes for 9 type elements

> Task :my-app:compileKotlin
> Task :my-app:compileJava NO-SOURCE
> Task :my-app:classes
...

Update: You must also add micronaut.router.static-resources section for Swagger into application.yaml configuration file to map swagger static routes like this:

micronaut:
  router:
    static-resources:
      swagger:
        paths: classpath:META-INF/swagger
        mapping: /swagger/**
      swagger-ui:
        paths: classpath:META-INF/swagger/views/swagger-ui
        mapping: /swagger-ui/**

Then you can access OpenAPI definition file on http://localhost:8080/swagger/my-app-1.0.yml and Swagger UI should be available on http://localhost:8080/swagger-ui .


问:
Why do we return by value while implementing cascading of cin cout?
This is a code to print/input the linked list by overloading cin/cout. Why is the return type ostream& in place of just ostream?</p>
```<code>ostream& operator<<(ostream& os, node* head)
{
    print(head);
}

// Overloading the istream operator '>>' to take continuous input into the linked
istream& operator>>(istream& is, node*& head)
{
    takeInput(head);
}

// Driver Code
int main()
{
    node* head = NULL;

    // input linked list
    cin >> head;

    // print linked list
    cout << head;
    return 0;
}
</code>```

答: It's because by default, c++ returns a copy of a variable. So ostream will be a copy, while ostream& will be a reference. References are commonly used in c++ for this reason and to save performance</p>

Body:
This is a code to print/input the linked list by overloading cin/cout. Why is the return type ostream& in place of just ostream?

ostream& operator<<(ostream& os, node* head)
{
    print(head);
}

// Overloading the istream operator '>>' to take continuous input into the linked
istream& operator>>(istream& is, node*& head)
{
    takeInput(head);
}

// Driver Code
int main()
{
    node* head = NULL;

    // input linked list
    cin >> head;

    // print linked list
    cout << head;
    return 0;
}


问:
I'm trying to learn the basic of ajax. I want to send a form data using post method to the server and get back a response text that's all
I know how to use the GET method but is hard to understand the POST method with a form.

I'm sure there is something wrong with the line request.send(); but I'm sorry I couldn't get it.

Also what If there is more than one field like I want to send name + email

My HTML code

```<code><!DOCTYPE html>
<html>
    <head>
        <title>AJAX Demo 2</title>
    </head>
    <body>
        <form action="demo2.php" method="post">
            Email: <input type="email" name="email" required >
        </form>

        <button onclick="loadContent()">Load</button>

        <div id="ServerContent">
           <p></p>
        </div>

        <script>
            function loadContent(email){
                //Create request object
                let request = new XMLHttpRequest();
                let email = document.getElementsByName("eamil").values;
               //Create event handler that specifies what should happen when server responds

                request.onload = function(){

                    //Check HTTP status code
                    if(request.status == 200){

                        //Get data from server
                        let responseData = request.responseText;

                        //Add data to page
                        document.getElementById("ServerContent").innerHTML = responseData;
                    }
                    else
                        alert("Error communicating with server");
                }

               //Set up request with HTTP method and URL
               request.open("POST", "demo2.php", true);
               xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
               //Send request
               request.send();
            }
        </script>
    </body>
</html>
</code>```

My PHP code

```<code>    <?php

//Get email string - need to filter input to reduce chances of SQL injection etc.
    $emailString = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_URL);

    if($emailString != ""){//email string exists
        echo 'Hello ' . $emailString;//Output message with contents of query string
    }
    else{//Query string parameter 'email' cannot be found
        echo 'Hello stranger';
    }
</code>```

答:
```<code>var url = "url to your php file";

var xhr = new XMLHttpRequest();
xhr.open("POST", url);

xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");

xhr.onreadystatechange = function () {
   if (xhr.readyState === 4) {
      console.log(xhr.responseText);
   }};

var data = `{
  "email": "youremailvariable",
  "name": "yournamevariable"
}`;

xhr.send(data);
</code>```

Try this way

Body:
I know how to use the GET method but is hard to understand the POST method with a form.

I'm sure there is something wrong with the line request.send(); but I'm sorry I couldn't get it.

Also what If there is more than one field like I want to send name + email

My HTML code

<!DOCTYPE html>

        <title>AJAX Demo 2</title>

        <form action="demo2.php" method="post">
            Email: <input type="email" name="email" required >
        </form>

        <button onclick="loadContent()">Load</button>

My PHP code

    <?php

//Get email string - need to filter input to reduce chances of SQL injection etc.
    $emailString = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_URL);

    if($emailString != ""){//email string exists
        echo 'Hello ' . $emailString;//Output message with contents of query string
    }
    else{//Query string parameter 'email' cannot be found
        echo 'Hello stranger';
    }

Body:
var url = "url to your php file";

var xhr = new XMLHttpRequest();
xhr.open("POST", url);

xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");

xhr.onreadystatechange = function () {
   if (xhr.readyState === 4) {
      console.log(xhr.responseText);
   }};

var data = `{
  "email": "youremailvariable",
  "name": "yournamevariable"
}`;

xhr.send(data);

Try this way


问:
How to set default values in angular if they aren't given from the other component
I am trying to set the variables to a default value if nothing is inputted from the component using the dialog. I am getting an error saying that it is still '' when the expected values (default values) should be applied. I currently have a template error dialog with a model that looks like:

```<code>export interface ErrorData {
   message: string;
   errorMessage: string;
   etc...
}
</code>```

The component looks like this:

```<code>constructor(
  public dialogRef-----etc,
  @Inject(MAT_DIALOG_DATA) public data: ErrorData,
) {
  const defaultData = {
     message: 'this is an error',
     errorMessage: '404httperror',
  }

  this.data = {
     ...defaultData,
     ...this.data
  }
}
</code>```

答:
The basic approach:

this.data.message = this.data.message || defaultData.message;
// repeat for each variable
```
<p>Cleverer approach, where there may be many values</p>
<pre class="lang-js prettyprint-override"><code>this.data = Object.entries(defaultData).reduce( (acc, [key, value]) => {
    return {
       ...acc,
       [key]: data[key] || value
    }
}, {...data})
</code>```

Note, I didn't run this, so syntax may be a bit off

Body:
I am trying to set the variables to a default value if nothing is inputted from the component using the dialog. I am getting an error saying that it is still '' when the expected values (default values) should be applied. I currently have a template error dialog with a model that looks like:

export interface ErrorData {
   message: string;
   errorMessage: string;
   etc...
}

The component looks like this:

constructor(
  public dialogRef-----etc,
  @Inject(MAT_DIALOG_DATA) public data: ErrorData,
) {
  const defaultData = {
     message: 'this is an error',
     errorMessage: '404httperror',
  }

  this.data = {
     ...defaultData,
     ...this.data
  }
}

Body:
The basic approach:

this.data.message = this.data.message || defaultData.message;
// repeat for each variable

Cleverer approach, where there may be many values

this.data = Object.entries(defaultData).reduce( (acc, [key, value]) => {
    return {
       ...acc,
       [key]: data[key] || value
    }
}, {...data})

Note, I didn't run this, so syntax may be a bit off


问:
Event Sourcing vs Event Driven Architecture difference
I was looking in to event base architecture and came to know about two architecture
Event Sourcing & Event Driven Architecture.

My understanding is following

Event driven :

used for distributed transactions like saga

event is pushed to message queue and listener listen
and does accordingly.

Event Sourcing:

Used to patters like CQRS.

Events responsible for saving data or syncing db

But what I did not get is how come replaying events in Event sourcing derives the whole
transaction but in event driven is not possible.

It will be helpful if someone describe it with real-life example.

答:
Event Driven Architecture is about components communicating via publishing events rather than making (e.g.) RPC calls against each other or manipulating shared state.  It's a communication strategy (albeit one which often relies on messages being persisted for fairly long periods).

Event Sourcing is when the components themselves treat the history of events which they have persisted as the ultimate source of truth for their state (or at least the state that they actually care about).  It's a persistence strategy and doesn't intrinsically say anything about communication.  Event Sourcing doesn't intrinsically have anything to do with CQRS (though event sourced systems do often find CQRS useful as a means of allowing queries which would have to replay a non-trivial subset of events to use a data model more optimized for that use case; likewise, there are some advantages to using an event sourcing persistence model for processing commands in a CQRS).

The persisted events being the ultimate source of truth implies that an event replay recovers the state (by definition, if an event replay could not recover the state, then the events were not the ultimate source of truth).

Event Sourcing is keeping a log for your own use so you don't forget.  Event Driven Architecture is about communicating what happened to others.  Typically, components in EDA can't recover the entirety of their state from the events they've published because not everything that changed their state is worth publishing.  A component which only takes as input events published by other components is able to recover its state based on replaying those events (though in many cases replaying them in the same order as they were published is quite difficult...), though I'd argue that that is command sourcing, not event sourcing, because an event published by one component is a command when consumed by another component (the command being "try to incorporate this event into your view of the world").

The log of events in an Event Sourced component is a very good (I'd even suggest that it's the optimal) source for deriving events to publish in an Event Driven Architecture, so Event Sourced components can be a part of an Event Driven Architecture.

For example, consider a shopping cart service backed by a relational DB.  The cart is represented in the DB by a row in a carts table and a cartitems table represents tracks has rows that say "2 USB chargers in cart ABC with price $4.75 apiece".  To add items to the cart we insert (or update if it's just a quantity change) rows to the cartitems table.  When the cart is checked out, we publish a JSON representation of the cart and its contents so the shipping service has what's in the cart and we set carts.checked_out to TRUE.

That's a perfectly OK Event Driven Architecture.  The cart service communicates that there's a checked out cart to the shipping service.  It's not event-sourced: we can't reconstruct the DB from the events.

The shopping cart service could be event sourced.  It stores events in an event store (which could be a datastore designed for the needs of event sourcing or could be relational DB or non-relational DB being used in a particular way (e.g. an events table)).  The following sequence of events for cart ABC might be written to the event store:

AddItem { "USB charger", $4.95 }

AddItem { "USB charger", $4.95 }

AddItem { "Camel Book", $34.95 }

RemoveItem { "Camel Book" }

DiscountApplied { Requirement { 2, "USB charger" }, -$0.40 }

AddItem { "The C Programming Language", $19.95 }

CheckedOut { Items { Item { "USB Charger", 2, $4.75 }, Item { "The C Programming Language", 1, $19.95 } } }

That last event (along with the fact that it's for cart ABC, which is metadata associated with the event) can be used to derive an event for publishing.  One key thing to note is that there's nothing else being written to the DB but these events.

As far as Event Driven Architecture is concerned, these two cart services are basically the same: they publish the same checkout events.  That one is event sourced is really just an implementation detail of that service.


问:
Javascript Changing button inner text without chaning the icon
I created the following button, and want to change the inner text "test" to other word.

```<code>            <button type="button" id="test"><i class="fa-2x fa-regular fa-floppy-disk"></i>test</button>
</code>```

I tried below method it can change the word but also deleted the icon.

```<code>$('button#bkmarktest').on('click', function(e){
e.preventDefault();
$(this).text("other");
});
</code>```

Is there any way that can only change the word, but keeping the icon, thanks!

答:
like @Kunal Tanwar said, wrapping the text in a span solves it and using Jquery this is my approach.. assuming the button has an id of test

using the .find() method to find the span child

```<code><button type="button" id="test">
  <i class="fa-2x fa-regular fa-floppy-disk"></i>
  <span>test<span>
</button>

$('#test').on('click', function(e){
  e.preventDefault();
  $(this).find('span').text("other");
});
</code>```

and another option would be to use the decendant selector since the span is a direct child of the button

```<code>$('#test').on('click', function(e){
  $('#test > span').text('other');
});
</code>```

Body:
I created the following button, and want to change the inner text "test" to other word.

            <button type="button" id="test">test</button>

I tried below method it can change the word but also deleted the icon.

$('button#bkmarktest').on('click', function(e){
e.preventDefault();
$(this).text("other");
});

Is there any way that can only change the word, but keeping the icon, thanks!

Body:
like @Kunal Tanwar said, wrapping the text in a span solves it and using Jquery this is my approach.. assuming the button has an id of test

using the .find() method to find the span child

<button type="button" id="test">
  <i class="fa-2x fa-regular fa-floppy-disk"></i>
  <span>test<span>
</button>

$('#test').on('click', function(e){
  e.preventDefault();
  $(this).find('span').text("other");
});

and another option would be to use the decendant selector since the span is a direct child of the button

$('#test').on('click', function(e){
  $('#test > span').text('other');
});


问:
How to launch one activity by clicking on the button
I want to call next activity from the first activity.
When user click on the button then it will call the next activity .
please suggest me how can i do that.</p>

答:
```<code>startActivity(new Intent(this, YourActivity.class));
</code>```

You would need to do this either in the OnClickListener for your button, or in a method you've declared to be called when you click on the button in your xml

Body:
startActivity(new Intent(this, YourActivity.class));

You would need to do this either in the OnClickListener for your button, or in a method you've declared to be called when you click on the button in your xml


答:
This is what I got to work using slightly different syntax for using variables.
Syntax taken from here

create or replace procedure myprocedure(DBNAME varchar(16777216))
  returns int
  language sql
  as
  $$
    DECLARE
        excludeCount int;
        fullyQualifiedProceduresTable  varchar(16777216);

    BEGIN
        SELECT CONCAT(:DBNAME, '.INFORMATION_SCHEMA.PROCEDURES') into :fullyQualifiedProceduresTable;
        SELECT count(*) into :excludeCount from IDENTIFIER(:fullyQualifiedProceduresTable) WHERE PROCEDURE_OWNER = '<role>';

        IF (excludeCount > 0) THEN
            RETURN 1;
        ELSE
            RETURN 0;
        END IF;
    END;
$$;
```

Title: Snowflake SQL stored procedure and save value from query with dynamic SQL


问:
Positioning an image on top of text
How can I position an image on top text. Like in the image given

答:
There is more than one technique.

Here's one, borrowed from w3schools:

<!DOCTYPE html>

Image Text

Add some text to an image in the top right corner:

Top Right

```

Title: Positioning an image on top of text

Body:
There is more than one technique.

Here's one, borrowed from w3schools:

<!DOCTYPE html>
<html>

<head>
  <style>
    .container {
      position: relative;
    }

    .topright {
      position: absolute;
      top: 8px;
      right: 16px;
      font-size: 18px;
    }

    img {
      width: 100%;
      height: auto;
      opacity: 0.3;
    }
  </style>
</head>

<body>

  <h2>Image Text</h2>
  <p>Add some text to an image in the top right corner:</p>

  <div class="container">
    <img src="img_5terre_wide.jpg" alt="Cinque Terre" width="1000" height="300">
    <div class="topright">Top Right</div>
  </div>

</body>

</html>