问:
SQL Performance (Replace)
I have a table that has about 400,000+ rows. I am writing some pattern matching code but need to clean up a column before I do so. This boils down to doing a replace-like operation.

I tried listing them all out one at a time...

```<code> Update T_ADDRESS set ADDR_LINEONE = REPLACE(ADDR_LINEONE,' southeast ',' se ')
 Update T_ADDRESS set ADDR_LINEONE = REPLACE(ADDR_LINEONE,' southwest ',' sw ')
</code>```

Since I have over 500 of these...it took too long.

Now I am trying to nest them...

```<code> Update T_ADDRESS set ADDR_LINEONE = REPLACE(REPLACE(ADDR_LINEONE,' southwest ',' sw '),' southeast ',' se ')
</code>```

But this is still painfully slow. I need to make this code work on tables of all sizes (1 record to 5 million records).

Anyone have any advice? I am using SQL Server by the way.

答:
Old question, but still useful.
Your query updates all the columns of the table, with a large penalty if this column is indexed.
You can improve the speed by filtering the fields that do not need to be updated as follows:

```<code>Update T set ADDR_LINEONE = REPLACE(ADDR_LINEONE,' southeast ',' se ') FROM T_ADDRESS T WHERE ADDR_LINEONE LIKE '% southeast %'
Update T set ADDR_LINEONE = REPLACE(ADDR_LINEONE,' southwest ',' sw ') FROM T_ADDRESS T WHERE ADDR_LINEONE LIKE '% southwest %'
</code>```

Unless all your addresses contain southeast or southwest, this will be an order of magnitude faster!

ContentLicense: CC BY-SA 2.5

Title: SQL Performance (Replace)

Body:
I have a table that has about 400,000+ rows. I am writing some pattern matching code but need to clean up a column before I do so. This boils down to doing a replace-like operation.

I tried listing them all out one at a time...

 Update T_ADDRESS set ADDR_LINEONE = REPLACE(ADDR_LINEONE,' southeast ',' se ')
 Update T_ADDRESS set ADDR_LINEONE = REPLACE(ADDR_LINEONE,' southwest ',' sw ')

Since I have over 500 of these...it took too long.

Now I am trying to nest them...

 Update T_ADDRESS set ADDR_LINEONE = REPLACE(REPLACE(ADDR_LINEONE,' southwest ',' sw '),' southeast ',' se ')

But this is still painfully slow. I need to make this code work on tables of all sizes (1 record to 5 million records).

Anyone have any advice? I am using SQL Server by the way.

Body:
Old question, but still useful.
Your query updates all the columns of the table, with a large penalty if this column is indexed.
You can improve the speed by filtering the fields that do not need to be updated as follows:

Update T set ADDR_LINEONE = REPLACE(ADDR_LINEONE,' southeast ',' se ') FROM T_ADDRESS T WHERE ADDR_LINEONE LIKE '% southeast %'
Update T set ADDR_LINEONE = REPLACE(ADDR_LINEONE,' southwest ',' sw ') FROM T_ADDRESS T WHERE ADDR_LINEONE LIKE '% southwest %'

Unless all your addresses contain southeast or southwest, this will be an order of magnitude faster!


来源: stackexchange

问:
Skipping errors in a loop? (PHP)
I have a loop where the code loops and in every loop it connects to different server and then makes MySQL query. However sometimes one of the loops/queries cannot reach to the end and all the code breaks. Is there a way where if the loop gives error then skip the processes / move to next loop?</p>

答:
As stated in the comments above, the correct way to do this is within a try...catch block.

To learn more about these, you can read about them here.

Thanks @Paul.

ContentLicense: CC BY-SA 3.0

Title: Skipping errors in a loop? (PHP)


问:
How to upload data using the new swift async/await methods?
The new features in Swift with async/await allow a better control about the process and a simplification in coding. But I cannot find out how this method can be applied for requests which go above a simple data reading. E.g. I need to pass a parameter in order to get a specific answer from a SQL database in the backend (accessed via php).

At first my code about the "standard" way to start with. This function reads all customer records and stores them into an account-array:

```<code>@available(iOS 15.0, *)
static func getCustomerListFromBackend() async throws -> [Account] {
    let url = URL(string: "https://xxx.de/xxx/getCustomerList.php")!
    let (data, _) = try await URLSession.shared.data(from: url)
    var accounts: [Account] = []
    accounts = try JSONDecoder().decode([Account].self, from: data)
    return accounts
}
</code>```

In order to make my question clear, now a piece of code in which the central statement does not work and exist. In this function I want to check whether a customer exists in the database and I need to pass the emailAddress as a parameter.

```<code>@available(iOS 15.0, *)
static func checkCustomerExistsInBackend(emailAddress: String) async throws -> String {
    let url = URL(string: "https://xxx.de/xxx/checkCustomerexists.php")!
    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    var dataString = "EmailAddress=\(emailAddress)"
    let dataD = dataString.data(using: .utf8)

    // Statement which does not work but for which I need an alternative
    let (data, _) = try await URLSession.shared.upload(request: request, data: dataD)

    let answer = try JSONDecoder().decode(BackendMessage.self, from: data)
    return answer.Message
}
</code>```

Unfortunately there is no statement for URLSession.shared.upload(request: request, data: dataD) Until now (before async/await), I used URLSession.shared.uploadTask(with: request, from: dataD) and then used .resume() to process it. This method however gave me too many problems in controlling the right sequence of tasks in the app. Async/await could simplify this very much as in my first example.

So, is there a way to realize this? Any advice would be appreciated.

答:
My question was answered by Florian Friedrich's comment and workingdog's answer as well. To the later one I had to make a little adoption which I want to reflect here in this wrap up in case it can be helpful for someone with a similar problem. I show here 2 solutions to my problem with a few remarks.

Applying Florian's answer.
This was straightforward and worked right away:

```<code> static func checkCustomerExistsInBackend(emailAddress: String) async throws -> String {
 let url = URL(string: "https://xxx.de/xxx/checkCustomerexists.php")!
 var request = URLRequest(url: url)
 request.httpMethod = "POST"
 let dataString = "EmailAddress=\(emailAddress)"
 let dataD = dataString.data(using: .utf8)
 let (data, _) = try await URLSession.shared.upload(for: request, from: dataD!, delegate: nil)
 let answer = try JSONDecoder().decode(BackendMessage.self, from: data)
 return answer.Message
 }
</code>```

The proposal from workingdog:
Here I noticed that although the url appeared to be correctly set (ending with checkCustomerexists.php?EmailAddress=test@gmx.de), the parameter did not arrive in my php object. After some tests I found out that it works when I use GET instead of POST. So in my php file I changed the line $EmailAddress = $_POST[EmailAddress]; to $EmailAddress = $_GET['EmailAddress'];. (I am sure there is a good reason for this and I am just not experienced enough to recognize this.) Accordingly the code I use for workingdog's proposal is slightly adjusted:

```<code> func checkCustomerExistsInBackend3(emailAddress: String) async throws -> String {
 if let url = URL(string: "https://xxx.de/xxx/checkCustomerexists.php"),
    var components = URLComponents(url: url, resolvingAgainstBaseURL: false) {
     components.queryItems = [URLQueryItem(name: "EmailAddress", value: emailAddress)]
     var request = URLRequest(url: components.url!)
     request.httpMethod = "GET"
     let (data, _) = try await URLSession.shared.data(for: request)
     let answer = try JSONDecoder().decode(BackendMessage.self, from: data)
     return answer.Message
 }
 throw URLError(.badURL)
 }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
The new features in Swift with async/await allow a better control about the process and a simplification in coding. But I cannot find out how this method can be applied for requests which go above a simple data reading. E.g. I need to pass a parameter in order to get a specific answer from a SQL database in the backend (accessed via php).

At first my code about the "standard" way to start with. This function reads all customer records and stores them into an account-array:

@available(iOS 15.0, *)
static func getCustomerListFromBackend() async throws -> [Account] {
    let url = URL(string: "https://xxx.de/xxx/getCustomerList.php")!
    let (data, _) = try await URLSession.shared.data(from: url)
    var accounts: [Account] = []
    accounts = try JSONDecoder().decode([Account].self, from: data)
    return accounts
}

In order to make my question clear, now a piece of code in which the central statement does not work and exist. In this function I want to check whether a customer exists in the database and I need to pass the emailAddress as a parameter.

@available(iOS 15.0, *)
static func checkCustomerExistsInBackend(emailAddress: String) async throws -> String {
    let url = URL(string: "https://xxx.de/xxx/checkCustomerexists.php")!
    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    var dataString = "EmailAddress=\(emailAddress)"
    let dataD = dataString.data(using: .utf8)

    // Statement which does not work but for which I need an alternative
    let (data, _) = try await URLSession.shared.upload(request: request, data: dataD)

    let answer = try JSONDecoder().decode(BackendMessage.self, from: data)
    return answer.Message
}

Unfortunately there is no statement for URLSession.shared.upload(request: request, data: dataD) Until now (before async/await), I used URLSession.shared.uploadTask(with: request, from: dataD) and then used .resume() to process it. This method however gave me too many problems in controlling the right sequence of tasks in the app. Async/await could simplify this very much as in my first example.

So, is there a way to realize this? Any advice would be appreciated.

Body:
My question was answered by Florian Friedrich's comment and workingdog's answer as well. To the later one I had to make a little adoption which I want to reflect here in this wrap up in case it can be helpful for someone with a similar problem. I show here 2 solutions to my problem with a few remarks.

Applying Florian's answer.
This was straightforward and worked right away:

 static func checkCustomerExistsInBackend(emailAddress: String) async throws -> String {
 let url = URL(string: "https://xxx.de/xxx/checkCustomerexists.php")!
 var request = URLRequest(url: url)
 request.httpMethod = "POST"
 let dataString = "EmailAddress=\(emailAddress)"
 let dataD = dataString.data(using: .utf8)
 let (data, _) = try await URLSession.shared.upload(for: request, from: dataD!, delegate: nil)
 let answer = try JSONDecoder().decode(BackendMessage.self, from: data)
 return answer.Message
 }

The proposal from workingdog:
Here I noticed that although the url appeared to be correctly set (ending with checkCustomerexists.php?EmailAddress=test@gmx.de), the parameter did not arrive in my php object. After some tests I found out that it works when I use GET instead of POST. So in my php file I changed the line $EmailAddress = $_POST[EmailAddress]; to $EmailAddress = $_GET['EmailAddress'];. (I am sure there is a good reason for this and I am just not experienced enough to recognize this.) Accordingly the code I use for workingdog's proposal is slightly adjusted:

 func checkCustomerExistsInBackend3(emailAddress: String) async throws -> String {
 if let url = URL(string: "https://xxx.de/xxx/checkCustomerexists.php"),
    var components = URLComponents(url: url, resolvingAgainstBaseURL: false) {
     components.queryItems = [URLQueryItem(name: "EmailAddress", value: emailAddress)]
     var request = URLRequest(url: components.url!)
     request.httpMethod = "GET"
     let (data, _) = try await URLSession.shared.data(for: request)
     let answer = try JSONDecoder().decode(BackendMessage.self, from: data)
     return answer.Message
 }
 throw URLError(.badURL)
 }


问:
How to find location in database of CPU intensive query?
I have a server called "Reporting" and looking at SQL Server performance reports, specifically "Top Queries by Total CPU Time". I have found the top CPU Time consuming queries.

The number 1 query shows me the "Query Text", "Database Name", "Object ID" and "Total CPU Time".

I would like to go and optimize the code of that query but I only know the database where the query is from but not the exact location folder or name of the query.

Is there any way of how one can go about finding the exact name and location of the query?

```<code> For Example:
Top CPU Expensive Query is in Database "Training", ObjectID "1727285326", Query text +- 500 lines of SQL code.
Where do I go look in the "Training" Database for the query since I only see the Query Text and Object ID?
</code>```

Any help or right direction would be much appreciated.

答:
As you have the object id you can just use the following to find the object</p>
```<code>USE Training;

SELECT OBJECT_SCHEMA_NAME(1727285326) AS schema_name,
       OBJECT_NAME(1727285326)        AS object_name;
</code>```

Body:
I have a server called "Reporting" and looking at SQL Server performance reports, specifically "Top Queries by Total CPU Time". I have found the top CPU Time consuming queries.

The number 1 query shows me the "Query Text", "Database Name", "Object ID" and "Total CPU Time".

I would like to go and optimize the code of that query but I only know the database where the query is from but not the exact location folder or name of the query.

Is there any way of how one can go about finding the exact name and location of the query?

 For Example:
Top CPU Expensive Query is in Database "Training", ObjectID "1727285326", Query text +- 500 lines of SQL code.
Where do I go look in the "Training" Database for the query since I only see the Query Text and Object ID?

Any help or right direction would be much appreciated.

Body:
As you have the object id you can just use the following to find the object

USE Training;

SELECT OBJECT_SCHEMA_NAME(1727285326) AS schema_name,
       OBJECT_NAME(1727285326)        AS object_name;


问:
Can js file be compiled in a different folder from the source folder?
I'm building an Obsidian plugin, and it uses esbuild to bundle ts file to js file. The ts file is located at D:\foo1\foo2\..., and I want the js file to be at D:\bar1\bar2\.... The reason for this is because I want the source folder is in a different folder than the plugin folder, so that when syncing it to mobile I don't have to exclude the source files.

I was suggested to edit the esbuild.config.mjs file, and I find in the documentation that beside the outfile config there are also outdir, outbase. However, these are the results when I'm using them:

outdir

outdir: 'D:\Quả Cầu\B Nội dung\Knowledge graphs\Cây vấn đề\.obsidian\plugins\dotmaker'
```
<blockquote>
<p>error: Failed to create output directory: mkdir D:\GitHub\Obsidian\dotmaker\D:Quả CầuB Nội dungKnowledge graphsCây vấn đề.obsidianpluginsdotmaker: The directory name is invalid.</p>
</blockquote>
<h3>outbase</h3>
<pre class="lang-js prettyprint-override"><code>outbase: 'D:\Quả Cầu\B Nội dung\Knowledge graphs\Cây vấn đề\.obsidian\plugins\dotmaker',
</code>```

It prints the js content in the terminal, but the real file isn't changed.

It seems that I can only create the js file inside the source folder. Is that possible?

答:
You didn't correctly format the content of the outdir setting. When using backslashes \ as path separator on windows, you have to escape them. Ie use

```<code>outdir: 'D:\\Quả Cầu\\B Nội dung\\Knowledge graphs\\Cây vấn đề\\.obsidian\\plugins\\dotmaker'
</code>```

Body:
I'm building an Obsidian plugin, and it uses esbuild to bundle ts file to js file. The ts file is located at D:\foo1\foo2\..., and I want the js file to be at D:\bar1\bar2\.... The reason for this is because I want the source folder is in a different folder than the plugin folder, so that when syncing it to mobile I don't have to exclude the source files.

I was suggested to edit the esbuild.config.mjs file, and I find in the documentation that beside the outfile config there are also outdir, outbase. However, these are the results when I'm using them:

outdir

outdir: 'D:\Quả Cầu\B Nội dung\Knowledge graphs\Cây vấn đề\.obsidian\plugins\dotmaker'

error: Failed to create output directory: mkdir D:\GitHub\Obsidian\dotmaker\D:Quả CầuB Nội dungKnowledge graphsCây vấn đề.obsidianpluginsdotmaker: The directory name is invalid.

outbase

outbase: 'D:\Quả Cầu\B Nội dung\Knowledge graphs\Cây vấn đề\.obsidian\plugins\dotmaker',

It prints the js content in the terminal, but the real file isn't changed.

It seems that I can only create the js file inside the source folder. Is that possible?

Body:
You didn't correctly format the content of the outdir setting. When using backslashes \ as path separator on windows, you have to escape them. Ie use

outdir: 'D:\\Quả Cầu\\B Nội dung\\Knowledge graphs\\Cây vấn đề\\.obsidian\\plugins\\dotmaker'


问:
How to display in Flask certain input fields depending on the value of variables
Have a good day!

I would be very grateful and grateful for help on an issue that I have been thinking about for a long time.

How to display certain input fields depending on the value of variables

Flask Bootstrap's form
input group
multiple inputs
custom forms

Input groups include support for custom selects and custom file inputs. Browser default versions of these are not supported.

I want to display a form for entries of various information.
Form, for example, from 20 different elements for entering, 15-25 different fields for entering any information.

I have 25 different variables, 25 variables can take on a value, a value - either zero (0) or one (1).

Each variable corresponds to a certain field in the form for entering any information.

And I need that if one of the above variable, for example, is equal to zero (0), then I do not display the corresponding field in the form for entering any information.

The number of fields may vary.
form text

```<code><label for="inputPassword5" class="form-label">Password</label>
<input type="password" id="inputPassword5" class="form-control" aria-describedby="passwordHelpBlock">
<div id="passwordHelpBlock" class="form-text">
  Your password must be 8-20 characters long, contain letters and numbers, and must not contain spaces, special characters, or emoji.
</div>
</code>```

答:
Here is a million ways how to do it. You need to clarify your question and show your code.

For example:

main.py

```<code>from flask import Flask, render_template, request

app = Flask(__name__)

@app.route("/1")
def hide_by_class():

    abc = {
        "a": str(request.args.get('a')),
        "b": str(request.args.get('b')),
        "c": str(request.args.get('c'))
    }

    return render_template('hide_by_class.html',  abc=abc)

@app.route("/2")
def hide_by_render():

    abc = {
        "a": str(request.args.get('a')),
        "b": str(request.args.get('b')),
        "c": str(request.args.get('c'))
    }

    return render_template('hide_by_render.html', abc=abc)

if __name__ == "__main__":
    app.run()
</code>```

templates/hide_by_render.html

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

  {% for k, v in abc.items() %}
    {% if v == "1" %}
        <label for="{{ k }}">{{ k }} is</label>
        <input type="text" id="{{ k }}" name="{{ k }}"><br>
    {% endif %}
  {% endfor %}

</body>
</html>
</code>```

templates/hide_by_class.html

```<code><!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <title>Title</title>
   <style>
    .hidden {display: none;}
  </style>
</head>
<body>

  {% for k, v in abc.items() %}
    <label class="{{ 'hidden' if v !="1" else 'displayed' }}" for="{{ k }}">{{ k }} is</label>
    <input class="{{ 'hidden' if v !="1" else 'displayed' }}" type="text" id="{{ k }}" name="{{ k }}"><br>
  {% endfor %}

</body>
</html>
</code>```

If you access URL http://127.0.0.1:5000/1?a=1&b=0&c=1

All a, b and c inputs will be present inside html code, but only a and c will be displayed by CSS

   <meta charset="UTF-8">
   <title>Title</title>

    a is
    <input class="displayed" type="text" id="a" name="a">

    b is
    <input class="hidden" type="text" id="b" name="b">

    c is
    <input class="displayed" type="text" id="c" name="c">

```
</div>
</div>
</p>
<p>If you access URL <code>http://127.0.0.1:5000/2?a=1&b=0&c=1</code></p>
<p>The <code>b</code> will not be present inside page at all</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-html lang-html prettyprint-override"><code><html lang="en"><head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

        <label for="a">a is</label>
        <input type="text" id="a" name="a"><br>

        <label for="c">c is</label>
        <input type="text" id="c" name="c"><br>

</body></html></code>```

Body:
Have a good day!

I would be very grateful and grateful for help on an issue that I have been thinking about for a long time.

How to display certain input fields depending on the value of variables

Flask Bootstrap's form
input group
multiple inputs
custom forms

Input groups include support for custom selects and custom file inputs. Browser default versions of these are not supported.

I want to display a form for entries of various information.
Form, for example, from 20 different elements for entering, 15-25 different fields for entering any information.

I have 25 different variables, 25 variables can take on a value, a value - either zero (0) or one (1).

Each variable corresponds to a certain field in the form for entering any information.

And I need that if one of the above variable, for example, is equal to zero (0), then I do not display the corresponding field in the form for entering any information.

The number of fields may vary.
form text

Password
<input type="password" id="inputPassword5" class="form-control" aria-describedby="passwordHelpBlock">

  Your password must be 8-20 characters long, contain letters and numbers, and must not contain spaces, special characters, or emoji.

Body:
Here is a million ways how to do it. You need to clarify your question and show your code.

For example:

main.py

from flask import Flask, render_template, request

app = Flask(__name__)

@app.route("/1")
def hide_by_class():

    abc = {
        "a": str(request.args.get('a')),
        "b": str(request.args.get('b')),
        "c": str(request.args.get('c'))
    }

    return render_template('hide_by_class.html',  abc=abc)

@app.route("/2")
def hide_by_render():

    abc = {
        "a": str(request.args.get('a')),
        "b": str(request.args.get('b')),
        "c": str(request.args.get('c'))
    }

    return render_template('hide_by_render.html', abc=abc)

if __name__ == "__main__":
    app.run()

templates/hide_by_render.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

  {% for k, v in abc.items() %}
    {% if v == "1" %}
        <label for="{{ k }}">{{ k }} is</label>
        <input type="text" id="{{ k }}" name="{{ k }}"><br>
    {% endif %}
  {% endfor %}

</body>
</html>

templates/hide_by_class.html

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <title>Title</title>
   <style>
    .hidden {display: none;}
  </style>
</head>
<body>

  {% for k, v in abc.items() %}
    <label class="{{ 'hidden' if v !="1" else 'displayed' }}" for="{{ k }}">{{ k }} is</label>
    <input class="{{ 'hidden' if v !="1" else 'displayed' }}" type="text" id="{{ k }}" name="{{ k }}"><br>
  {% endfor %}

</body>
</html>

If you access URL http://127.0.0.1:5000/1?a=1&b=0&c=1

All a, b and c inputs will be present inside html code, but only a and c will be displayed by CSS

<html lang="en"><head>
   <meta charset="UTF-8">
   <title>Title</title>
   <style>
    .hidden {display: none;}
  </style>
</head>
<body>

    <label class="displayed" for="a">a is</label>
    <input class="displayed" type="text" id="a" name="a"><br>

    <label class="hidden" for="b">b is</label>
    <input class="hidden" type="text" id="b" name="b"><br>

    <label class="displayed" for="c">c is</label>
    <input class="displayed" type="text" id="c" name="c"><br>

</body></html>

If you access URL http://127.0.0.1:5000/2?a=1&b=0&c=1

The b will not be present inside page at all

<html lang="en"><head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

        <label for="a">a is</label>
        <input type="text" id="a" name="a"><br>

        <label for="c">c is</label>
        <input type="text" id="c" name="c"><br>

</body></html>


问:
how character pointer could be used to point a string in c++?
First of all I am beginner in C++. I was trying to learn about type casting in C++ with strings and character pointer. Is it possible to point a string with a character pointer?

```<code>int main() {
    string data="LetsTry";
    cout<<(&data)<<"\n";
    cout<<data<<"\n"<<"size "<<sizeof(data)<<"\n";
    //char *ptr = static_cast<char*>(data);
    //char *ptr=(char*)data;
    char *ptr = reinterpret_cast<char*>(&data);
    cout<<(ptr)<<"\n";
    cout<<*ptr;
}
</code>```

The above code yields outcome as below:

```<code>0x7ffea4a06150
LetsTry
size 32
`a���
`
</code>```

I understand as ptr should output the address 0x7ffea4a06150

答:
std::string and const char* are different types,  reinterpret_cast<char*>(&data) means reinterpret the bits located at &data as const char*, which is not we want in this case.

so assuming we have type A and type B:

A a;
B b;
```
<p>the following are conversion:</p>
<pre class="lang-cpp prettyprint-override"><code>a = (A)b;                 //c sytle
// and
a = A(b);
// and
a = static_cast<A>(b);    //c++ style
</code>```

the following are bit reinterpretation:

```<code>a = *(A*)&b;                   //c style
// and
a = *reinterpret_cast<A*>(&b); //c++ style
</code>```

finally, this should works:

int main() {
    string data = "LetsTry";
    const char *ptr = data.c_str();
    cout<< ptr << "\n";
}
```

bit reinterpretation is sometimes used, like when doing bit manipulation of a floating point number, but there are some rules to follow like this one What is the strict aliasing rule?

also note that cout << ptr << "\n"; is a specially case because feeds a pointer to std::cout usually output the address that pointer points to, but std::cout treats char* specially so that it output the content of that char array instead

Body:
First of all I am beginner in C++. I was trying to learn about type casting in C++ with strings and character pointer. Is it possible to point a string with a character pointer?

int main() {
    string data="LetsTry";
    cout<<(&data)<<"\n";
    cout<<data<<"\n"<<"size "<<sizeof(data)<<"\n";
    //char *ptr = static_cast<char*>(data);
    //char *ptr=(char*)data;
    char *ptr = reinterpret_cast<char*>(&data);
    cout<<(ptr)<<"\n";
    cout<<*ptr;
}

The above code yields outcome as below:

0x7ffea4a06150
LetsTry
size 32
`a���
`

I understand as ptr should output the address 0x7ffea4a06150

Body:
std::string and const char* are different types,  reinterpret_cast<char*>(&data) means reinterpret the bits located at &data as const char*, which is not we want in this case.

so assuming we have type A and type B:

A a;
B b;

the following are conversion:

a = (A)b;                 //c sytle
// and
a = A(b);
// and
a = static_cast<A>(b);    //c++ style

the following are bit reinterpretation:

a = *(A*)&b;                   //c style
// and
a = *reinterpret_cast<A*>(&b); //c++ style

finally, this should works:

int main() {
    string data = "LetsTry";
    const char *ptr = data.c_str();
    cout<< ptr << "\n";
}

bit reinterpretation is sometimes used, like when doing bit manipulation of a floating point number, but there are some rules to follow like this one What is the strict aliasing rule?

also note that cout << ptr << "\n"; is a specially case because feeds a pointer to std::cout usually output the address that pointer points to, but std::cout treats char* specially so that it output the content of that char array instead


问:
Spring Cloud Stream - Testing consuming from and producing into a shared topic
I have been trying to implement the following solution:

My application is expecting to consume message A from all-messages, do some business logic and then producing
message B back into all-messages.

The reason why I am using StreamBridge instead of a Function is because I want the producing side to work with an arbitrary
number of produced messages, but for the sake of this example I am trying to simplify the scenario to just one.

Additionally, there is a custom router function in order to avoid an infinite loop, that dispatch the incoming messages
into the appropriate consumer, either incoming or discarded, would be great to have a way to effectively discard messages.

That being said I cannot quite get the implementation right using Spring Cloud Stream.

I'd like your help to understand what am I doing wrong and how to fix the current configure/setup in order to make the solution work as expected, specifically:

Is this solution supported by Spring cloud stream?

Is my application configuration correctly implementing the solution diagram above?

Which bindings exactly should I use inside the app when sending/receiving messages?

The major headache comes from the bindings, so I tried to write a test with different combinations of incoming and outgoing bindings to see what is what, something along these lines:

class ScsProblemTests {

    /* ... */

    @ParameterizedTest
    @MethodSource("bindings")
    void consumeFromAndProduceIntoSharedTopic(String incomingBinding, String outgoingBinding) {
        givenNoOutgoingMessages();
        whenAnIncomingMessageArrives(incomingBinding);
        thenEventuallyAnOutgoingMessageIsProduced(outgoingBinding);
    }

    public static Stream<Arguments> bindings() {
        return Stream.of(
            Arguments.of(null, null),
            Arguments.of(null, "outgoing-out-0"),
            Arguments.of(null, "all-messages"),
            Arguments.of("incoming-in-0", null),
            Arguments.of("incoming-in-0", "outgoing-out-0"),
            Arguments.of("incoming-in-0", "all-messages"),
            Arguments.of("all-messages", null),
            Arguments.of("all-messages", "outgoing-out-0"),
            Arguments.of("all-messages", "all-messages")
        );
    }

    /* ... */
}
```

I am running this set of tests with a overrides spring profile, where I setup the destination overrides as per the diagram, I am also testing the same set with a different spring profile with no overrides, again just for having a control group to compare with. Only 2 tests from the no-overrides profile pass, the rest fails.

The no-overrides profile does not match the design obviously, but I was curious to see how the overrides where affecting the results, specifically the no-overrides tests that passes are the one where:

incomingBinding=null, outgoingBinding=null

incomingBinding=null, outgoingBinding=outgoing-out-0

And for my understanding of Spring Cloud Stream, even in this no-overrides case, I'd expect also the following to pass (the are not):

incomingBinding=incoming-in-0, outgoingBinding=null

incomingBinding=incoming-in-0, outgoingBinding=outgoing-out-0

At this point I am starting to think I misunderstood some concepts behind Spring Cloud Stream, but I really hope
you can provide some useful advise.

I have shared my code into this repository for convenience.

Thanks in advance.

答:
Ok here are the problems in my implementation and how to fix them:

I had a typo in the routing configuration, so wasn't enabled, this is how to enable the function router in spring cloud:

spring:
  cloud:
    stream:
      function:
        routing:
          enabled: true
```
<ol start="2">
<li>Because I have a function router involved, I don't need anymore to configure my <code>incoming-in-0</code> binding instead I need to configure a destination for the function router:</li>
</ol>
<pre class="lang-yaml prettyprint-override"><code>spring:
  cloud:
    stream:
      bindings:
        functionRouter-in-0:
          destination: all-messages
        outgoing-out-0:
          destination: all-messages
      source: outgoing
      # ...
</code>```

I misunderstood bindings/destinations and how to use the testing helpers provided by the framework, specifically InputDestination and OutputDestination. I was not sure what parameters should I use to send a message or receive one. The answer is that those components are there to simulate the real binder (e.g. RabbitMQ, Kafka, etc), and they have no knowledge of a binding (which is a construct from spring cloud), they only know about destination.
So in my case that translated into something like this:

@SpringBootTest
@Import(TestChannelBinderConfiguration.class)
class ScsProblemTests {

    @Autowired
    private InputDestination input;

    @Autowired
    private OutputDestination output;

    /* ... */

    @Test
    void consumeFromAndProduceIntoSharedTopic() {
        // prepare message A ...

        // simulate message "A" arriving into "all-messages"
        input.send(messageA, "all-messages")

        // ...
        // application will pick up the message
        // the function router will dispatch the message to the right consumer
        // the consumer does some business logic
        // eventually a message "B" should be produced into "all-messages"

        // check if "all-messages" contains message "B"
        // NOTE: "all-messages" will contain both "A" and "B"
        var discard = output.receive(1000, "all-messages"); // message A
        var messageB = output.receive(1000, "all-messages");
        // assertions ...
    }

    /* ... */
}
```

Note: as per the comments in the pseudo-code, the final state is represented by having both A and B in all-messages, in this case the OutputDestination is simply a window to the shared channel, which obviously will also contain the initial message we sent.

Hopefully this makes sense. I cleaned and pushed a working version of the code into a fixed branch in the same repository so you can see the actual fixes.

Body:
I have been trying to implement the following solution:

My application is expecting to consume message A from all-messages, do some business logic and then producing
message B back into all-messages.

The reason why I am using StreamBridge instead of a Function is because I want the producing side to work with an arbitrary
number of produced messages, but for the sake of this example I am trying to simplify the scenario to just one.

Additionally, there is a custom router function in order to avoid an infinite loop, that dispatch the incoming messages
into the appropriate consumer, either incoming or discarded, would be great to have a way to effectively discard messages.

That being said I cannot quite get the implementation right using Spring Cloud Stream.

I'd like your help to understand what am I doing wrong and how to fix the current configure/setup in order to make the solution work as expected, specifically:

Is this solution supported by Spring cloud stream?

Is my application configuration correctly implementing the solution diagram above?

Which bindings exactly should I use inside the app when sending/receiving messages?

The major headache comes from the bindings, so I tried to write a test with different combinations of incoming and outgoing bindings to see what is what, something along these lines:

class ScsProblemTests {

    /* ... */

    @ParameterizedTest
    @MethodSource("bindings")
    void consumeFromAndProduceIntoSharedTopic(String incomingBinding, String outgoingBinding) {
        givenNoOutgoingMessages();
        whenAnIncomingMessageArrives(incomingBinding);
        thenEventuallyAnOutgoingMessageIsProduced(outgoingBinding);
    }

    public static Stream<Arguments> bindings() {
        return Stream.of(
            Arguments.of(null, null),
            Arguments.of(null, "outgoing-out-0"),
            Arguments.of(null, "all-messages"),
            Arguments.of("incoming-in-0", null),
            Arguments.of("incoming-in-0", "outgoing-out-0"),
            Arguments.of("incoming-in-0", "all-messages"),
            Arguments.of("all-messages", null),
            Arguments.of("all-messages", "outgoing-out-0"),
            Arguments.of("all-messages", "all-messages")
        );
    }

    /* ... */
}

I am running this set of tests with a overrides spring profile, where I setup the destination overrides as per the diagram, I am also testing the same set with a different spring profile with no overrides, again just for having a control group to compare with. Only 2 tests from the no-overrides profile pass, the rest fails.

The no-overrides profile does not match the design obviously, but I was curious to see how the overrides where affecting the results, specifically the no-overrides tests that passes are the one where:

incomingBinding=null, outgoingBinding=null

incomingBinding=null, outgoingBinding=outgoing-out-0

And for my understanding of Spring Cloud Stream, even in this no-overrides case, I'd expect also the following to pass (the are not):

incomingBinding=incoming-in-0, outgoingBinding=null

incomingBinding=incoming-in-0, outgoingBinding=outgoing-out-0

At this point I am starting to think I misunderstood some concepts behind Spring Cloud Stream, but I really hope
you can provide some useful advise.

I have shared my code into this repository for convenience.

Thanks in advance.

Body:
Ok here are the problems in my implementation and how to fix them:

I had a typo in the routing configuration, so wasn't enabled, this is how to enable the function router in spring cloud:

spring:
  cloud:
    stream:
      function:
        routing:
          enabled: true

Because I have a function router involved, I don't need anymore to configure my incoming-in-0 binding instead I need to configure a destination for the function router:

spring:
  cloud:
    stream:
      bindings:
        functionRouter-in-0:
          destination: all-messages
        outgoing-out-0:
          destination: all-messages
      source: outgoing
      # ...

I misunderstood bindings/destinations and how to use the testing helpers provided by the framework, specifically InputDestination and OutputDestination. I was not sure what parameters should I use to send a message or receive one. The answer is that those components are there to simulate the real binder (e.g. RabbitMQ, Kafka, etc), and they have no knowledge of a binding (which is a construct from spring cloud), they only know about destination.
So in my case that translated into something like this:

@SpringBootTest
@Import(TestChannelBinderConfiguration.class)
class ScsProblemTests {

    @Autowired
    private InputDestination input;

    @Autowired
    private OutputDestination output;

    /* ... */

    @Test
    void consumeFromAndProduceIntoSharedTopic() {
        // prepare message A ...

        // simulate message "A" arriving into "all-messages"
        input.send(messageA, "all-messages")

        // ...
        // application will pick up the message
        // the function router will dispatch the message to the right consumer
        // the consumer does some business logic
        // eventually a message "B" should be produced into "all-messages"

        // check if "all-messages" contains message "B"
        // NOTE: "all-messages" will contain both "A" and "B"
        var discard = output.receive(1000, "all-messages"); // message A
        var messageB = output.receive(1000, "all-messages");
        // assertions ...
    }

    /* ... */
}

Note: as per the comments in the pseudo-code, the final state is represented by having both A and B in all-messages, in this case the OutputDestination is simply a window to the shared channel, which obviously will also contain the initial message we sent.

Hopefully this makes sense. I cleaned and pushed a working version of the code into a fixed branch in the same repository so you can see the actual fixes.


问:
Azure Data Factory data flow timezone conversion problem
I was trying to convert a timezone from CST to UTC inside a data flow. A quick google gave me that CST is in UTC-6:00, so it should add 6 hours.

The following derived column function for some reason only added 5 hours:

```<code>toUTC(localDatetime, 'CST')
</code>```

Moreover, CurrentUTC('CST') Gave me the correct 6 hours difference, so I had to rewrite this function like this:

```<code>LocalDatetime + hours(toInteger((currentUTC('CST') - currentUTC()) / 1000 / 60 / 60))
// Minus between timestamps gives difference in milliseconds
</code>```

Is this intended behavior? I am worried that when the timezone "shifts" this code will break, so using toUTC would be the best solution, but for some reason it gives incorrect results now

答:
toUTC()  converts a datetime to UTC time zone based on the Daylight-Saving Time effectiveness.

When you are converting from CST to UCT, if your date falls when Daylight saving is effective, then it adds +5 to your date else adds +6 to your date.

Example:

Derived column expression: toUTC(toTimestamp(Date_UTC), 'CST')

Body:
I was trying to convert a timezone from CST to UTC inside a data flow. A quick google gave me that CST is in UTC-6:00, so it should add 6 hours.

The following derived column function for some reason only added 5 hours:

toUTC(localDatetime, 'CST')

Moreover, CurrentUTC('CST') Gave me the correct 6 hours difference, so I had to rewrite this function like this:

LocalDatetime + hours(toInteger((currentUTC('CST') - currentUTC()) / 1000 / 60 / 60))
// Minus between timestamps gives difference in milliseconds

Is this intended behavior? I am worried that when the timezone "shifts" this code will break, so using toUTC would be the best solution, but for some reason it gives incorrect results now


问:
MediaWiki 1.16.4: Script to upload multiple image files
I am using MediaWiki 1.16.4 and currently have to migrate from a help site using HTML to a new help site with mediawiki. One problem I bump into is to upload a mass amount of images onto mediawiki without using the web interface (since that would take forever and a half). I am currently trying to use pywikipedia (which is a python bot) for the task but haven't succeeded yet. Does any of you happen to know a script for the task?

Thansk,

答: Try upload.py from the pywikipedia bot framework.</p>


问:
createdb: database creation failed: ERROR: permission denied to create database
I am pretty much confused about root user,super user,user and permissions! I am not able to create a database inside user "athleticu". Following are the commands I used:-

athleticu@ip-172-30-4-103:/home/ubuntu$ createdb -T template0 simple_db1
createdb: database creation failed: ERROR:  permission denied to create database
athleticu@ip-172-30-4-103:/home/ubuntu$ sudo createdb -T template0 simple_db1
sudo: unable to resolve host ip-172-30-4-103
createdb: could not connect to database template1: FATAL:  role "root" does not exist
```

Please somebody clarify my doubts and tell me what should I write!

答:
Error ? You are trying to perform database actions( Creating Database, creating Roles) using a user that doesn't have the permission for those types of actions you are trying to perform.

solution ? Simply login to your database on the command line, i.e for PostgreSQL one will use "sudo -u postgres psql", then confirm that users specific assigned roles using the command "\du", most probably he/she doesn't have the necessary permissions to perform the actions you wanted. Then simply assign the roles you want the user to perform ,i.e create Database or simply make user "Superuser" by following along(https://chartio.com/resources/tutorials/how-to-change-a-user-to-superuser-in-postgresql/)

Body:
I am pretty much confused about root user,super user,user and permissions! I am not able to create a database inside user "athleticu". Following are the commands I used:-

athleticu@ip-172-30-4-103:/home/ubuntu$ createdb -T template0 simple_db1
createdb: database creation failed: ERROR:  permission denied to create database
athleticu@ip-172-30-4-103:/home/ubuntu$ sudo createdb -T template0 simple_db1
sudo: unable to resolve host ip-172-30-4-103
createdb: could not connect to database template1: FATAL:  role "root" does not exist

Please somebody clarify my doubts and tell me what should I write!


问:
does pop( ) method delete the object from the memory?
In the following code:

```<code>#include<iostream>
#include<queue>
using namespace std;
int main()
{
    queue<int> q;
    int a = 5;
    q.push(a);
    cout << q.front() << endl;    // 5
    int* b = &(q.front());
    q.pop();
    cout << *b;          // Outputs 5 but why ?
}
</code>```

Is a copy of 'a' created inside the queue when I pass 'a' into it ? And when I pop out 'a', then why I am able to dereference the pointer to get the correct output i.e. 5. All I know is that pop() calls the destructor .

Please help !

答:
Calling the destructor means that the object is destroyed and the program is no longer using it. It doesn't mean that the memory it took is now overwritten.
So, in short:

The object data might still be in memory as garbage.

So the contents of the same memory address will depend on whether the program has already used that memory for something else or not.

As the behaviour of accessing garbage data is undefined, this might vary between executions.

Body:
In the following code:

#include<iostream>
#include<queue>
using namespace std;
int main()
{
    queue<int> q;
    int a = 5;
    q.push(a);
    cout << q.front() << endl;    // 5
    int* b = &(q.front());
    q.pop();
    cout << *b;          // Outputs 5 but why ?
}

Is a copy of 'a' created inside the queue when I pass 'a' into it ? And when I pop out 'a', then why I am able to dereference the pointer to get the correct output i.e. 5. All I know is that pop() calls the destructor .

Please help !


问:
Parse JSON String into a Particular Object Prototype in JavaScript
I know how to parse a JSON String and turn it into a JavaScript Object.
 You can use JSON.parse() in modern browsers (and IE9+).

That's great, but how can I take that JavaScript Object and turn it into a particular JavaScript Object (i.e. with a certain prototype)?

For example, suppose you have:

```<code>function Foo()
{
   this.a = 3;
   this.b = 2;
   this.test = function() {return this.a*this.b;};
}
var fooObj = new Foo();
alert(fooObj.test() ); //Prints 6
var fooJSON = JSON.parse({"a":4, "b": 3});
//Something to convert fooJSON into a Foo Object
//....... (this is what I am missing)
alert(fooJSON.test() ); //Prints 12
</code>```

Again, I am not wondering how to convert a JSON string into a generic JavaScript Object.  I want to know how to convert a JSON string into a "Foo" Object.  That is, my Object should now have a function 'test' and properties 'a' and 'b'.

UPDATE
After doing some research, I thought of this...

```<code>Object.cast = function cast(rawObj, constructor)
{
    var obj = new constructor();
    for(var i in rawObj)
        obj[i] = rawObj[i];
    return obj;
}
var fooJSON = Object.cast({"a":4, "b": 3}, Foo);
</code>```

Will that work?

UPDATE May, 2017: The "modern" way of doing this, is via Object.assign, but this function is not available in IE 11 or older Android browsers.

答:
A very simple way to get the desired effect is to add an type attribute while generating the json string, and use this string while parsing the string to generate the object:

```<code>    serialize = function(pObject) {
        return JSON.stringify(pObject, (key, value) => {
            if (typeof(value) == "object") {
                value._type = value.constructor.name;
            }
            return value;
        });
    }

    deSerialize = function(pJsonString) {
        return JSON.parse(pJsonString, (key, value) => {
            if (typeof(value) == "object" && value._type) {
                value = Object.assign(eval('new ' + value._type + '()'), value);
                delete value._type;
            }
            return value;
        });
    }
</code>```

Here a little example of use:

```<code>    class TextBuffer {
        constructor() {
            this.text = "";
        }

        getText = function() {
            return this.text;
        }

        setText = function(pText) {
            this.text = pText;
        }
    }

    let textBuffer = new TextBuffer();
    textBuffer.setText("Hallo");
    console.log(textBuffer.getText()); // "Hallo"

    let newTextBuffer = deSerialize(serialize(textBuffer));
    console.log(newTextBuffer.getText()); // "Hallo"
</code>```

Body:
I know how to parse a JSON String and turn it into a JavaScript Object.
 You can use JSON.parse() in modern browsers (and IE9+).

That's great, but how can I take that JavaScript Object and turn it into a particular JavaScript Object (i.e. with a certain prototype)?

For example, suppose you have:

function Foo()
{
   this.a = 3;
   this.b = 2;
   this.test = function() {return this.a*this.b;};
}
var fooObj = new Foo();
alert(fooObj.test() ); //Prints 6
var fooJSON = JSON.parse({"a":4, "b": 3});
//Something to convert fooJSON into a Foo Object
//....... (this is what I am missing)
alert(fooJSON.test() ); //Prints 12

Again, I am not wondering how to convert a JSON string into a generic JavaScript Object.  I want to know how to convert a JSON string into a "Foo" Object.  That is, my Object should now have a function 'test' and properties 'a' and 'b'.

UPDATE
After doing some research, I thought of this...

Object.cast = function cast(rawObj, constructor)
{
    var obj = new constructor();
    for(var i in rawObj)
        obj[i] = rawObj[i];
    return obj;
}
var fooJSON = Object.cast({"a":4, "b": 3}, Foo);

Will that work?

UPDATE May, 2017: The "modern" way of doing this, is via Object.assign, but this function is not available in IE 11 or older Android browsers.

Body:
A very simple way to get the desired effect is to add an type attribute while generating the json string, and use this string while parsing the string to generate the object:

    serialize = function(pObject) {
        return JSON.stringify(pObject, (key, value) => {
            if (typeof(value) == "object") {
                value._type = value.constructor.name;
            }
            return value;
        });
    }

    deSerialize = function(pJsonString) {
        return JSON.parse(pJsonString, (key, value) => {
            if (typeof(value) == "object" && value._type) {
                value = Object.assign(eval('new ' + value._type + '()'), value);
                delete value._type;
            }
            return value;
        });
    }

Here a little example of use:

    class TextBuffer {
        constructor() {
            this.text = "";
        }

        getText = function() {
            return this.text;
        }

        setText = function(pText) {
            this.text = pText;
        }
    }

    let textBuffer = new TextBuffer();
    textBuffer.setText("Hallo");
    console.log(textBuffer.getText()); // "Hallo"

    let newTextBuffer = deSerialize(serialize(textBuffer));
    console.log(newTextBuffer.getText()); // "Hallo"


问:
Can't Debug Azure JavaScript Function using Visual Studio Code
I am using VS code first time and trying to create a azure function with JavaScript language.
I followed this article.

Environment:

NodeJS v16.x installed

Azure Functions Extensions installed

Azure Functions Core Tools 4.x installed

Problem:

I created one sample azure function. When running the app with f5 it shows the following error

I removed extension bundle configuration from the host.json and tried again. This time, I got the following error

Can anyone please help on me this

Update:

host.json

```<code>    {
  "version": "2.0",
  "logging": {
    "applicationInsights": {
      "samplingSettings": {
        "isEnabled": true,
        "excludedTypes": "Request"
      }
    }
  },
  "extensionBundle": {
    "id": "Microsoft.Azure.Functions.ExtensionBundle",
    "version": "[2.*, 3.0.0)"
  }
}
</code>```

local.settings.json

```<code>{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "",
    "FUNCTIONS_WORKER_RUNTIME": "node"
  }
}
</code>```

index.js

```<code>module.exports = async function (context, req) {
    context.log('JavaScript HTTP trigger function processed a request.');

    const name = (req.query.name || (req.body && req.body.name));
    const responseMessage = name
        ? "Hello, " + name + ". This HTTP triggered function executed successfully."
        : "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response.";

    context.res = {
        // status: 200, /* Defaults to 200 */
        body: responseMessage
    };
}
</code>```

答:
Here is the workaround I did to run the Azure Functions of JavaScript Stack using Visual Studio Code by following the same documentation given in the question

Pre-requisites:

Install VS Code and Install the Azure Account, Azure Functions, Azure Storage, Azurite, Extension from Extensions Menu and Sign-in to Azure Account from VS Code.

Download and Install NodeJS Version 14 (and 16 is in preview I guess), Source: https://nodejs.org/en/download/ and https://phoenixnap.com/kb/install-node-js-npm-on-windows

Verify the installation from command prompt using the commands node -v and npm -v.

If you think, you have installed old NodeJS and NPM versions, go ahead to update them. (Reference: https://phoenixnap.com/kb/update-node-js-version and https://www.npmjs.com/package/npm-upgrade).

Install the Azure Storage Emulator (it is deprecated but still using for local development and testing) from here by clicking on the standalone installer.
-After Installing the Azure Storage Emulator, make sure it is running. If it is shutdown, then run it manually.
To start the Azure Storage Emulator:

Select the  Start  button or press the  Windows  key.

Begin typing  Azure Storage Emulator.

Select the emulator from the list of displayed applications.

Type Start > Enter and Close the Window.

Install the Azure Functions Core Tools v3 as well as v4 used for both Old Version and New Version Stack Development from the source and check the version using func --version command from command prompt.

Install the Azure CLI from the source and PowerShell Module from the source.

Follow this prerequisite check before going to the IDE (VS Code/Visual Studio).

Steps for running the Azure Functions with/without debugging:

Created the workspace folder in the file explorer and opened VS Code from that folder path.

Created Azure Functions Project of JavaScript Stack using Azure Functions extension.
Here is the boilerplate code which is not modified:

Index.js

```<code>module.exports = async  function (context, req) {
context.log('JavaScript HTTP trigger function processed a request.');

const  name = (req.query.name || (req.body && req.body.name));

const  responseMessage = name
? "Hello, " + name + ". This HTTP triggered function executed successfully."
: "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response.";

context.res = {
// status: 200, /* Defaults to 200 */
body:  responseMessage
};
}
</code>```

local.settings.json

```<code>{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"FUNCTIONS_WORKER_RUNTIME": "node"
}
}
</code>```

host.json

```<code>{
"version": "2.0",
"logging": {
"applicationInsights": {
"samplingSettings": {
"isEnabled": true,
"excludedTypes": "Request"
}
}
},
"extensionBundle": {
"id": "Microsoft.Azure.Functions.ExtensionBundle",
"version": "[2.*, 3.0.0)"
}
}
</code>```

No need to remove the extension bundles from host.json

To Run the Function, go to Run Menu > Select either of options Start Debugging or Run without Debugging and I have run this without starting the VS Code, it runs successful in locally.

To Debug the Code:

Put a breakpoint at any line of the code and select the Start Debugging option from the Run Menu

Note:
For the errors like: A host error has occurred during startup operation, Value cannot be null, few resolution steps were:

Use Azure Storage emulator in local development and testing purpose.

Make Sure You have the latest version of Azure Functions Core Tools along with old if you have (You can install multiple version of AF Core Tools and use according to the requirement).

In local.settings.json, value of AzureWebJobsStorage is empty by default but if we're using the project locally, it is better to use like "AzureWebJobsStorage": "UseDevelopmentStorage=true"

You can download the above project from my GitHub Repository.

Body:
I am using VS code first time and trying to create a azure function with JavaScript language.
I followed this article.

Environment:

NodeJS v16.x installed

Azure Functions Extensions installed

Azure Functions Core Tools 4.x installed

Problem:

I created one sample azure function. When running the app with f5 it shows the following error

I removed extension bundle configuration from the host.json and tried again. This time, I got the following error

Can anyone please help on me this

Update:

host.json

    {
  "version": "2.0",
  "logging": {
    "applicationInsights": {
      "samplingSettings": {
        "isEnabled": true,
        "excludedTypes": "Request"
      }
    }
  },
  "extensionBundle": {
    "id": "Microsoft.Azure.Functions.ExtensionBundle",
    "version": "[2.*, 3.0.0)"
  }
}

local.settings.json

{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "",
    "FUNCTIONS_WORKER_RUNTIME": "node"
  }
}

index.js

module.exports = async function (context, req) {
    context.log('JavaScript HTTP trigger function processed a request.');

    const name = (req.query.name || (req.body && req.body.name));
    const responseMessage = name
        ? "Hello, " + name + ". This HTTP triggered function executed successfully."
        : "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response.";

    context.res = {
        // status: 200, /* Defaults to 200 */
        body: responseMessage
    };
}

Body:
Here is the workaround I did to run the Azure Functions of JavaScript Stack using Visual Studio Code by following the same documentation given in the question

Pre-requisites:

Install VS Code and Install the Azure Account, Azure Functions, Azure Storage, Azurite, Extension from Extensions Menu and Sign-in to Azure Account from VS Code.

Download and Install NodeJS Version 14 (and 16 is in preview I guess), Source: https://nodejs.org/en/download/ and https://phoenixnap.com/kb/install-node-js-npm-on-windows

Verify the installation from command prompt using the commands node -v and npm -v.

If you think, you have installed old NodeJS and NPM versions, go ahead to update them. (Reference: https://phoenixnap.com/kb/update-node-js-version and https://www.npmjs.com/package/npm-upgrade).

Install the Azure Storage Emulator (it is deprecated but still using for local development and testing) from here by clicking on the standalone installer.
-After Installing the Azure Storage Emulator, make sure it is running. If it is shutdown, then run it manually.
To start the Azure Storage Emulator:

Select the  Start  button or press the  Windows  key.

Begin typing  Azure Storage Emulator.

Select the emulator from the list of displayed applications.

Type Start > Enter and Close the Window.

Install the Azure Functions Core Tools v3 as well as v4 used for both Old Version and New Version Stack Development from the source and check the version using func --version command from command prompt.

Install the Azure CLI from the source and PowerShell Module from the source.

Follow this prerequisite check before going to the IDE (VS Code/Visual Studio).

Steps for running the Azure Functions with/without debugging:

Created the workspace folder in the file explorer and opened VS Code from that folder path.

Created Azure Functions Project of JavaScript Stack using Azure Functions extension.
Here is the boilerplate code which is not modified:

Index.js

module.exports = async  function (context, req) {
context.log('JavaScript HTTP trigger function processed a request.');

const  name = (req.query.name || (req.body && req.body.name));

const  responseMessage = name
? "Hello, " + name + ". This HTTP triggered function executed successfully."
: "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response.";

context.res = {
// status: 200, /* Defaults to 200 */
body:  responseMessage
};
}

local.settings.json

{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"FUNCTIONS_WORKER_RUNTIME": "node"
}
}

host.json

{
"version": "2.0",
"logging": {
"applicationInsights": {
"samplingSettings": {
"isEnabled": true,
"excludedTypes": "Request"
}
}
},
"extensionBundle": {
"id": "Microsoft.Azure.Functions.ExtensionBundle",
"version": "[2.*, 3.0.0)"
}
}

No need to remove the extension bundles from host.json

To Run the Function, go to Run Menu > Select either of options Start Debugging or Run without Debugging and I have run this without starting the VS Code, it runs successful in locally.

To Debug the Code:

Put a breakpoint at any line of the code and select the Start Debugging option from the Run Menu

Note:
For the errors like: A host error has occurred during startup operation, Value cannot be null, few resolution steps were:

Use Azure Storage emulator in local development and testing purpose.

Make Sure You have the latest version of Azure Functions Core Tools along with old if you have (You can install multiple version of AF Core Tools and use according to the requirement).

In local.settings.json, value of AzureWebJobsStorage is empty by default but if we're using the project locally, it is better to use like "AzureWebJobsStorage": "UseDevelopmentStorage=true"

You can download the above project from my GitHub Repository.


问:
Concatenate two properties inline in select-object
I have an object array like

```<code>{
  Id: 1,
  Name: Name1,
  Users:
  [
     {
       Identifier: a@a.com,
       AccessRight: Admin
     },
     {
       Identifier: b@b.com,
       AccessRight: Member
     }
  ]
},
{
  Id: 2,
  Name: Name2,
  Users:
  [
     {
       Identifier: c@c.com,
       AccessRight: Admin
     }
  ]
}
</code>```

I want to produce the following csv output

Id
Name
Users

1
Name1
a@a.com;Admin,b@b.com;Member

2
Name2
c@c.com;Admin

I'm failing on concatenating the Users...

```<code>$users | Select Id, Name, @{Name="Users";Expression={ $_.Users.Identifier -join "," }}
</code>```

produces:

Id
Name
Users

1
Name1
a@a.com,b@b.com

2
Name2
c@c.com

How can I concatenate the Identifier + AccessRight with semicolon part before joining with commas?

答:
Change your property expression to iterate over each object in Users and concatenate the two relevant sub-properties before you -join (again):

```<code> $users | Select Id, Name, @{Name="Users";Expression={ $_.Users.ForEach({$_.Identifier,$_.AccessRight -join ';'}) -join "," }}
</code>```

Body:
I have an object array like

{
  Id: 1,
  Name: Name1,
  Users:
  [
     {
       Identifier: a@a.com,
       AccessRight: Admin
     },
     {
       Identifier: b@b.com,
       AccessRight: Member
     }
  ]
},
{
  Id: 2,
  Name: Name2,
  Users:
  [
     {
       Identifier: c@c.com,
       AccessRight: Admin
     }
  ]
}

I want to produce the following csv output

Id
Name
Users

1
Name1
a@a.com;Admin,b@b.com;Member

2
Name2
c@c.com;Admin

I'm failing on concatenating the Users...

$users | Select Id, Name, @{Name="Users";Expression={ $_.Users.Identifier -join "," }}

produces:

Id
Name
Users

1
Name1
a@a.com,b@b.com

2
Name2
c@c.com

How can I concatenate the Identifier + AccessRight with semicolon part before joining with commas?

Body:
Change your property expression to iterate over each object in Users and concatenate the two relevant sub-properties before you -join (again):

 $users | Select Id, Name, @{Name="Users";Expression={ $_.Users.ForEach({$_.Identifier,$_.AccessRight -join ';'}) -join "," }}


问:
How can I access the artefact from a pull request for which a build was run?
I'm using azure for a windows app and so I don't really need to go as far as CD as that isn't really relevant.  We eventually plan to move to the cloud but for now that is not the case.

I have now got my .net (c#) build running as a build pipeline and I have a develop branch which Pull Requests are used to merge in changes.  What I want is for a tester to be able to pick up the build artefact that was created for a particular bug or product backlog item when the pull request was successfully completed.  Is this possible without having a Release Pipeline?  I don't currently have a subscription that would allow me to create a release pipeline.

答:
One can find build id with branchName filter :

```<code>GET https://dev.azure.com/{organization}/{project}/_apis/build/builds?api-version=5.0&reasonFilter=pullRequest&definitions={buildDefinitionId}&branchName=refs/pull/{pullRequestId}/merge
</code>```

Once builder id has been retrieved, get artifact by name :

```<code>GET https://dev.azure.com/{organization}/{project}/_apis/build/builds/{buildId}/artifacts?artifactName={artifactName}&api-version=6.0
</code>```

Body:
One can find build id with branchName filter :

GET https://dev.azure.com/{organization}/{project}/_apis/build/builds?api-version=5.0&reasonFilter=pullRequest&definitions={buildDefinitionId}&branchName=refs/pull/{pullRequestId}/merge

Once builder id has been retrieved, get artifact by name :

GET https://dev.azure.com/{organization}/{project}/_apis/build/builds/{buildId}/artifacts?artifactName={artifactName}&api-version=6.0


问:
flutter_launcher_icons not working Unhandled exception: FormatException: Invalid number (at character 1)
I want to change my app icon in flutter using flutter_launcher_icons: ^0.9.2

It shows me errors while I'm running Command flutter pub run flutter_launcher_icons:main

Image of the error

I tried many times but no new results

答:
If the solution proposed by @Iagows doesn't work for you, have a look at this:
flutter_launcher_icons-issues</p>


问:
How to get access token using angular-oauth2-oidc for PKCE code authentication?
I am using angular-oauth2-oidc for authentication and I dont know how to get access token. I am using PKCE code flow with this configuraion

```<code>  authConfig: AuthConfig = {
    issuer: 'https://test.com/oauth/token',
    // requireHttps: false,
    redirectUri:'http://localhost:4200/',
    strictDiscoveryDocumentValidation: false,
    tokenEndpoint: 'https://test.com/oauth/token',
    clientId: 'test',
    // dummyClientSecret: 'test',
    scope: 'openid',
    oidc: true,
    responseType: 'code',
    showDebugInformation: true,
    requestAccessToken: true
  };
</code>```

Flow is initiated with this code and after login it's redirected but I can't get any tokens.

```<code>  getAutherizationCodeWithPKCE() {
    this.oauthService.configure(this.authConfig);
    this.oauthService.initCodeFlow();
    this.oauthService.loadDiscoveryDocumentAndTryLogin
}
</code>```

答:
Issue is resolved with sending client secret in the example above

```<code>   dummyClientSecret: 'test',
</code>```

I am using Cloud Foundry authorization server that seems to require client secret.
Access token then can be easily obtained with

```<code>this.oauthService.getAccessToken()
</code>```

versions:

```<code>angular 13.1.2
angular-oauth2-oidc 13.0.1
cloud foundry uaa 75.11.0
</code>```

I am not deleting this question in case someone get same issue in the future.

Body:
I am using angular-oauth2-oidc for authentication and I dont know how to get access token. I am using PKCE code flow with this configuraion

  authConfig: AuthConfig = {
    issuer: 'https://test.com/oauth/token',
    // requireHttps: false,
    redirectUri:'http://localhost:4200/',
    strictDiscoveryDocumentValidation: false,
    tokenEndpoint: 'https://test.com/oauth/token',
    clientId: 'test',
    // dummyClientSecret: 'test',
    scope: 'openid',
    oidc: true,
    responseType: 'code',
    showDebugInformation: true,
    requestAccessToken: true
  };

Flow is initiated with this code and after login it's redirected but I can't get any tokens.

  getAutherizationCodeWithPKCE() {
    this.oauthService.configure(this.authConfig);
    this.oauthService.initCodeFlow();
    this.oauthService.loadDiscoveryDocumentAndTryLogin
}

Body:
Issue is resolved with sending client secret in the example above

   dummyClientSecret: 'test',

I am using Cloud Foundry authorization server that seems to require client secret.
Access token then can be easily obtained with

this.oauthService.getAccessToken()

versions:

angular 13.1.2
angular-oauth2-oidc 13.0.1
cloud foundry uaa 75.11.0

I am not deleting this question in case someone get same issue in the future.


问:
Xposed Abstract Methods and Interfaces
Is Xposed able to hook abstract methods and/or methods defined in interfaces? I am trying to hook a method defined in an interface with the usual findAndHookMethod, but it returns

```<code>java.lang.IllegalArgumentException: Cannot hook interfaces: public abstract void com.angrydoughnuts.android.alarmclock.MediaListView$OnItemPickListener.onItemPick(android.net.Uri,java.lang.String)
</code>```

This is my method call:

```<code>findAndHookMethod("com.angrydoughnuts.android.alarmclock.MediaListView$OnItemPickListener", lpparam.classLoader, "onItemPick", "android.net.Uri", "java.lang.String", new XC_MethodHook() {
</code>```

OnItemPickListener is the interface.

答: I'm not sure, but you can try XposedBridge.hookAllMethods</p>

Title: Xposed Abstract Methods and Interfaces

Body:
Is Xposed able to hook abstract methods and/or methods defined in interfaces? I am trying to hook a method defined in an interface with the usual findAndHookMethod, but it returns

java.lang.IllegalArgumentException: Cannot hook interfaces: public abstract void com.angrydoughnuts.android.alarmclock.MediaListView$OnItemPickListener.onItemPick(android.net.Uri,java.lang.String)

This is my method call:

findAndHookMethod("com.angrydoughnuts.android.alarmclock.MediaListView$OnItemPickListener", lpparam.classLoader, "onItemPick", "android.net.Uri", "java.lang.String", new XC_MethodHook() {

OnItemPickListener is the interface.


问:
copy line from a txt file and replace it in another txt file at specific number line using PowerShell
I'm relatively new to PowerShell. I would like to be able to copy a text line from a list file and paste it on another text file at specific number line.

I have the first step copy specific number line and need the second steppaste at specific number line:

```<code>Get-Content C:\Temp\Megateo\Hash.txt -TotalCount 121 | Select-Object -Skip 1 -First 1 > C:\Temp\Megateo\Monin.txt
</code>```

答:
Looking at the title of your question and also the latest comment you wrote, you are actually looking for a way to replace a line, rather than inserting a new line.

Try

In real life you want to get the input from files:

```<code># Get your replacement line from the first file
$replacementText = Get-Content -Path 'C:\Temp\Megateo\Hash.txt' -TotalCount 121 | Select-Object -Skip 1 -First 1
# and read the file you want to update
$lines = Get-Content -Path 'C:\Temp\Megateo\Monin.txt'
</code>```

But for demo here I'm using:

```<code>$replacementText = "This is the new line"

$lines = @"
text text text text text text
text text text text text text
Replace this line with something NEW
text text text text text text
text text text text text text
"@ -split '\r?\n'
</code>```

If you already know the line index to replace, simply do

```<code>$index = 2
if ($index -lt $lines.Count) {
    $lines[$index] = $replacementText
    # and write the updated file
    $lines | Set-Content -Path 'C:\Temp\Megateo\Monin.txt'
}
else {
    Write-Warning "'$index' exceeds the total number of lines ($($lines.Count))"
}
</code>```

However, if you need to first find the index using a search string, you can either use the .IndexOf() method on the $lines array as in Santiago's helpful answer, which is Case-Sensitive, or use the .FindIndex() like below to find the line case-insensitively.

Remember that both .IndexOf() and .FindIndex() can return a value of -1 if the string you're looking for is not found.

```<code># make the FindIndex() array method look for the string case-insensitively
$predicate = [Predicate[String]]{param($s) $s -like 'replace this line*'}

# try and find the index of the line to replace. if not found, this returns -1
$index = [array]::FindIndex([string[]]$lines, $predicate)
if ($index -ge 0) {
    # now change the line at position $index with the replacement string
    $lines[$index] = $replacementText
    # and write the updated file
    $lines | Set-Content -Path 'C:\Temp\Megateo\Monin.txt'
}
else {
    Write-Warning "Could not find the requested line"
}
</code>```

Body:
I'm relatively new to PowerShell. I would like to be able to copy a text line from a list file and paste it on another text file at specific number line.

I have the first step copy specific number line and need the second steppaste at specific number line:

Get-Content C:\Temp\Megateo\Hash.txt -TotalCount 121 | Select-Object -Skip 1 -First 1 > C:\Temp\Megateo\Monin.txt

Body:
Looking at the title of your question and also the latest comment you wrote, you are actually looking for a way to replace a line, rather than inserting a new line.

Try

In real life you want to get the input from files:

# Get your replacement line from the first file
$replacementText = Get-Content -Path 'C:\Temp\Megateo\Hash.txt' -TotalCount 121 | Select-Object -Skip 1 -First 1
# and read the file you want to update
$lines = Get-Content -Path 'C:\Temp\Megateo\Monin.txt'

But for demo here I'm using:

$replacementText = "This is the new line"

$lines = @"
text text text text text text
text text text text text text
Replace this line with something NEW
text text text text text text
text text text text text text
"@ -split '\r?\n'

If you already know the line index to replace, simply do

$index = 2
if ($index -lt $lines.Count) {
    $lines[$index] = $replacementText
    # and write the updated file
    $lines | Set-Content -Path 'C:\Temp\Megateo\Monin.txt'
}
else {
    Write-Warning "'$index' exceeds the total number of lines ($($lines.Count))"
}

However, if you need to first find the index using a search string, you can either use the .IndexOf() method on the $lines array as in Santiago's helpful answer, which is Case-Sensitive, or use the .FindIndex() like below to find the line case-insensitively.

Remember that both .IndexOf() and .FindIndex() can return a value of -1 if the string you're looking for is not found.

# make the FindIndex() array method look for the string case-insensitively
$predicate = [Predicate[String]]{param($s) $s -like 'replace this line*'}

# try and find the index of the line to replace. if not found, this returns -1
$index = [array]::FindIndex([string[]]$lines, $predicate)
if ($index -ge 0) {
    # now change the line at position $index with the replacement string
    $lines[$index] = $replacementText
    # and write the updated file
    $lines | Set-Content -Path 'C:\Temp\Megateo\Monin.txt'
}
else {
    Write-Warning "Could not find the requested line"
}


问:
R - Issues with group order/ ggplot dodge barchart
I looked through other questions but I didn't find this exact problem

```<code>company<-c("c1","c1","c2","c2","c2","c3","c3","c3","c4","c4", "c4")
subsegment<- c("Sub2","Sub3", "Sub1","Sub2", "Sub3", "Sub1","Sub2", "Sub3", "Sub1","Sub2", "Sub3")
values<-c(120,300,30,300,1800,10,96,277, 10, 400, 1100)
df<- data.frame(company,subsegment, values)
</code>```

That's my code for the data frame and I try to make a grouped barchart:

```<code>plot.1<- ggplot(df, aes(fill=company, y=values, x=subsegment)) +
  geom_bar(position="dodge", stat="identity", alpha=0.5)
</code>```

The plot I get is exactly what I want, values for each company grouped by SubSegment... except the subsegments are ordered from left to right in default in alphabetical order "Sub1","Sub2","Sub3" and same for the companies...

I would like the same graphic to appear, but showing first "Sub3" then "Sub1" and last "Sub2"
I would also like for the bars inside each group (inside each subsegment) to be ordered by value from bigger to smaller, instead of just alphabetically.

I attach picture of the graph I get:

Hope the question is clear enough, I want to get the same graph but change order of things in the x axis

答:
I did it by manipulating the underlying data.  I like to do all my factor munging outside of the ggplot call; I think this makes things cleaner.  Oh the joys of factors:</p>
```<code>df<- data.frame(company,subsegment, values) %>%
  # subsegment order
  mutate(reorder_subsegment = case_when(
    subsegment == "Sub3" ~ 1,
    subsegment == "Sub1" ~ 2,
    subsegment == "Sub2" ~ 3
  )) %>%
  mutate(subsegment = reorder(subsegment, reorder_subsegment)) %>%
  # company order
  group_by(company) %>%
  mutate(company_by_value = sum(values)) %>%
  ungroup() %>%
  mutate(company = reorder(company, -company_by_value))

ggplot(df, aes(fill=company, y=values, x=subsegment)) +
  geom_col(position="dodge", alpha=0.5)
</code>```

Body:
I looked through other questions but I didn't find this exact problem

company<-c("c1","c1","c2","c2","c2","c3","c3","c3","c4","c4", "c4")
subsegment<- c("Sub2","Sub3", "Sub1","Sub2", "Sub3", "Sub1","Sub2", "Sub3", "Sub1","Sub2", "Sub3")
values<-c(120,300,30,300,1800,10,96,277, 10, 400, 1100)
df<- data.frame(company,subsegment, values)

That's my code for the data frame and I try to make a grouped barchart:

plot.1<- ggplot(df, aes(fill=company, y=values, x=subsegment)) +
  geom_bar(position="dodge", stat="identity", alpha=0.5)

The plot I get is exactly what I want, values for each company grouped by SubSegment... except the subsegments are ordered from left to right in default in alphabetical order "Sub1","Sub2","Sub3" and same for the companies...

I would like the same graphic to appear, but showing first "Sub3" then "Sub1" and last "Sub2"
I would also like for the bars inside each group (inside each subsegment) to be ordered by value from bigger to smaller, instead of just alphabetically.

I attach picture of the graph I get:

Hope the question is clear enough, I want to get the same graph but change order of things in the x axis

Body:
I did it by manipulating the underlying data.  I like to do all my factor munging outside of the ggplot call; I think this makes things cleaner.  Oh the joys of factors:

df<- data.frame(company,subsegment, values) %>%
  # subsegment order
  mutate(reorder_subsegment = case_when(
    subsegment == "Sub3" ~ 1,
    subsegment == "Sub1" ~ 2,
    subsegment == "Sub2" ~ 3
  )) %>%
  mutate(subsegment = reorder(subsegment, reorder_subsegment)) %>%
  # company order
  group_by(company) %>%
  mutate(company_by_value = sum(values)) %>%
  ungroup() %>%
  mutate(company = reorder(company, -company_by_value))

ggplot(df, aes(fill=company, y=values, x=subsegment)) +
  geom_col(position="dodge", alpha=0.5)


问:
Is there a way to add multiple columns (and edit the values) based on another multiple conditions on another column?
I am working on a dataset of compilation of vaccination records of different countries. I would like to add multiple columns of different vaccines used by the countries by indicating 1 or 0.

Preview of "vaccines" column of dataset

```<code>list_4
OUTPUT
[1] "Pfizer/BioNTech"    "Sputnik V"          "Oxford/AstraZeneca" "Moderna"            "Sinopharm/Beijing"  "Sinovac"            "Sinopharm/Wuhan"
 [8] "Covaxin"            "EpiVacCorona"       "Johnson&Johnson"
[1] "character"
</code>```

I was able to achieve (Final result) it with the code below (hard coding), is there any way to achieve the same result by utilising list_4 directly?

```<code>data_6 <- data_5 %>%
  mutate("Pfizer/BioNTech" = ifelse(str_detect(vaccines, "Pfizer/BioNTech"), 1, 0)) %>%
  mutate("Sputnik V" = ifelse(str_detect(vaccines, "Sputnik V"), 1, 0)) %>%
  mutate("Oxford/AstraZeneca" = ifelse(str_detect(vaccines, "Oxford/AstraZeneca"), 1, 0)) %>%
  mutate("Moderna" = ifelse(str_detect(vaccines, "Moderna"), 1, 0)) %>%
  mutate("Sinopharm/Beijing" = ifelse(str_detect(vaccines, "Sinopharm/Beijing"), 1, 0)) %>%
  mutate("Sinovac" = ifelse(str_detect(vaccines, "Sinovac"), 1, 0)) %>%
  mutate("Sinopharm/Wuhan" = ifelse(str_detect(vaccines, "Sinopharm/Wuhan"), 1, 0)) %>%
  mutate("Covaxin" = ifelse(str_detect(vaccines, "Covaxin"), 1, 0)) %>%
  mutate("EpiVacCorona" = ifelse(str_detect(vaccines, "EpiVacCorona"), 1, 0)) %>%
  mutate("Johnson&Johnson" = ifelse(str_detect(vaccines, "Johnson&Johnson"), 1, 0))
</code>```

答:
Maybe the OP is looking for a way to get dummy cols that tell whether a given vaccine is present in the vector of vaccines contained in every row.

small reprex

```<code>strings <- c('Oxford/AstraZeneca, Sputnik V', 'Moderna, Oxford/AstraZeneca')
vaccines <- c('Oxford/AstraZeneca', 'Sputnik V', 'Moderna')
df <- tibble(strings)

df

# A tibble: 2 × 1
  strings
  <chr>
1 Oxford/AstraZeneca, Sputnik V
2 Moderna, Oxford/AstraZeneca
</code>```

answer

```<code>
library(purrr)
library(dplyr)
library(stringr)

df %>%
        mutate(map_dfc(vaccines, ~+str_detect(strings, .x)) %>%
                       set_names(vaccines))

# A tibble: 2 × 4
  strings                       `Oxford/AstraZeneca` `Sputnik V` Moderna
  <chr>                                        <int>       <int>   <int>
1 Oxford/AstraZeneca, Sputnik V                    1           1       0
2 Moderna, Oxford/AstraZeneca                      1           0       1
</code>```

Body:
I am working on a dataset of compilation of vaccination records of different countries. I would like to add multiple columns of different vaccines used by the countries by indicating 1 or 0.

Preview of "vaccines" column of dataset

list_4
OUTPUT
[1] "Pfizer/BioNTech"    "Sputnik V"          "Oxford/AstraZeneca" "Moderna"            "Sinopharm/Beijing"  "Sinovac"            "Sinopharm/Wuhan"
 [8] "Covaxin"            "EpiVacCorona"       "Johnson&Johnson"
[1] "character"

I was able to achieve (Final result) it with the code below (hard coding), is there any way to achieve the same result by utilising list_4 directly?

data_6 <- data_5 %>%
  mutate("Pfizer/BioNTech" = ifelse(str_detect(vaccines, "Pfizer/BioNTech"), 1, 0)) %>%
  mutate("Sputnik V" = ifelse(str_detect(vaccines, "Sputnik V"), 1, 0)) %>%
  mutate("Oxford/AstraZeneca" = ifelse(str_detect(vaccines, "Oxford/AstraZeneca"), 1, 0)) %>%
  mutate("Moderna" = ifelse(str_detect(vaccines, "Moderna"), 1, 0)) %>%
  mutate("Sinopharm/Beijing" = ifelse(str_detect(vaccines, "Sinopharm/Beijing"), 1, 0)) %>%
  mutate("Sinovac" = ifelse(str_detect(vaccines, "Sinovac"), 1, 0)) %>%
  mutate("Sinopharm/Wuhan" = ifelse(str_detect(vaccines, "Sinopharm/Wuhan"), 1, 0)) %>%
  mutate("Covaxin" = ifelse(str_detect(vaccines, "Covaxin"), 1, 0)) %>%
  mutate("EpiVacCorona" = ifelse(str_detect(vaccines, "EpiVacCorona"), 1, 0)) %>%
  mutate("Johnson&Johnson" = ifelse(str_detect(vaccines, "Johnson&Johnson"), 1, 0))

Body:
Maybe the OP is looking for a way to get dummy cols that tell whether a given vaccine is present in the vector of vaccines contained in every row.

small reprex

strings <- c('Oxford/AstraZeneca, Sputnik V', 'Moderna, Oxford/AstraZeneca')
vaccines <- c('Oxford/AstraZeneca', 'Sputnik V', 'Moderna')
df <- tibble(strings)

df

# A tibble: 2 × 1
  strings
  <chr>
1 Oxford/AstraZeneca, Sputnik V
2 Moderna, Oxford/AstraZeneca

answer

library(purrr)
library(dplyr)
library(stringr)

df %>%
        mutate(map_dfc(vaccines, ~+str_detect(strings, .x)) %>%
                       set_names(vaccines))

# A tibble: 2 × 4
  strings                       `Oxford/AstraZeneca` `Sputnik V` Moderna
  <chr>                                        <int>       <int>   <int>
1 Oxford/AstraZeneca, Sputnik V                    1           1       0
2 Moderna, Oxford/AstraZeneca                      1           0       1


问:
How to set statuscode on postman throw exeption java
i have this snippet , in my controller

```<code>public String getlavoro(String nome , String cognome) throws Exception {
        if (determinareSeEUnaStringaONo(nome)== false && determinareSeEUnaStringaONo(cognome) == false){
            List<Cliente> cliente =clienteRepository.findByNomeAndCognome(nome,cognome);
            if (cliente.size() != 0){
                Cliente c = cliente.get(0);
                Optional<Lavoro> lavoro = lavoroRepository.findByIdcliente(Math.toIntExact(c.getId()));
                return "nome : "+c.getNome()+" cognome "+c.getCognome()+" lavoro :"+ lavoro.get().getNomelavoro();
            }else
                throw new  // insert status code 404
        throw new //  insert status code 400
    }
</code>```

basically i have to set statuscode on postman throw exeption , i can i write it ? i have to change to specific status this on postman

enter image description here

答:
You have to define a mapping between your custom exception and your http code, in a ControllerAdvice class.

BadRequestException map to 400 http code

RecordNotFoundException map to 404 http code

Body:
i have this snippet , in my controller

public String getlavoro(String nome , String cognome) throws Exception {
        if (determinareSeEUnaStringaONo(nome)== false && determinareSeEUnaStringaONo(cognome) == false){
            List<Cliente> cliente =clienteRepository.findByNomeAndCognome(nome,cognome);
            if (cliente.size() != 0){
                Cliente c = cliente.get(0);
                Optional<Lavoro> lavoro = lavoroRepository.findByIdcliente(Math.toIntExact(c.getId()));
                return "nome : "+c.getNome()+" cognome "+c.getCognome()+" lavoro :"+ lavoro.get().getNomelavoro();
            }else
                throw new  // insert status code 404
        throw new //  insert status code 400
    }

basically i have to set statuscode on postman throw exeption , i can i write it ? i have to change to specific status this on postman

enter image description here


问:
What are exact requirements on automatic storage duration?
Depending on the compiler the following code:

```<code>int main()
{
   srand( 0 );
   if( rand() ) {
      char buffer[600 * 1024] = {};
      printf( buffer );
   } else {
      char buffer[500 * 1024] = {};
      printf( buffer );
   }
   return 0;
}
</code>```

when ran on a system with maximum stack size equal to 1 megabyte either prints an empty string or crashes with a stack overflow.

The difference is because different compilers allocate automatic storage differently. Most compilers allocate storage for all objects on function start, so in the code above they allocate 600+400=1100 kilobytes and that leads to stack overflow. Some compilers are smarter and they see that those two arrays can never be accessible at the same time so they reuse the same memory and only allocate 600 kilobytes and the program runs fine.

Now The Standard says (3.7/1) that storage duration defines the minimum potential lifetime of the storage and then (3.7.2/1) that the storage for these objects [with automatic duration] lasts until the block in which they are created exists.

I don't understand how 3.7/1 and 3.7.2/1 are to be applied together. One says that duration is minimum potential and the other says explicitly that it lasts until the block exists. Looks like according to the first both allocation strategies are legal, but the second demands that only "reuse" allocation strategy is used.

How do 3.7/1 and 3.7.2/1 co-exist? Is it legal to allocate more memory than the program needs in the worst case (the first strategy)?

答: "Lasts until" also is a minimum.</p>

Body:
Depending on the compiler the following code:

int main()
{
   srand( 0 );
   if( rand() ) {
      char buffer[600 * 1024] = {};
      printf( buffer );
   } else {
      char buffer[500 * 1024] = {};
      printf( buffer );
   }
   return 0;
}

when ran on a system with maximum stack size equal to 1 megabyte either prints an empty string or crashes with a stack overflow.

The difference is because different compilers allocate automatic storage differently. Most compilers allocate storage for all objects on function start, so in the code above they allocate 600+400=1100 kilobytes and that leads to stack overflow. Some compilers are smarter and they see that those two arrays can never be accessible at the same time so they reuse the same memory and only allocate 600 kilobytes and the program runs fine.

Now The Standard says (3.7/1) that storage duration defines the minimum potential lifetime of the storage and then (3.7.2/1) that the storage for these objects [with automatic duration] lasts until the block in which they are created exists.

I don't understand how 3.7/1 and 3.7.2/1 are to be applied together. One says that duration is minimum potential and the other says explicitly that it lasts until the block exists. Looks like according to the first both allocation strategies are legal, but the second demands that only "reuse" allocation strategy is used.

How do 3.7/1 and 3.7.2/1 co-exist? Is it legal to allocate more memory than the program needs in the worst case (the first strategy)?

Body: "Lasts until" also is a minimum.


问:
Why do you divide by two when checking prime numbers in Java?
I was looking over this on YouTube and saw some code. I got most of it but didn't understand at all the reason why you the value n divide by two. Could someone please explain it?</p>
```<code>import java.util.ArrayList;

public class Primes {

    public static void main(String[] args) {

        System.out.println(findPrimes(1, 100));

    }

    public static ArrayList<Integer> findPrimes(int start, int end) {

        ArrayList<Integer> primes = new ArrayList<Integer>();

        for(int n = start; n < end; n++) {
            boolean prime = true;

            int i = 2;
            while(i <= n/2) {
                if(n % i == 0) {
                    prime = false;
                    break;
                }
                i++;
            }

            if(prime) {
                primes.add(n);
            }
        }

        return primes;
    }

}
</code>```

答: A number can only be divided by a number that is less than or equal to its half. Or the number to be divided itself.</p>

Body:
I was looking over this on YouTube and saw some code. I got most of it but didn't understand at all the reason why you the value n divide by two. Could someone please explain it?

import java.util.ArrayList;

public class Primes {

    public static void main(String[] args) {

        System.out.println(findPrimes(1, 100));

    }

    public static ArrayList<Integer> findPrimes(int start, int end) {

        ArrayList<Integer> primes = new ArrayList<Integer>();

        for(int n = start; n < end; n++) {
            boolean prime = true;

            int i = 2;
            while(i <= n/2) {
                if(n % i == 0) {
                    prime = false;
                    break;
                }
                i++;
            }

            if(prime) {
                primes.add(n);
            }
        }

        return primes;
    }

}


问:
Have two columns in Markdown
I would like to write a coding standard specification document with good and bad coding examples. Each rule should have a number, a description and an example.

For example here is the rule 1:

```<code># Rule 1
Description for rule 1.

## Good
```c
int foo (void)
{
    int i;
}
```

## Bad
```c
int foo (void) {
    int i;
}
```
</code>```

From each rule, I would like to generate a PDF or an HTML page with a global table of contents.

How can I write a Markdown compatible code that can represent horizontally aligned code blocks with syntactic coloring?

Like this (this is an image):

I know that I could use HTML inside my Markdown document, so I might be able to write something like this:

```<code><good>
```c
int foo (void)
{
    int i;
}
```
</good>
<bad>
```c
int foo (void) {
    int i;
}
```
</bad>
</code>```

And process the data afterwards (I still don't know how)

```<code>markdown -> own-tags-processing -> LaTeX -> pdf
markdown -> own-tags-processing -> HTML
</code>```

Is there a better way to horizontally align two blocks of code horizontally?

答:
Depending on what flavour of markdown you're using, if you're using R Markdown at least, you can use the ::: format to create multi-column layouts. Much simpler than embedding HTML etc..

The ::: is shorthand for a  tag, but unlike adding a raw HTML, the ::: can wrap code blocks etc. to keep everything in the R markdown framework.

The ::: must be followed by {} containing any declarations you would put inside the opening  tag, or empty if there are none, but it must be there (ie :::{}).

Here, you can add any css styling or classes, even bootstrap to make your markdown responsive:

```<code>::: {.row}
  ::: {.col-md-4}
    table ...
  :::
  ::: {.col-md-8}
    graph ...
  :::
:::
</code>```

You can find more detail at https://enzedonline.com/en/tech-blog/adding-multi-column-formats-to-r-markdown-documents/

Example:

```<code>```{r, fig.height=4, fig.width=5, warning=FALSE, message=FALSE}
library(ggthemes)
library(kableExtra)
library(ggplot2)
library(dplyr)
data("mtcars")
```
:::::::::::::: {.columns}
::: {.column width="30%"}

```{r}
mtcars %>%
    select(disp, mpg) %>%
    sample_n(10) %>%
    kbl() %>%
    kable_styling()
```

:::
::: {.column width="5%"}

\

:::
::: {.column width="65%"}

\

```{r, fig.height=4, fig.width=7}
mtcars %>%
    ggplot(aes(x=disp, y=mpg)) +
    geom_point() +
    theme_excel_new()
```

:::
::::::::::::::
</code>```

Gives the following output:

Title: Have two columns in Markdown

Body:
I would like to write a coding standard specification document with good and bad coding examples. Each rule should have a number, a description and an example.

For example here is the rule 1:

# Rule 1
Description for rule 1.

## Good
```c
int foo (void)
{
    int i;
}
```

## Bad
```c
int foo (void) {
    int i;
}
```

From each rule, I would like to generate a PDF or an HTML page with a global table of contents.

How can I write a Markdown compatible code that can represent horizontally aligned code blocks with syntactic coloring?

Like this (this is an image):

I know that I could use HTML inside my Markdown document, so I might be able to write something like this:

<good>
```c
int foo (void)
{
    int i;
}
```
</good>
<bad>
```c
int foo (void) {
    int i;
}
```
</bad>

And process the data afterwards (I still don't know how)

markdown -> own-tags-processing -> LaTeX -> pdf
markdown -> own-tags-processing -> HTML

Is there a better way to horizontally align two blocks of code horizontally?

Body:
Depending on what flavour of markdown you're using, if you're using R Markdown at least, you can use the ::: format to create multi-column layouts. Much simpler than embedding HTML etc..

The ::: is shorthand for a  tag, but unlike adding a raw HTML, the ::: can wrap code blocks etc. to keep everything in the R markdown framework.

The ::: must be followed by {} containing any declarations you would put inside the opening  tag, or empty if there are none, but it must be there (ie :::{}).

Here, you can add any css styling or classes, even bootstrap to make your markdown responsive:

::: {.row}
  ::: {.col-md-4}
    table ...
  :::
  ::: {.col-md-8}
    graph ...
  :::
:::

You can find more detail at https://enzedonline.com/en/tech-blog/adding-multi-column-formats-to-r-markdown-documents/

Example:

```{r, fig.height=4, fig.width=5, warning=FALSE, message=FALSE}
library(ggthemes)
library(kableExtra)
library(ggplot2)
library(dplyr)
data("mtcars")
```
:::::::::::::: {.columns}
::: {.column width="30%"}

```{r}
mtcars %>%
    select(disp, mpg) %>%
    sample_n(10) %>%
    kbl() %>%
    kable_styling()
```

:::
::: {.column width="5%"}

\

:::
::: {.column width="65%"}

\

```{r, fig.height=4, fig.width=7}
mtcars %>%
    ggplot(aes(x=disp, y=mpg)) +
    geom_point() +
    theme_excel_new()
```

:::
::::::::::::::

Gives the following output: