问:
PHP-Isset function is not working
I am new to PHP. My isset function is not working .It does not not show  error .It always insert the table. I have given my code. Kindly advice what i done wrong on this

```<code><?php
if(isset($_POST['submit'])) {
    $a= $_POST['companyname'];
    $b= $_POST['ballpark_url'];
    $c= $_POST['username'];
    $d= $_POST['email'];
    $e= $_POST['login1'];
    $f= $_POST['pass'];
    $error = false;
    if(validname($a) ==false) {
        echo $nameerror = "enter the valid name";
    }
    if(validemail($d) ==false) {
        echo $nameerror = "enter the valid email";
    }
    if(isset($_POST['companyname'])) {
        if($error==false) {
            $query= "INSERT INTO user VALUES ('$a','$b','$c','$d','$e','$f','');";
            if(!mysql_query($query)) {
                die ('error:'.mysql_error());
            }
            mysql_close($conn);
        }
        include("templats/header_1.html");
        include("templats/content.html");
        include("templats/footer.html");
    }
?>
</code>```

kindly rectify the issue in my code and send back to me...

答: Following on from Garvey, if it doesnt exist, then check in your HTML that you have set a submit button with the name submit...... (thanks shef for saying to post it ;))</p>

Title: PHP-Isset function is not working

Body:
I am new to PHP. My isset function is not working .It does not not show  error .It always insert the table. I have given my code. Kindly advice what i done wrong on this

<?php
if(isset($_POST['submit'])) {
    $a= $_POST['companyname'];
    $b= $_POST['ballpark_url'];
    $c= $_POST['username'];
    $d= $_POST['email'];
    $e= $_POST['login1'];
    $f= $_POST['pass'];
    $error = false;
    if(validname($a) ==false) {
        echo $nameerror = "enter the valid name";
    }
    if(validemail($d) ==false) {
        echo $nameerror = "enter the valid email";
    }
    if(isset($_POST['companyname'])) {
        if($error==false) {
            $query= "INSERT INTO user VALUES ('$a','$b','$c','$d','$e','$f','');";
            if(!mysql_query($query)) {
                die ('error:'.mysql_error());
            }
            mysql_close($conn);
        }
        include("templats/header_1.html");
        include("templats/content.html");
        include("templats/footer.html");
    }
?>

kindly rectify the issue in my code and send back to me...


来源: stackexchange

问:
Removing line breaks in Ruby
I have a problem removing \n and \r tags. When I'm using double quotes, it works fine, otherwise it leaves "\". With gsub, it doesn't work without double quotes at all. Why?

```<code>"Remove \n".delete('\n') # result: "Remove"
'Remove \n'.delete('\n') # result: "Remove \"
</code>```

I found this because it doesn't work with results from the database.

答:
If you don't care about extra blank spaces, the cleanest solution is to use #strip:

"Remove \n".strip
```

ContentLicense: CC BY-SA 4.0

Title: Removing line breaks in Ruby

Body:
I have a problem removing \n and \r tags. When I'm using double quotes, it works fine, otherwise it leaves "\". With gsub, it doesn't work without double quotes at all. Why?

"Remove \n".delete('\n') # result: "Remove"
'Remove \n'.delete('\n') # result: "Remove \"

I found this because it doesn't work with results from the database.


问:
Change password directly without Okta web console
Does Okta have an API to send “change password” URL to the user (or widget) ?

Okta has “change password” API.

https://developer.okta.com/docs/reference/api/users/#change-password

However, it requres oldPassword/newPassword as input parameters. It means that our system needs to temporarily store password on memory when I integrate Okta with our system. Due to the security reason, we would like to avoid storing password in our system and directly input password to Okta. Our user will not use Okta web console directly.

I found we can send “reset password” URL to the user.

https://developer.okta.com/docs/reference/api/users/#reset-password

However, it is not “change password” because user status is changed.

Can we have a good solution ?

答: Yes, you need to update user with POST and send a new credentials object to update its password- https://developer.okta.com/docs/reference/api/users/#update-user


问:
Find the n largest occurrences of duplicate values in a column
I have a 7GB csv file from which I need to find the first n values which occurred mostly in the 5th column. The format of my file is as:

```<code>"instance id","src IP","destination ip","63812","389"
"instance id","src IP","destination ip","389","65311"
"instance id","src IP","destination ip","63812","389"
"instance id","src IP","destination ip","88","49194"
"instance id","src IP","destination ip","12489","49194"
"instance id","src IP","destination ip","63812","389"
"instance id","src IP","destination ip","63812","389"
</code>```

Using the following command
awk -F , ' !count[$5]++ {save[$5] = $0; next} count[$5] > 0 { print save[$5] " is " count[$5] " times"} ' example.csv
able to find the following output

```<code>"instance id","src IP","destination ip","63812","389" is 1 times
"instance id","src IP","destination ip","389","65311" is 1 times
"instance id","src IP","destination ip","63812","389" is 2 times
"instance id","src IP","destination ip","88","49194" is 1 times
"instance id","src IP","destination ip","12489","49194" is 2 times
"instance id","src IP","destination ip","63812","389" is 3 times
"instance id","src IP","destination ip","63812","389" is 4 times
</code>```

but not able to understand how to get the top 50 rows in which the 5th column entry duplicated most of the time.

Let's suppose if n=2, then my output should be like following:

```<code>"instance id","src IP","destination ip","63812","389" is 4 times
"instance id","src IP","destination ip","12489","49194" is 2 times
</code>```

答:
This method is using GNU awk extensions:

Return n most frequent values in column p:

```<code>awk 'BEGIN{n=50; p=5; PROCINFO["sorted_in"]="@val_num_desc"} {a[$p]++}
     END { for(i in a) { if (!n--) { break }; print i } }' file
</code>```

Return last record of n most frequent values in column p:

```<code>awk 'BEGIN{n=50; p=5; PROCINFO["sorted_in"]="@val_num_desc"} {a[$p]++;b[$p]=$0}
     END { for(i in a) { if (!n--) { break }; print b[i] } }' file
</code>```

Adopting the above to the expected output of the OP:

```<code>awk 'BEGIN{n=50; p=5; FS=","; PROCINFO["sorted_in"]="@val_num_desc"}
     {a[$p]++;b[$p]=$0}
     END { for(i in a) { if (!n--) { break }; print b[i],"is",a[i],"times" } }' file
</code>```

Body:
I have a 7GB csv file from which I need to find the first n values which occurred mostly in the 5th column. The format of my file is as:

"instance id","src IP","destination ip","63812","389"
"instance id","src IP","destination ip","389","65311"
"instance id","src IP","destination ip","63812","389"
"instance id","src IP","destination ip","88","49194"
"instance id","src IP","destination ip","12489","49194"
"instance id","src IP","destination ip","63812","389"
"instance id","src IP","destination ip","63812","389"

Using the following command
awk -F , ' !count[$5]++ {save[$5] = $0; next} count[$5] > 0 { print save[$5] " is " count[$5] " times"} ' example.csv
able to find the following output

"instance id","src IP","destination ip","63812","389" is 1 times
"instance id","src IP","destination ip","389","65311" is 1 times
"instance id","src IP","destination ip","63812","389" is 2 times
"instance id","src IP","destination ip","88","49194" is 1 times
"instance id","src IP","destination ip","12489","49194" is 2 times
"instance id","src IP","destination ip","63812","389" is 3 times
"instance id","src IP","destination ip","63812","389" is 4 times

but not able to understand how to get the top 50 rows in which the 5th column entry duplicated most of the time.

Let's suppose if n=2, then my output should be like following:

"instance id","src IP","destination ip","63812","389" is 4 times
"instance id","src IP","destination ip","12489","49194" is 2 times

Body:
This method is using GNU awk extensions:

Return n most frequent values in column p:

awk 'BEGIN{n=50; p=5; PROCINFO["sorted_in"]="@val_num_desc"} {a[$p]++}
     END { for(i in a) { if (!n--) { break }; print i } }' file

Return last record of n most frequent values in column p:

awk 'BEGIN{n=50; p=5; PROCINFO["sorted_in"]="@val_num_desc"} {a[$p]++;b[$p]=$0}
     END { for(i in a) { if (!n--) { break }; print b[i] } }' file

Adopting the above to the expected output of the OP:

awk 'BEGIN{n=50; p=5; FS=","; PROCINFO["sorted_in"]="@val_num_desc"}
     {a[$p]++;b[$p]=$0}
     END { for(i in a) { if (!n--) { break }; print b[i],"is",a[i],"times" } }' file


问:
discord.py on_reaction event not detecting messages after the bot is run
Whenever we add a reaction to a message that was sent before the bot has started, it goes undetected. Any fixes?

Code: (doesn't really matter to the question)

```<code>@client.event
async def on_reaction_add(reaction, user):
  if not user.bot:
    if reaction.message.author.id == bot_id:
      global reactions
      if f'{reaction}' in reactions:
        await VoteAdded(reaction, user)
        await reaction.message.remove_reaction(reaction, user)
      else:
        await reaction.message.remove_reaction(reaction, user)
</code>```

答:
This is because the on_reaction_add function only checks the messages that are in the bot's cache.

To fix this, change the on_reaction_add to on_raw_reaction_add

Body:
Whenever we add a reaction to a message that was sent before the bot has started, it goes undetected. Any fixes?

Code: (doesn't really matter to the question)

@client.event
async def on_reaction_add(reaction, user):
  if not user.bot:
    if reaction.message.author.id == bot_id:
      global reactions
      if f'{reaction}' in reactions:
        await VoteAdded(reaction, user)
        await reaction.message.remove_reaction(reaction, user)
      else:
        await reaction.message.remove_reaction(reaction, user)


问:
Sum rows until customer number changes
How can I sum the rows of product sales 1-3, until the Customer Code changes? Then the next Customer sales should be summed up. There may be customers with only 1 or 2 products also.

答:
If you have CustomerId in column A and Sales in column B, you could add an extra column C with formula:

```<code>=IF(A2=A1,C1+B2,B2)
</code>```

And then drag it down.

Title: Sum rows until customer number changes

Body:
If you have CustomerId in column A and Sales in column B, you could add an extra column C with formula:

=IF(A2=A1,C1+B2,B2)

And then drag it down.


问:
Solution needed, email composer crashes the app
I have a problem with cordova-plugin-email-composer: sending email was working in the app for some time, but today I found out it's not working anymore - upon calling .open on EmailComposer the app closes. Calling .isAvailable() and .getClients() returns undefined.

None of the suggestions at Ionic email composer crash on android 11 work for me. Since I was using @ionic-native/email-composer I also went with @awesome-cordova-plugins/email-composer but it didn't fix the issue either.

Any suggestions for fixes or alternatives?

I'm sorry if someone thinks there's no need for this question since it's asked in that link above, but since it's with accepted answer, I figured I should ask a new one. Powers-that-be: feel free to delete this question if it's inappropriate or unnecessary in your opinion.

答:
After a month of going back-and-forth to fixing this problem with my app, I finally found a solution with the help and guidelines of a kind soul answering my question on the plugin's GitHub repo.

So:

Installed a 6.1.1 gradle version and in Android Studio > Gradle Settings pointed the Gradle to installation folder.

Added distributionUrl=https\://services.gradle.org/distributions/gradle-6.1.1-all.zip to gradle-wrapper.properties.

Added

```<code>    <queries>
          <intent>
                <action android:name="android.intent.action.SENDTO" />
                <data android:scheme="*" />
          </intent>
    </queries>
</code>```

inside of AndroidManifest.xml

Finally set targetSdkVersion = 30 in variables.gradle.

Body:
After a month of going back-and-forth to fixing this problem with my app, I finally found a solution with the help and guidelines of a kind soul answering my question on the plugin's GitHub repo.

So:

Installed a 6.1.1 gradle version and in Android Studio > Gradle Settings pointed the Gradle to installation folder.

Added distributionUrl=https\://services.gradle.org/distributions/gradle-6.1.1-all.zip to gradle-wrapper.properties.

Added

    <queries>
          <intent>
                <action android:name="android.intent.action.SENDTO" />
                <data android:scheme="*" />
          </intent>
    </queries>

inside of AndroidManifest.xml

Finally set targetSdkVersion = 30 in variables.gradle.


问:
How to extend the canvas to the size of the parent div with P5JS?
I want to add my canvas inside a specific div and I want it to be as big as the canvas size.

For example on this code I would like the canvas to be inside the div "p5-div" and to be as big as it is. Having in consideration that the size of the div is unpredictable because is set by css and this can change.

```<code>
<!doctype html>
<html lang="en">
  <head>
    <style>
      #p5-div {
        width: 50%;
        height: 300px
      }
    </style>
  </head>
  <body>
    <h1>My Sketch</h1>
    <div id="p5-div">
    </div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.1/p5.min.js" integrity="sha512-NxocnqsXP3zm0Xb42zqVMvjQIktKEpTIbCXXyhBPxqGZHqhcOXHs4pXI/GoZ8lE+2NJONRifuBpi9DxC58L0Lw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

    <script>
      function setup() {
        createCanvas(100, 100); // this has to be adapted in load time to the side of the div
      }

      function draw(){
        background(33);
      }
    </script>
  </body>
</html>
</code>```

答:
To allocate your canvas inside an specific div you have to use this code in your setup():

```<code>function setup() {
  const myCanvas = createCanvas(divWidth, divHeight);
  myCanvas.parent("div-id");
}
</code>```

Now, in order to know the size of the canvas it gets a bit more complicated, this is my solution:

```<code>class Utils {
  // Calculate the Width in pixels of a Dom element
  static elementWidth(element) {
    return (
      element.clientWidth -
      parseFloat(window.getComputedStyle(element, null).getPropertyValue("padding-left")) -
      parseFloat(window.getComputedStyle(element, null).getPropertyValue("padding-right"))
    )
  }

  // Calculate the Height in pixels of a Dom element
  static elementHeight(element) {
    return (
      element.clientHeight -
      parseFloat(window.getComputedStyle(element, null).getPropertyValue("padding-top")) -
      parseFloat(window.getComputedStyle(element, null).getPropertyValue("padding-bottom"))
    )
  }
}

</code>```

Then we can do:

```<code>function setup() {
  p5Div = document.getElementById("div-id");
  const p5Canvas = createCanvas(Utils.elementWidth(p5Div), Utils.elementHeight(p5Div));
  p5Canvas.parent(p5Div);
}
</code>```

Body:
I want to add my canvas inside a specific div and I want it to be as big as the canvas size.

For example on this code I would like the canvas to be inside the div "p5-div" and to be as big as it is. Having in consideration that the size of the div is unpredictable because is set by css and this can change.

<!doctype html>

My Sketch

Body:
To allocate your canvas inside an specific div you have to use this code in your setup():

function setup() {
  const myCanvas = createCanvas(divWidth, divHeight);
  myCanvas.parent("div-id");
}

Now, in order to know the size of the canvas it gets a bit more complicated, this is my solution:

class Utils {
  // Calculate the Width in pixels of a Dom element
  static elementWidth(element) {
    return (
      element.clientWidth -
      parseFloat(window.getComputedStyle(element, null).getPropertyValue("padding-left")) -
      parseFloat(window.getComputedStyle(element, null).getPropertyValue("padding-right"))
    )
  }

  // Calculate the Height in pixels of a Dom element
  static elementHeight(element) {
    return (
      element.clientHeight -
      parseFloat(window.getComputedStyle(element, null).getPropertyValue("padding-top")) -
      parseFloat(window.getComputedStyle(element, null).getPropertyValue("padding-bottom"))
    )
  }
}

Then we can do:

function setup() {
  p5Div = document.getElementById("div-id");
  const p5Canvas = createCanvas(Utils.elementWidth(p5Div), Utils.elementHeight(p5Div));
  p5Canvas.parent(p5Div);
}


问:
Guide to build Realtime Chat Application in React Native
I wanna build a real-time chat application in react native.
But as a beginner I don't know how!
My actual question is that, what technologies I required to build the app.
I have surf through internet a lot for this, some are telling to use xmpp, some are using socket.io, some are only using firebase.

So please provide me a step by step proper guide about the technologies I should use.

答:
As you are looking for a foundation for both User Interface and real-time database.

The opinionated way is to try:

UI/UX - https://github.com/FaridSafi/react-native-gifted-chat

Realtime database  - https://firebase.google.com/docs/firestore

This's not the best solution or stack available but it will give you a glimpse of what requires to build a modern chat app.


问:
Split string with limit, where last string contains the remainder
e.g. if I run this javascript:

```<code>var str = 'hello_world_there';
var parts = str.split('_', 2);

var p1 = parts[0];
var p2 = parts[1];
</code>```

at the end, p1 contains "hello", and p2 contains "world".

I'd like p1 to contain "hello", and p2 to contain "world_there". i.e. I want p2 to contain the rest of the string, regardless of how many underscores it has (similar to how c#'s String.Split(char[] separator, int count) behaves.

Any workarounds ?

答:
For your specific case where you just want two parts, the simplest thing is indexOf and substring:

```<code>const index = text.indexOf("_");
const p0 = index === -1 ? text : text.substring(0, index);
const p1 = index === -1 ? "" : text.substring(index + 1);
</code>```

Live Example:

const text = "hello_world_there";
const index = text.indexOf("_");
const p0 = index === -1 ? text : text.substring(0, index);
const p1 = index === -1 ? "" : text.substring(index + 1);
console.log(`p0 = "${p0}", p1 = "${p1}"`);```
</div>
</div>
</p>
<p>I've found I want that often enough I have it in a utility module:</p>
```const twoParts = (str, delim = " ") => {
    const index = str.indexOf("_");
    if (index === -1) {
        return [str, ""];
    }
    return [
        str.substring(0, index),
        str.substring(index + delim.length),
    ];
};
```
<p>But if you wanted to do more than just teh two parts, an approach that doesn't require rejoining the string after the fact would be to use a regular expression with capture groups:</p>
```const result = text.match(/^([^_]+)_+([^_]+)_+(.*)$/);
const [_, p0 = "", p1 = "", p2 = ""] = result ?? [];
```
<p>Live Example:</p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const text = "hello_world_xyz_there";
const result = text.match(/^([^_]+)_+([^_]+)_+(.*)$/);
const [_, p0 = "", p1 = "", p2 = ""] = result ?? [];
console.log(`p0 = "${p0}", p1 = "${p1}", p2 = "${p2}"`);</code>```

ContentLicense: CC BY-SA 3.0

Body:
e.g. if I run this javascript:

var str = 'hello_world_there';
var parts = str.split('_', 2);

var p1 = parts[0];
var p2 = parts[1];

at the end, p1 contains "hello", and p2 contains "world".

I'd like p1 to contain "hello", and p2 to contain "world_there". i.e. I want p2 to contain the rest of the string, regardless of how many underscores it has (similar to how c#'s String.Split(char[] separator, int count) behaves.

Any workarounds ?

Body:
For your specific case where you just want two parts, the simplest thing is indexOf and substring:

const index = text.indexOf("_");
const p0 = index === -1 ? text : text.substring(0, index);
const p1 = index === -1 ? "" : text.substring(index + 1);

Live Example:

const text = "hello_world_there";
const index = text.indexOf("_");
const p0 = index === -1 ? text : text.substring(0, index);
const p1 = index === -1 ? "" : text.substring(index + 1);
console.log(`p0 = "${p0}", p1 = "${p1}"`);

I've found I want that often enough I have it in a utility module:

const twoParts = (str, delim = " ") => {
    const index = str.indexOf("_");
    if (index === -1) {
        return [str, ""];
    }
    return [
        str.substring(0, index),
        str.substring(index + delim.length),
    ];
};

But if you wanted to do more than just teh two parts, an approach that doesn't require rejoining the string after the fact would be to use a regular expression with capture groups:

const result = text.match(/^([^_]+)_+([^_]+)_+(.*)$/);
const [_, p0 = "", p1 = "", p2 = ""] = result ?? [];

Live Example:

const text = "hello_world_xyz_there";
const result = text.match(/^([^_]+)_+([^_]+)_+(.*)$/);
const [_, p0 = "", p1 = "", p2 = ""] = result ?? [];
console.log(`p0 = "${p0}", p1 = "${p1}", p2 = "${p2}"`);


问:
Dynamically update options in selectfield depending on another Select Field's data of another Form
Is it possible? If yes, then how? Please, give an example, because I can't find it anywhere. (I found the example of dynamically update options depending on another select field's data but in the same form).</p>

答:
You can add an eventlistener to the change of the select and based on value change any other element.

const select1 = document.querySelector('.select_1');
const option1 = document.querySelector('.select_2 option:first-of-type');
select1.addEventListener('change', function(){
  if(this.value === 'b'){
    option1.textContent = 'newA';
    option1.setAttribute('value','newA');
  } else {
    option1.textContent = 'A';
    option1.setAttribute('value','a');
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
  <select class="select_1">
    <option value="a">A</option>
    <option value="b">B</option>
  </select>
</form>

<form>
  <select class="select_2">
    <option value="a">A</option>
    <option value="b">B</option>
  </select>
</form></code>```

Body:
You can add an eventlistener to the change of the select and based on value change any other element.

const select1 = document.querySelector('.select_1');
const option1 = document.querySelector('.select_2 option:first-of-type');
select1.addEventListener('change', function(){
  if(this.value === 'b'){
    option1.textContent = 'newA';
    option1.setAttribute('value','newA');
  } else {
    option1.textContent = 'A';
    option1.setAttribute('value','a');
  }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
  <select class="select_1">
    <option value="a">A</option>
    <option value="b">B</option>
  </select>
</form>

<form>
  <select class="select_2">
    <option value="a">A</option>
    <option value="b">B</option>
  </select>
</form>


问:
What can cause a Laravel request input to be empty?
I'm posting some data to a Laravel api endpoint:

```<code>POST {{authority}}/api/feedback HTTP/1.1
Content-Type: application/json
Accept: application/json

{
    "message": "Well done! I really like your app.",
    "specs": "Device Info",
}
</code>```

But the data is not in the request:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class FeedbackController extends Controller
{
    public function feedback(Request $request)
    {
        // this works fine:
        // $inputs = file_get_contents('php://input');

        // this gives an empty array:
        $inputs = $request->all();

        dd($inputs);

        return 'just testing';
    }
}
```

What could cause this to happen?

Laravel v8.79.0, php v8.0.14

答:
Since you are expecting a json and ass the documentation specifies better use the input method to access json objects.

example:

$name = $request->input('user.name');
or
$input = $request->input();
for all inputs

Body:
I'm posting some data to a Laravel api endpoint:

POST {{authority}}/api/feedback HTTP/1.1
Content-Type: application/json
Accept: application/json

{
    "message": "Well done! I really like your app.",
    "specs": "Device Info",
}

But the data is not in the request:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class FeedbackController extends Controller
{
    public function feedback(Request $request)
    {
        // this works fine:
        // $inputs = file_get_contents('php://input');

        // this gives an empty array:
        $inputs = $request->all();

        dd($inputs);

        return 'just testing';
    }
}

What could cause this to happen?

Laravel v8.79.0, php v8.0.14


问:
Update timestamps every 30 seconds using setInterval()
I have a list of posts like so:

```<code><ul>
    <li>
       <p class="post" id="432">This is a post</p>
       <p class="timestamp">5 minutes ago</p>
    </li>
    <li>
       <p class="post" id="589">This is another post on the site</p>
       <p class="timestamp">1 hour ago</p>
    </li>
</ul>
</code>```

I want to update the timestamp every 30 seconds (much like facebook timestamps) using setInterval().

```<code>function update_timestamps(){

    $('.timestamp').ajax({
        type    : 'POST',
        url     : '/ajax/refresh_timestamp',
        data    : { 'post_id' : $(this).closest('li').find('p.post').attr('id') },
        success : function(data){
            $(this).html(data);
        }
    });

}

setInterval(update_timestamps(), 30000);
</code>```

Obviously something is wrong with my .ajax() function, or maybe I shouldn't use ajax() at all?

答:
Nothing is inherently wrong with your ajax function. You're just calling setInterval wrong:

```<code>setInterval(update_timestamps, 30000);
</code>```

(notice the function reference to update_timestamps, not function call)

If you think hard, you will realize for yourself why what you did didn't work (hint: you're passing undefined to setInterval).

Body:
I have a list of posts like so:

This is a post

5 minutes ago

This is another post on the site

1 hour ago

I want to update the timestamp every 30 seconds (much like facebook timestamps) using setInterval().

function update_timestamps(){

    $('.timestamp').ajax({
        type    : 'POST',
        url     : '/ajax/refresh_timestamp',
        data    : { 'post_id' : $(this).closest('li').find('p.post').attr('id') },
        success : function(data){
            $(this).html(data);
        }
    });

}

setInterval(update_timestamps(), 30000);

Obviously something is wrong with my .ajax() function, or maybe I shouldn't use ajax() at all?

Body:
Nothing is inherently wrong with your ajax function. You're just calling setInterval wrong:

setInterval(update_timestamps, 30000);

(notice the function reference to update_timestamps, not function call)

If you think hard, you will realize for yourself why what you did didn't work (hint: you're passing undefined to setInterval).


问:
Console.Logging Mapped Data in React
It appears I cannot console.log any selection from an onClick for this React component. I am trying to basically achieve the following.

https://codesandbox.io/s/great-ardinghelli-6seko?file=/src/demoComponent.jsx

The data is fetched from redux and appears in the frontend (I have this working).

I would like to achieve that when you select a line, it just console.logs('you have selected'role).

However it doesn't appear I can get ANY data to trigger on an onClick when it's a mapped data source.

I have implemented a p tag which fires and works as expected.

See the following refined code:

```<code>import React, { useRef } from "react";
import styled from "styled-components";

const SearchContent = styled.div`
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    padding: 1em;
    overflow-y: auto;
`;

const JobContainer = styled.div`
    width: 100%;
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    padding: 5px 5px;
`;

export function SearchBarTrialRedux(props) {

  const inputRef = useRef();
  const [term, setTerm] = useState("")

  const handleClickRole = () => {
      console.log("Hello, you have selected" )
  }

  const searchResults = useSelector(state => state.jobsearch.roles.map(role => role.title))

  const SearchResultsText = ({ text }) => {
      return (
          <JobContainer onClick={()=> {
              console.log("Hello")
          }}>
              <JobSearchTypography
              >
                  {text}
              </JobSearchTypography>
        </JobContainer>
      );
    };

  return (
          <SearchContent>
              <JobContainer >
                {searchResults && searchResults.length < 3 && searchResults.map((result) =>
                    (<IndividualContainer handleClick={handleClickRole}>
                        <SearchResultsText text={result}/>
                    </IndividualContainer>
                    )
                )}
              </JobContainer>
              <p onClick={handleClickRole}>
                fff
              </p>
         </SearchContent>
        )
</code>```

Does anyone know why this doesn't work + how to achieve the solution? I'm a little lost here!

答:
As it can be seen from your code snippet the handleClickRole function just prints to the console the message "Hello, you have selected". There is no variable passed on it in order to print it.
This can be changed like this:

```<code>const handleClickRole = (role) => {
  console.log(`Hello, you have selected ${role}`);
}
</code>```

Furthermore, the way you call the above function on the onClick event I think is incomplete. It would be better if it looked like this:

```<code><p onClick={() => handleClickRole(role)}>fff</p> // considering that you want to pass a variable with the role
</code>```

or

```<code><p onClick={() => handleClickRole()}>fff</p> // without a variable
</code>```

Please also look at the below example:

```<code>import { useState } from "react";

export default function App() {
  const [myInput, setMyInput] = useState("");
  const [isButtonClicked, setIsButtonClicked] = useState(false);
  const handleChange = (event) => {
    setIsButtonClicked(false);
    setMyInput(event.target.value);
  };
  const handleClick = () => {
    setIsButtonClicked(true);
    console.log(myInput);
  };

  return (
    <div className="App">
      <input
        onChange={handleChange}
        id=".myInput"
        placeHolder="Enter Something"
      />

      <button
        style={{
          display: "block",
          width: "100px",
          margin: "10px auto",
        }}
        onClick={() => handleClick()}
      >
        OK
      </button>

      <p style={{ fontWeight: "bold" }}>
        The entered value is:
        <span style={{ fontWeight: "400" }}>
          {isButtonClicked ? ` ${myInput}` : null}
        </span>
      </p>
    </div>
  );
}
</code>```

Title: Console.Logging Mapped Data in React

Body:
It appears I cannot console.log any selection from an onClick for this React component. I am trying to basically achieve the following.

https://codesandbox.io/s/great-ardinghelli-6seko?file=/src/demoComponent.jsx

The data is fetched from redux and appears in the frontend (I have this working).

I would like to achieve that when you select a line, it just console.logs('you have selected'role).

However it doesn't appear I can get ANY data to trigger on an onClick when it's a mapped data source.

I have implemented a p tag which fires and works as expected.

See the following refined code:

import React, { useRef } from "react";
import styled from "styled-components";

const SearchContent = styled.div`
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    padding: 1em;
    overflow-y: auto;
`;

const JobContainer = styled.div`
    width: 100%;
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    padding: 5px 5px;
`;

export function SearchBarTrialRedux(props) {

  const inputRef = useRef();
  const [term, setTerm] = useState("")

  const handleClickRole = () => {
      console.log("Hello, you have selected" )
  }

  const searchResults = useSelector(state => state.jobsearch.roles.map(role => role.title))

  const SearchResultsText = ({ text }) => {
      return (
          <JobContainer onClick={()=> {
              console.log("Hello")
          }}>
              <JobSearchTypography
              >
                  {text}
              </JobSearchTypography>
        </JobContainer>
      );
    };

  return (
          <SearchContent>
              <JobContainer >
                {searchResults && searchResults.length < 3 && searchResults.map((result) =>
                    (<IndividualContainer handleClick={handleClickRole}>
                        <SearchResultsText text={result}/>
                    </IndividualContainer>
                    )
                )}
              </JobContainer>

                fff

         </SearchContent>
        )

Does anyone know why this doesn't work + how to achieve the solution? I'm a little lost here!

Body:
As it can be seen from your code snippet the handleClickRole function just prints to the console the message "Hello, you have selected". There is no variable passed on it in order to print it.
This can be changed like this:

const handleClickRole = (role) => {
  console.log(`Hello, you have selected ${role}`);
}

Furthermore, the way you call the above function on the onClick event I think is incomplete. It would be better if it looked like this:

<p onClick={() => handleClickRole(role)}>fff</p> // considering that you want to pass a variable with the role

or

<p onClick={() => handleClickRole()}>fff</p> // without a variable

Please also look at the below example:

import { useState } from "react";

export default function App() {
  const [myInput, setMyInput] = useState("");
  const [isButtonClicked, setIsButtonClicked] = useState(false);
  const handleChange = (event) => {
    setIsButtonClicked(false);
    setMyInput(event.target.value);
  };
  const handleClick = () => {
    setIsButtonClicked(true);
    console.log(myInput);
  };

  return (
    <div className="App">
      <input
        onChange={handleChange}
        id=".myInput"
        placeHolder="Enter Something"
      />

      <button
        style={{
          display: "block",
          width: "100px",
          margin: "10px auto",
        }}
        onClick={() => handleClick()}
      >
        OK
      </button>

      <p style={{ fontWeight: "bold" }}>
        The entered value is:
        <span style={{ fontWeight: "400" }}>
          {isButtonClicked ? ` ${myInput}` : null}
        </span>
      </p>
    </div>
  );
}


问:
Add additional props to component in a foreach loop
i have a component in React that receives some elements (photos), i have a object with this composition:

```<code>getItems() {
    const { gallery } = this.props;
    const { content_elements: contentElements } = gallery;
    const items = [];

    if (contentElements) {
      contentElements.forEach((photo, index) => {
        let item = (
          <div key={photo.id} className="gal__fig-item">
            <Image
              srcset="gallery"
              figureClassName="mm"
              imgClassName="mm__img"
              noZoom={true}
              showCaption={false}
              wrapperClassName="mm__wr"
              {...photo}/>
          </div>
        );

        items.push(item);
      });
    }

    return items;
  }
</code>```

I need to add a prop in the image component, but only in the first element (index = 0).

I do this:

```<code>getItems() {
    const { gallery } = this.props;
    const { content_elements: contentElements } = gallery;
    const items = [];

    if (contentElements) {
      contentElements.forEach((photo, index) => {
        let item = (
          <div key={photo.id} className="gal__fig-item">
            <Image
              srcset="gallery"
              figureClassName="mm"
              imgClassName="mm__img"
              noZoom={true}
              showCaption={false}
              wrapperClassName="mm__wr"
              {...photo}/>
          </div>
        );
        if(index === 0){
           item = (
            <div key={photo.id} className="gal__fig-item">
              <Image
                srcset="gallery"
                figureClassName="mm"
                imgClassName="mm__img"
                noZoom={true}
                showCaption={false}
                hasLazyLoad={false}
                wrapperClassName="mm__wr"
                {...photo}/>
            </div>
          );
        }

        items.push(item);
      });
    }

    return items;
  }
</code>```

That works, but....maybe there is an other option, more clean code, to do it?
Someone can help me? Thanks

答:
you can set hasLazyLoad based on the value of i:

```<code> if (contentElements) {
      contentElements.forEach((photo, index) => {
        let item = (
            <div key={photo.id} className="gal__fig-item">
              <Image
                srcset="gallery"
                figureClassName="mm"
                imgClassName="mm__img"
                noZoom={true}
                showCaption={false}
                hasLazyLoad={i !== 0} // use i !== 0 to false when i = 0
                wrapperClassName="mm__wr"
                {...photo}/>
            </div>
          );
        }
    ```
```

Body:
i have a component in React that receives some elements (photos), i have a object with this composition:

getItems() {
    const { gallery } = this.props;
    const { content_elements: contentElements } = gallery;
    const items = [];

    if (contentElements) {
      contentElements.forEach((photo, index) => {
        let item = (

            <Image
              srcset="gallery"
              figureClassName="mm"
              imgClassName="mm__img"
              noZoom={true}
              showCaption={false}
              wrapperClassName="mm__wr"
              {...photo}/>

        );

        items.push(item);
      });
    }

    return items;
  }

I need to add a prop in the image component, but only in the first element (index = 0).

I do this:

getItems() {
    const { gallery } = this.props;
    const { content_elements: contentElements } = gallery;
    const items = [];

    if (contentElements) {
      contentElements.forEach((photo, index) => {
        let item = (

            <Image
              srcset="gallery"
              figureClassName="mm"
              imgClassName="mm__img"
              noZoom={true}
              showCaption={false}
              wrapperClassName="mm__wr"
              {...photo}/>

        );
        if(index === 0){
           item = (

              <Image
                srcset="gallery"
                figureClassName="mm"
                imgClassName="mm__img"
                noZoom={true}
                showCaption={false}
                hasLazyLoad={false}
                wrapperClassName="mm__wr"
                {...photo}/>

          );
        }

        items.push(item);
      });
    }

    return items;
  }

That works, but....maybe there is an other option, more clean code, to do it?
Someone can help me? Thanks

Body:
you can set hasLazyLoad based on the value of i:

 if (contentElements) {
      contentElements.forEach((photo, index) => {
        let item = (
            <div key={photo.id} className="gal__fig-item">
              <Image
                srcset="gallery"
                figureClassName="mm"
                imgClassName="mm__img"
                noZoom={true}
                showCaption={false}
                hasLazyLoad={i !== 0} // use i !== 0 to false when i = 0
                wrapperClassName="mm__wr"
                {...photo}/>
            </div>
          );
        }
    ```


答:
I would replace forEach to map and add ternary operator for hasLazoLoad prop:</p>
```<code>getItems() {
  const { gallery } = this.props;
  const { content_elements: contentElements } = gallery;

  const items = contentElements?.map((photo, index) => {
    return <div key={photo.id} className="gal__fig-item">
      <Image
        srcset="gallery"
        figureClassName="mm"
        imgClassName="mm__img"
        noZoom={true}
        showCaption={false}
        hasLazyLoad={index === 0 ? false : true}
        wrapperClassName="mm__wr"
        {...photo} />
    </div>
  }) || [];

  return items;
}
</code>```

Title: Add additional props to component in a foreach loop

Body:
I would replace forEach to map and add ternary operator for hasLazoLoad prop:

getItems() {
  const { gallery } = this.props;
  const { content_elements: contentElements } = gallery;

  const items = contentElements?.map((photo, index) => {
    return <div key={photo.id} className="gal__fig-item">
      <Image
        srcset="gallery"
        figureClassName="mm"
        imgClassName="mm__img"
        noZoom={true}
        showCaption={false}
        hasLazyLoad={index === 0 ? false : true}
        wrapperClassName="mm__wr"
        {...photo} />
    </div>
  }) || [];

  return items;
}


问:
Replace the element with the searched value in an array of objects in Javascript
Having the following array of objects:

```<code>const input = [ {id: 3, data: {name: 'john'} },
                {id: 6, data: {name: 'mike'} },
                {id: 2, data: {name: 'anna'} }
              ];
</code>```

I want to write a method that recevies a new object, if the object's id is in the array, it replaces that one with the new one, otherwise it creates a new object.

For example, if the method receives this object: {id: 1, data: {name: 'maria' }}, it will add it to the array, so the array will look like:

```<code>const input = [ {id: 3, data: {name: 'john'} },
                {id: 6, data: {name: 'mike'} },
                {id: 2, data: {name: 'anna'} },
                {id: 2, data: {name: 'maria'} }
              ];
</code>```

If it receives {id: 3, data: {name: 'jack' }} it should replace the object with id=3 so the result would be:

```<code>const input = [ {id: 3, data: {name: 'jack'} },
                {id: 6, data: {name: 'mike'} },
                {id: 2, data: {name: 'anna'} },
                {id: 2, data: {name: 'maria'} }
              ];
</code>```

The code:

```<code>function doMagic(input, newObj) {
  if (input.some(el => el.id === newObj.id) {
    // replace it
  } else {
    // add the object to the array
  }
}
</code>```

答:
It is possible to use find() to check whether it contains desired object.
And if array contains object, then we can update it throug Object.assign() method. If no, then we just push this item to array.

```<code>const oneFunction = (arr, objToEdit) => {
  let existingObject = arr.find(f => f.id === objToEdit.id
      && f.data.name !== objToEdit.name);

  if (existingObject)
    Object.assign(existingObject, objToEdit);
  else
    arr.push(objToEdit)

  return arr;
}
</code>```

An example:

const input =
[
  {id: 3, data: {name: 'john'} },
  {id: 6, data: {name: 'mike'} },
  {id: 2, data: {name: 'anna'} }
];

const oneFunction = (arr, objToEdit) => {
  let existingObject = arr.find(f => f.id === objToEdit.id && f.data.name !== objToEdit.name);

  if (existingObject)
    Object.assign(existingObject, objToEdit);
  else
    arr.push(objToEdit)

  return arr;
}

let testObject = {id: 3, data: {name: 'john1'}};
console.log(oneFunction(input, testObject))```

Body:
Having the following array of objects:

const input = [ {id: 3, data: {name: 'john'} },
                {id: 6, data: {name: 'mike'} },
                {id: 2, data: {name: 'anna'} }
              ];

I want to write a method that recevies a new object, if the object's id is in the array, it replaces that one with the new one, otherwise it creates a new object.

For example, if the method receives this object: {id: 1, data: {name: 'maria' }}, it will add it to the array, so the array will look like:

const input = [ {id: 3, data: {name: 'john'} },
                {id: 6, data: {name: 'mike'} },
                {id: 2, data: {name: 'anna'} },
                {id: 2, data: {name: 'maria'} }
              ];

If it receives {id: 3, data: {name: 'jack' }} it should replace the object with id=3 so the result would be:

const input = [ {id: 3, data: {name: 'jack'} },
                {id: 6, data: {name: 'mike'} },
                {id: 2, data: {name: 'anna'} },
                {id: 2, data: {name: 'maria'} }
              ];

The code:

function doMagic(input, newObj) {
  if (input.some(el => el.id === newObj.id) {
    // replace it
  } else {
    // add the object to the array
  }
}

Body:
It is possible to use find() to check whether it contains desired object.
And if array contains object, then we can update it throug Object.assign() method. If no, then we just push this item to array.

const oneFunction = (arr, objToEdit) => {
  let existingObject = arr.find(f => f.id === objToEdit.id
      && f.data.name !== objToEdit.name);

  if (existingObject)
    Object.assign(existingObject, objToEdit);
  else
    arr.push(objToEdit)

  return arr;
}

An example:

const input =
[
  {id: 3, data: {name: 'john'} },
  {id: 6, data: {name: 'mike'} },
  {id: 2, data: {name: 'anna'} }
];

const oneFunction = (arr, objToEdit) => {
  let existingObject = arr.find(f => f.id === objToEdit.id && f.data.name !== objToEdit.name);

  if (existingObject)
    Object.assign(existingObject, objToEdit);
  else
    arr.push(objToEdit)

  return arr;
}

let testObject = {id: 3, data: {name: 'john1'}};
console.log(oneFunction(input, testObject))


问:
rmic error class not found
I'm reading head first java and I'm about to try the ready baked codes that shows how to use RMI.
These are the classes:

The remote interface

```<code>import java.rmi.*;

public interface MyRemote extends Remote {

    public String sayHello() throws RemoteException;
}
</code>```

The remote implementation

```<code>import java.rmi.*;
import java.rmi.server.*;

public class MyRemoteImpl extends UnicastRemoteObject implements MyRemote {

    public String sayHello() {
        return "Server Says,Hello";
    }

    public MyRemoteImpl() throws RemoteException { }

    public static void main(String[] args) {

        try {
            MyRemote service = new MyRemoteImpl();
            Naming.rebind("Remote Hello", service);
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
}
</code>```

Then I placed the .java and the .class file in c:\RMI. When running it, it says MyRemoteImpl class not found even though I'm running from the same directory. How can i fix this? Thanks.

EDIT: The error appear when I try to run this command

```<code>rmic MyRemoteImpl
</code>```

答:
There is a path variable called CLASSPATH where the JVM will look for class files to excute when you try to run a class file.

CLASSPATH describes the location where all the required files are available which are used in the application.

Java Compiler and JVM (Java Virtual Machine) use CLASSPATH to locate the required files.

If the CLASSPATH is not set, Java Compiler will not be able to find the required files and hence will throw error.

If you don't know where your current path is, then type echo "%CLASSPATH%" in the command prompt.

Alternatively, you can also add/remove/edit the CLASSPATH variable in the Environmental Variables.

Make sure that you have added your Java to your path.

To add the current path where your .class files exists there are three ways.

Using Environmental variables - Reference

Using Command Prompt - set PATH = .

Specify the class path using -classpath argument while executing.

Semi-colon (;) is used as a separator and dot (.) is the default value of CLASSPATH while specifying the class path using -classpath argument.

```<code>rmic -classpath . <Class Name>
</code>```
```<code>rmic -classpath "C:\Example\Demo" <Class Name>
</code>```

Here . stands for the current directory and you can specify any path there.

Title: rmic error class not found

Body:
I'm reading head first java and I'm about to try the ready baked codes that shows how to use RMI.
These are the classes:

The remote interface

import java.rmi.*;

public interface MyRemote extends Remote {

    public String sayHello() throws RemoteException;
}

The remote implementation

import java.rmi.*;
import java.rmi.server.*;

public class MyRemoteImpl extends UnicastRemoteObject implements MyRemote {

    public String sayHello() {
        return "Server Says,Hello";
    }

    public MyRemoteImpl() throws RemoteException { }

    public static void main(String[] args) {

        try {
            MyRemote service = new MyRemoteImpl();
            Naming.rebind("Remote Hello", service);
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
}

Then I placed the .java and the .class file in c:\RMI. When running it, it says MyRemoteImpl class not found even though I'm running from the same directory. How can i fix this? Thanks.

EDIT: The error appear when I try to run this command

rmic MyRemoteImpl

Body:
There is a path variable called CLASSPATH where the JVM will look for class files to excute when you try to run a class file.

CLASSPATH describes the location where all the required files are available which are used in the application.

Java Compiler and JVM (Java Virtual Machine) use CLASSPATH to locate the required files.

If the CLASSPATH is not set, Java Compiler will not be able to find the required files and hence will throw error.

If you don't know where your current path is, then type echo "%CLASSPATH%" in the command prompt.

Alternatively, you can also add/remove/edit the CLASSPATH variable in the Environmental Variables.

Make sure that you have added your Java to your path.

To add the current path where your .class files exists there are three ways.

Using Environmental variables - Reference

Using Command Prompt - set PATH = .

Specify the class path using -classpath argument while executing.

Semi-colon (;) is used as a separator and dot (.) is the default value of CLASSPATH while specifying the class path using -classpath argument.

rmic -classpath . <Class Name>

rmic -classpath "C:\Example\Demo" <Class Name>

Here . stands for the current directory and you can specify any path there.


问:
how to save data into mongodb using express?
Trying to create signin and signup using express and MongoDB. In postman the data is perfectly passed but  couldn't save the data into mongoDB cluster.
IN this file connection to the db is created and also confused whether i am connected to the db or not in this file, I created schema for the user details to be provided

```<code>//Index.js

const express = require("express");
const mongoose = require("mongoose");
const app = express();
const dotenv = require("dotenv");

dotenv.config();

const db = process.env.DATABASE;

mongoose.connect(db, { useNewUrlParse: true }, () =>
  console.log("connected to db")
);

//midlewares
app.use(express.json());

//importing routes

const authRoute = require("./routes/auth");

//route middle wares
app.use("/api/user", authRoute);

app.listen(3000, () => console.log("gg server is running"));

//User.js

const mongoose = require("mongoose");

const { Schema } = mongoose;

const userSchema = new Schema({
  name: {
    type: String,
    max: 32,
    required: true,
    min: 6,
  },

  email: {
    type: String,
    required: true,
    max: 32,
  },
  password: {
    type: String,
    max: 1022,
    min: 8,
    required: true,
  },

  date: {
    type: Date,
    default: Date.now,
  },
});

module.exports = mongoose.model("User", userSchema);

//Auth.js

const router = require("express").Router();
const User = require("../model/User");

router.post("/register", (req, res) => {
  const user = new User({
    name: req.body.name,
    email: req.body.email,
    password: req.body.password,
  });

  const name = {
    name: req.body.name,
    email: req.body.email,
  };

  res.send(user);

  user.save();
});
module.exports = route[![enter image description here][1]][1]r;
</code>```

答:
Step 1

First, you should create a server after your MongoDB is connected. So, put your server logic inside mongoose.connect connect. This will assure that when yo u try to create a new user, MongoDB is already connected.

mongoose.connect(db, { useNewUrlParse: true }, () =>
  console.log("connected to db");

  //midlewares
  app.use(express.json());

  //importing routes

  const authRoute = require("./routes/auth");

  //route middle wares
  app.use("/api/user", authRoute);

  app.listen(3000, () => console.log("gg server is running"));
);
```
<h1>Step 2</h1>
<p>Use <code>create</code> method to create new user document:</p>
<pre class="lang-js prettyprint-override"><code>router.post("/register", async (req, res) => {
  const user = await User.create({
    name: req.body.name,
    email: req.body.email,
    password: req.body.password,
  });

  return res.status(200).json(user);
});
</code>```

Body:
Trying to create signin and signup using express and MongoDB. In postman the data is perfectly passed but  couldn't save the data into mongoDB cluster.
IN this file connection to the db is created and also confused whether i am connected to the db or not in this file, I created schema for the user details to be provided

//Index.js

const express = require("express");
const mongoose = require("mongoose");
const app = express();
const dotenv = require("dotenv");

dotenv.config();

const db = process.env.DATABASE;

mongoose.connect(db, { useNewUrlParse: true }, () =>
  console.log("connected to db")
);

//midlewares
app.use(express.json());

//importing routes

const authRoute = require("./routes/auth");

//route middle wares
app.use("/api/user", authRoute);

app.listen(3000, () => console.log("gg server is running"));

//User.js

const mongoose = require("mongoose");

const { Schema } = mongoose;

const userSchema = new Schema({
  name: {
    type: String,
    max: 32,
    required: true,
    min: 6,
  },

  email: {
    type: String,
    required: true,
    max: 32,
  },
  password: {
    type: String,
    max: 1022,
    min: 8,
    required: true,
  },

  date: {
    type: Date,
    default: Date.now,
  },
});

module.exports = mongoose.model("User", userSchema);

//Auth.js

const router = require("express").Router();
const User = require("../model/User");

router.post("/register", (req, res) => {
  const user = new User({
    name: req.body.name,
    email: req.body.email,
    password: req.body.password,
  });

  const name = {
    name: req.body.name,
    email: req.body.email,
  };

  res.send(user);

  user.save();
});
module.exports = route[![enter image description here][1]][1]r;

Body:
Step 1

First, you should create a server after your MongoDB is connected. So, put your server logic inside mongoose.connect connect. This will assure that when yo u try to create a new user, MongoDB is already connected.

mongoose.connect(db, { useNewUrlParse: true }, () =>
  console.log("connected to db");

  //midlewares
  app.use(express.json());

  //importing routes

  const authRoute = require("./routes/auth");

  //route middle wares
  app.use("/api/user", authRoute);

  app.listen(3000, () => console.log("gg server is running"));
);

Step 2

Use create method to create new user document:

router.post("/register", async (req, res) => {
  const user = await User.create({
    name: req.body.name,
    email: req.body.email,
    password: req.body.password,
  });

  return res.status(200).json(user);
});


问:
FormView is completely hidden when there are no records
I have a simple FormView in a ASP.Net application. However when there are no records in the datasource, the control completely hides itself. I need to be able to have the end user add the first record view the FormView. Is there any way around this behavior?</p>

答:
You can use EmptyDataTemplate to show the formView when no data is available.

http://msdn2.microsoft.com/us-en/system.web.ui.webcontrols.formview.emptydatatemplate(VS.80).aspx


问:
H2 Database result set is readonly
I'm getting the SQLNonTransientException error when trying to update one of my rows in a H2 database.

```<code>public static void setNewServiceInformationsToShown() {
    try (Connection conn = DriverManager.getConnection("jdbc:h2:" + Main.config_db_location,
            Main.config_db_username, Main.config_db_password)) {
        //read data from database
        PreparedStatement stmt = conn.prepareStatement("SELECT * FROM BCSTASKS_SERVICE");

        ResultSet rs = stmt.executeQuery();
        while (rs.next()) {
            if(rs.getString("Status").equals("Neu") && rs.getBoolean("wasShown") == false) {
                rs.updateBoolean("WASSHOWN", true);
            }
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
}
</code>```

The error message already suggests that I should use conn.createStatement and set the ResultSet to CONCUR_UPDATABLE. The error occurs at the line with rs.updateBoolean(...);

Error Message:

The result set is readonly. You may need to use conn.createStatement(.., ResultSet.CONCUR_UPDATABLE). [90140-210]

The problem is I don't know where and how I should use this method. In the same function or at the start of the program?

答:
You need to create a separate query/prepareStatement for an update. In your case as far as I can see you need only one update query:</p>
```<code>conn.prepareStatement("UPDATE BCSTASKS_SERVICE SET WASSHOWN=true where
                       Status = 'Neu' and wasShown = false "
</code>```

Title: H2 Database result set is readonly

Body:
I'm getting the SQLNonTransientException error when trying to update one of my rows in a H2 database.

public static void setNewServiceInformationsToShown() {
    try (Connection conn = DriverManager.getConnection("jdbc:h2:" + Main.config_db_location,
            Main.config_db_username, Main.config_db_password)) {
        //read data from database
        PreparedStatement stmt = conn.prepareStatement("SELECT * FROM BCSTASKS_SERVICE");

        ResultSet rs = stmt.executeQuery();
        while (rs.next()) {
            if(rs.getString("Status").equals("Neu") && rs.getBoolean("wasShown") == false) {
                rs.updateBoolean("WASSHOWN", true);
            }
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

The error message already suggests that I should use conn.createStatement and set the ResultSet to CONCUR_UPDATABLE. The error occurs at the line with rs.updateBoolean(...);

Error Message:

The result set is readonly. You may need to use conn.createStatement(.., ResultSet.CONCUR_UPDATABLE). [90140-210]

The problem is I don't know where and how I should use this method. In the same function or at the start of the program?

Body:
You need to create a separate query/prepareStatement for an update. In your case as far as I can see you need only one update query:

conn.prepareStatement("UPDATE BCSTASKS_SERVICE SET WASSHOWN=true where
                       Status = 'Neu' and wasShown = false "


问:
Publish Python Package via GitHub Actions to AWS CodeArtifact
I have a hard time to publish a package to AWS CodeArtifact. Problem is the authentification.

First I tried to execute the login via the aws cli but due to the lack of the .pypirc file containing the repository settings that didn't work out. Now I tried to store the token and feed it into the --repository-url but in both cases I end up that the process wants a username anyway.

Stacktrace:

```<code>File "/opt/hostedtoolcache/Python/3.9.1/x64/bin/twine", line 8, in <module>
    sys.exit(main())
  File "/opt/hostedtoolcache/Python/3.9.1/x64/lib/python3.9/site-packages/twine/__main__.py", line 28, in main
    result = cli.dispatch(sys.argv[1:])
  File "/opt/hostedtoolcache/Python/3.9.1/x64/lib/python3.9/site-packages/twine/cli.py", line 82, in dispatch
    return main(args.args)
  File "/opt/hostedtoolcache/Python/3.9.1/x64/lib/python3.9/site-packages/twine/commands/upload.py", line 154, in main
    return upload(upload_settings, parsed_args.dists)
  File "/opt/hostedtoolcache/Python/3.9.1/x64/lib/python3.9/site-packages/twine/commands/upload.py", line 91, in upload
    repository = upload_settings.create_repository()
  File "/opt/hostedtoolcache/Python/3.9.1/x64/lib/python3.9/site-packages/twine/settings.py", line 345, in create_repository
    self.username,
  File "/opt/hostedtoolcache/Python/3.9.1/x64/lib/python3.9/site-packages/twine/settings.py", line 146, in username
    return cast(Optional[str], self.auth.username)
  File "/opt/hostedtoolcache/Python/3.9.1/x64/lib/python3.9/site-packages/twine/auth.py", line 35, in username
    return utils.get_userpass_value(
  File "/opt/hostedtoolcache/Python/3.9.1/x64/lib/python3.9/site-packages/twine/utils.py", line 241, in get_userpass_value
    return prompt_strategy()
  File "/opt/hostedtoolcache/Python/3.9.1/x64/lib/python3.9/site-packages/twine/auth.py", line 81, in username_from_keyring_or_prompt
    return self.prompt("username", input)
  File "/opt/hostedtoolcache/Python/3.9.1/x64/lib/python3.9/site-packages/twine/auth.py", line 92, in prompt
    return how(f"Enter your {what}: ")
EOFError: EOF when reading a line
Enter your username:
Error: Process completed with exit code 1.
</code>```

Partial github-action.yml:

```<code>steps:
    - uses: actions/checkout@v2
    - name: Set up Python
      uses: actions/setup-python@v2
      with:
        python-version: '3.x'
    - name: Install dependencies
      run: |
        python -m pip install --upgrade pip
        pip install setuptools wheel twine

    - name: Configure AWS Credentials
      uses: aws-actions/configure-aws-credentials@v1
      with:
        aws-access-key-id: ${{ secrets.AWS_CA_ACCESS_KEY_ID }}
        aws-secret-access-key: ${{ secrets.AWS_CA_SECRET_ACCESS_KEY }}
        aws-region: eu-central-1

    - name: Build and publish
      run: |
        token=$(aws codeartifact get-authorization-token --domain foobar --domain-owner 123456678901 --query authorizationToken --output text)
        python setup.py sdist bdist_wheel
        twine upload --repository-url https://aws:$token@foobar-123456678901.d.codeartifact.eu-central-1.amazonaws.com/pypi/my-repo/simple dist/*
</code>```

答:
The AWS CLI lets you configure credentials for twine so you don't have to pass them explicitly.

    - name: Build and publish
      run: |
        aws codeartifact login --tool twine --domain foobar --repository my-repo
        python setup.py sdist bdist_wheel
        twine upload --repository codeartifact dist/*
```

Links:

https://docs.aws.amazon.com/codeartifact/latest/ug/python-configure.html

https://docs.aws.amazon.com/codeartifact/latest/ug/python-run-twine.html

Body:
I have a hard time to publish a package to AWS CodeArtifact. Problem is the authentification.

First I tried to execute the login via the aws cli but due to the lack of the .pypirc file containing the repository settings that didn't work out. Now I tried to store the token and feed it into the --repository-url but in both cases I end up that the process wants a username anyway.

Stacktrace:

File "/opt/hostedtoolcache/Python/3.9.1/x64/bin/twine", line 8, in <module>
    sys.exit(main())
  File "/opt/hostedtoolcache/Python/3.9.1/x64/lib/python3.9/site-packages/twine/__main__.py", line 28, in main
    result = cli.dispatch(sys.argv[1:])
  File "/opt/hostedtoolcache/Python/3.9.1/x64/lib/python3.9/site-packages/twine/cli.py", line 82, in dispatch
    return main(args.args)
  File "/opt/hostedtoolcache/Python/3.9.1/x64/lib/python3.9/site-packages/twine/commands/upload.py", line 154, in main
    return upload(upload_settings, parsed_args.dists)
  File "/opt/hostedtoolcache/Python/3.9.1/x64/lib/python3.9/site-packages/twine/commands/upload.py", line 91, in upload
    repository = upload_settings.create_repository()
  File "/opt/hostedtoolcache/Python/3.9.1/x64/lib/python3.9/site-packages/twine/settings.py", line 345, in create_repository
    self.username,
  File "/opt/hostedtoolcache/Python/3.9.1/x64/lib/python3.9/site-packages/twine/settings.py", line 146, in username
    return cast(Optional[str], self.auth.username)
  File "/opt/hostedtoolcache/Python/3.9.1/x64/lib/python3.9/site-packages/twine/auth.py", line 35, in username
    return utils.get_userpass_value(
  File "/opt/hostedtoolcache/Python/3.9.1/x64/lib/python3.9/site-packages/twine/utils.py", line 241, in get_userpass_value
    return prompt_strategy()
  File "/opt/hostedtoolcache/Python/3.9.1/x64/lib/python3.9/site-packages/twine/auth.py", line 81, in username_from_keyring_or_prompt
    return self.prompt("username", input)
  File "/opt/hostedtoolcache/Python/3.9.1/x64/lib/python3.9/site-packages/twine/auth.py", line 92, in prompt
    return how(f"Enter your {what}: ")
EOFError: EOF when reading a line
Enter your username:
Error: Process completed with exit code 1.

Partial github-action.yml:

steps:
    - uses: actions/checkout@v2
    - name: Set up Python
      uses: actions/setup-python@v2
      with:
        python-version: '3.x'
    - name: Install dependencies
      run: |
        python -m pip install --upgrade pip
        pip install setuptools wheel twine

    - name: Configure AWS Credentials
      uses: aws-actions/configure-aws-credentials@v1
      with:
        aws-access-key-id: ${{ secrets.AWS_CA_ACCESS_KEY_ID }}
        aws-secret-access-key: ${{ secrets.AWS_CA_SECRET_ACCESS_KEY }}
        aws-region: eu-central-1

    - name: Build and publish
      run: |
        token=$(aws codeartifact get-authorization-token --domain foobar --domain-owner 123456678901 --query authorizationToken --output text)
        python setup.py sdist bdist_wheel
        twine upload --repository-url https://aws:$token@foobar-123456678901.d.codeartifact.eu-central-1.amazonaws.com/pypi/my-repo/simple dist/*

Body:
The AWS CLI lets you configure credentials for twine so you don't have to pass them explicitly.

    - name: Build and publish
      run: |
        aws codeartifact login --tool twine --domain foobar --repository my-repo
        python setup.py sdist bdist_wheel
        twine upload --repository codeartifact dist/*

Links:

https://docs.aws.amazon.com/codeartifact/latest/ug/python-configure.html

https://docs.aws.amazon.com/codeartifact/latest/ug/python-run-twine.html


问:
Create an Outlook Archive with Powershell
I have to create archive (.pst file) for mailbox in Outlook. I use an exchange server 2016.
If i do the "microsoft way" (https://support.microsoft.com/en-us/office/archive-items-manually-ecf54f37-14d7-4ee3-a830-46a5c33274f6)
i always find mails that aren't transfert to the archive.
Cached Exchange Mode are turn off.

I wish to find a way with powershell to access Outlook and the mail box.
I want to copy all folders and subfolders name, their hierarchy, to create them on my archive.pst

Then, i want to find all mail prior to a specific date, and copy each mail on the right folder.

Thank to the post here : Powershell - Read and Move mails to archive folder
the function "Get-OutlookInBox" could give me mails, but only it seems on Inbox, not the others folders.

Can anyone tell me how to do this ?

Thank in advance

答:
Posts you are referring to use PowerShell scripts that automate Outlook. The OOM has access to the local data only.

Instead, you can use EWS, see Explore the EWS Managed API, EWS, and web services in Exchange for more information. But EWS is discontinued, so now Graph API is the best and valid approach for that, read more about that in the Outlook mail API overview article.

Then, i want to find all mail prior to a specific date, and copy each mail on the right folder.

Here you are free to use a powershell script which searches for items that correspond to your conditions. The Find/FindNext or Restrict methods can help with such tasks in Outlook:

How To: Use Find and FindNext methods to retrieve Outlook mail items from a folder (C#, VB.NET)

How To: Use Restrict method to retrieve Outlook mail items from a folder


问:
making the transformed layer as normal state in ios
Hi all i am trying to use CATransform3D in my project.i seen some code snippet for transforming a layer  that is shown below.my question is after transforming the layer with below code how to get layer in the normal dimensions which means same as before transforming of the layer

```<code> -(IBAction)animateThumbnail{
CATransform3D rotationAndPerspectiveTransform = CATransform3DIdentity;
rotationAndPerspectiveTransform.m34 = 1.0 / -500;
rotationAndPerspectiveTransform = CATransform3DRotate(rotationAndPerspectiveTransform,30.0f * M_PI / 180.0f , 0.0f, 1.0f, 0.0f);

[CATransaction begin];
[CATransaction setValue:[NSNumber numberWithFloat:3.0]forKey:kCATransactionAnimationDuration];
imageLayer.transform = rotationAndPerspectiveTransform;
[CATransaction commit];
}
</code>```

can any one please post your way of transformation to get my layer should be in the normal state.
Thank you in advance.

答: You could use +[CATransaction setCompletionBlock:] and set the transform to CATransform3DIdentity. Or, you could use a CAPropertyAnimation and set autoreverses to YES.

Body:
Hi all i am trying to use CATransform3D in my project.i seen some code snippet for transforming a layer  that is shown below.my question is after transforming the layer with below code how to get layer in the normal dimensions which means same as before transforming of the layer

 -(IBAction)animateThumbnail{
CATransform3D rotationAndPerspectiveTransform = CATransform3DIdentity;
rotationAndPerspectiveTransform.m34 = 1.0 / -500;
rotationAndPerspectiveTransform = CATransform3DRotate(rotationAndPerspectiveTransform,30.0f * M_PI / 180.0f , 0.0f, 1.0f, 0.0f);

[CATransaction begin];
[CATransaction setValue:[NSNumber numberWithFloat:3.0]forKey:kCATransactionAnimationDuration];
imageLayer.transform = rotationAndPerspectiveTransform;
[CATransaction commit];
}

can any one please post your way of transformation to get my layer should be in the normal state.
Thank you in advance.


答:
I suggest this :

if index was zero then hasLazyload will be false and vise versa

```<code>getItems() {
        const { gallery } = this.props;
        const { content_elements: contentElements } = gallery;
        const items = [];

        if (contentElements) {
          contentElements.forEach((photo, index) => {
            let item = (
              <div key={photo.id} className="gal__fig-item">
                <Image
                  srcset="gallery"
                  figureClassName="mm"
                  imgClassName="mm__img"
                  noZoom={true}
                  showCaption={false}
                  hasLazyLoad = {index !== 0}
                  wrapperClassName="mm__wr"
                  {...photo}/>
              </div>
            );

            items.push(item);
          });
        }

        return items;
      }
</code>```

Body:
I suggest this :

if index was zero then hasLazyload will be false and vise versa

getItems() {
        const { gallery } = this.props;
        const { content_elements: contentElements } = gallery;
        const items = [];

        if (contentElements) {
          contentElements.forEach((photo, index) => {
            let item = (
              <div key={photo.id} className="gal__fig-item">
                <Image
                  srcset="gallery"
                  figureClassName="mm"
                  imgClassName="mm__img"
                  noZoom={true}
                  showCaption={false}
                  hasLazyLoad = {index !== 0}
                  wrapperClassName="mm__wr"
                  {...photo}/>
              </div>
            );

            items.push(item);
          });
        }

        return items;
      }


问:
How to convert two vectors into dataframe (wide format)
I want to convert two vectors into a wide format dataframe. The fist vector represent the column names and the second vector the values.
Here is my reproduceable example:

```<code>vector1<-c("Reply","Reshare","Like","Share","Search")
vector2<-c(2,1,0,4,3)
</code>```

Now I want to convert these two vector into a wide format dataframe:

```<code># A tibble: 1 x 5
   Reply Reshare  Like Share Search
   <dbl>   <dbl> <dbl> <dbl>  <dbl>
1     2       1     0     4      3
</code>```

I have found some examples for the long format, but none simple solution for the wide format. Can anyone help me?

答:
Yet another solution, based on dplyr::bind_rows:

library(dplyr)

vector1<-c("Reply","Reshare","Like","Share","Search")
vector2<-c(2,1,0,4,3)

names(vector2) <- vector1
bind_rows(vector2)

#> # A tibble: 1 × 5
#>   Reply Reshare  Like Share Search
#>   <dbl>   <dbl> <dbl> <dbl>  <dbl>
#> 1     2       1     0     4      3
```

Body:
I want to convert two vectors into a wide format dataframe. The fist vector represent the column names and the second vector the values.
Here is my reproduceable example:

vector1<-c("Reply","Reshare","Like","Share","Search")
vector2<-c(2,1,0,4,3)

Now I want to convert these two vector into a wide format dataframe:

# A tibble: 1 x 5
   Reply Reshare  Like Share Search
   <dbl>   <dbl> <dbl> <dbl>  <dbl>
1     2       1     0     4      3

I have found some examples for the long format, but none simple solution for the wide format. Can anyone help me?


问:
How to corrently use UIViews systemLayoutSizeFitting to get the height to show all subviews using a given width?
TD;DR

It seems that in some cases systemLayoutSizeFitting does not return the correct height to correctly show / position all subviews of a view. Am I using systemLayoutSizeFitting wrong or is there some other way to avoid this?

Long story:

The XIB file of a UIViewController does not only contain the main view but also a number of other views which are added to the view controllers view at runtime. All these additional views should get the same height when they are added to the view controllers view.

The views might look like this: A simple container view holding some subviews which are stacked on top of each other.

Since the height of the container view should be flexible, the vertical spacing between the bottom button and the lable above it, uses a grater-than constraint.

To give all views the same height, I tried to measure the necessary height of each view using systemLayoutSizeFitting:

```<code>@IBOutlet var pageViews: [UIView]!

override func viewDidLoad() {
    super.viewDidLoad()

    var maxHeight: CGFloat = 0
    for pageView in pageViews {
        // Add pageView somewhere on view and give it leading, trailing and top
        // constraint, but no height constraint yet.
        addToView(pageView)

        maxHeight = max(maxHeight, pageView.systemLayoutSizeFitting(CGSize(width: view.frame.width, height: UIView.layoutFittingCompressedSize.height), withHorizontalFittingPriority: .required, verticalFittingPriority: .fittingSizeLevel).height)
    }

    for pageView in pageViews {
        // Give all pageViews the same height
        pageView.heightAnchor.constraint(equalToConstant: maxHeight).isActive = true
    }
}
</code>```

This does not work, when the label text becomes to long:

In the right example the height is not large enough and thus the button is squeezed. I can counter act this by raising the vertical compression resistance of the button, however in this case the other controls (e.g. the title label) is squeezed...

Why is this? Why does not systemLayoutSizeFitting return a height which is sufficent to show all controls without any squeezing?

答:
Its actually smash button's height when label text is getting bigger . You are setting top and bottom constraints but button height is not declared so when label getting bigger , view basically say "I can reduce button height before updating my height , I have space.Bottom and top constraints are still same , didn't effect."

Giving the constant height constraints of button might be fix your issue.

Body:
TD;DR

It seems that in some cases systemLayoutSizeFitting does not return the correct height to correctly show / position all subviews of a view. Am I using systemLayoutSizeFitting wrong or is there some other way to avoid this?

Long story:

The XIB file of a UIViewController does not only contain the main view but also a number of other views which are added to the view controllers view at runtime. All these additional views should get the same height when they are added to the view controllers view.

The views might look like this: A simple container view holding some subviews which are stacked on top of each other.

Since the height of the container view should be flexible, the vertical spacing between the bottom button and the lable above it, uses a grater-than constraint.

To give all views the same height, I tried to measure the necessary height of each view using systemLayoutSizeFitting:

@IBOutlet var pageViews: [UIView]!

override func viewDidLoad() {
    super.viewDidLoad()

    var maxHeight: CGFloat = 0
    for pageView in pageViews {
        // Add pageView somewhere on view and give it leading, trailing and top
        // constraint, but no height constraint yet.
        addToView(pageView)

        maxHeight = max(maxHeight, pageView.systemLayoutSizeFitting(CGSize(width: view.frame.width, height: UIView.layoutFittingCompressedSize.height), withHorizontalFittingPriority: .required, verticalFittingPriority: .fittingSizeLevel).height)
    }

    for pageView in pageViews {
        // Give all pageViews the same height
        pageView.heightAnchor.constraint(equalToConstant: maxHeight).isActive = true
    }
}

This does not work, when the label text becomes to long:

In the right example the height is not large enough and thus the button is squeezed. I can counter act this by raising the vertical compression resistance of the button, however in this case the other controls (e.g. the title label) is squeezed...

Why is this? Why does not systemLayoutSizeFitting return a height which is sufficent to show all controls without any squeezing?


问:
Servicestack redirect to metadata
i've the following problem: i've a web service application that uses ServiceStack. I'd like to register as base path "/api", but even if I set DefaultRedirectPath to "/api/metadata", when i start the app it won't redirect automatically (if i type "/api/metadata" all works)
Can anyone help me?
Here's my code inside AppHost

```<code>public override void Configure(Container container)
{
     SetConfig(new HostConfig
     {
         DefaultRedirectPath = "/api/metadata"
     });
}

public class Startup
{
    public IConfiguration Configuration { get; }

    public Startup()
    {
        Configuration = new ConfigurationBuilder()
          .AddJsonFile("appsettings.json")
          .Build();
    }

    public void ConfigureServices(IServiceCollection services)
    {

    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseServiceStack(new AppHost
        {
            PathBase = "/api",
            AppSettings = new NetCoreAppSettings(Configuration)
        });
    }
}
</code>```

Thanks in advance and sorry for my english

答:
Firstly I'd consider not using an /api PathBase which would disable the new /api route. E.g. if you didn't have a /api PathBase you would automatically be able to call a Hello API from /api/Hello.

But if you you still want to host ServiceStack at a custom /api path know that this is the path that ServiceStack will be mounted at, i.e. from where ServiceStack will be able to receive any requests.

Which also means you should just use /metadata which will redirect from where ServiceStack is mounted at, so if you had:

public class AppHost : AppHostBase
{
    public AppHost() : base("MyApp", typeof(MyServices).Assembly) {}

    public override void Configure(Container container)
    {
        SetConfig(new HostConfig {
            DefaultRedirectPath = "/metadata"
        });
    }
}
```
<p>Then calling <code>https://localhost:5001/api</code> will redirect to <code>https://localhost:5001/api/metadata</code>.</p>
<p>ServiceStack can only see requests from <code>/api</code> where it's mounted at, so if you wanted to redirect the <code>/</code> route to the metadata page you would need to register a custom ASP.NET Core handler to do it, e.g:</p>
<pre class="lang-cs prettyprint-override"><code>public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseServiceStack(new AppHost {
        PathBase = "/api",
    });

    app.UseRouting();

    app.UseEndpoints(endpoints => {
        endpoints.MapGet("/", async context =>
            context.Response.Redirect("/api/metadata"));
    });
}
</code>```

Note: you no longer need to set NetCoreAppSettings() which is populated by default

Title: Servicestack redirect to metadata

Body:
i've the following problem: i've a web service application that uses ServiceStack. I'd like to register as base path "/api", but even if I set DefaultRedirectPath to "/api/metadata", when i start the app it won't redirect automatically (if i type "/api/metadata" all works)
Can anyone help me?
Here's my code inside AppHost

public override void Configure(Container container)
{
     SetConfig(new HostConfig
     {
         DefaultRedirectPath = "/api/metadata"
     });
}

public class Startup
{
    public IConfiguration Configuration { get; }

    public Startup()
    {
        Configuration = new ConfigurationBuilder()
          .AddJsonFile("appsettings.json")
          .Build();
    }

    public void ConfigureServices(IServiceCollection services)
    {

    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseServiceStack(new AppHost
        {
            PathBase = "/api",
            AppSettings = new NetCoreAppSettings(Configuration)
        });
    }
}

Thanks in advance and sorry for my english

Body:
Firstly I'd consider not using an /api PathBase which would disable the new /api route. E.g. if you didn't have a /api PathBase you would automatically be able to call a Hello API from /api/Hello.

But if you you still want to host ServiceStack at a custom /api path know that this is the path that ServiceStack will be mounted at, i.e. from where ServiceStack will be able to receive any requests.

Which also means you should just use /metadata which will redirect from where ServiceStack is mounted at, so if you had:

public class AppHost : AppHostBase
{
    public AppHost() : base("MyApp", typeof(MyServices).Assembly) {}

    public override void Configure(Container container)
    {
        SetConfig(new HostConfig {
            DefaultRedirectPath = "/metadata"
        });
    }
}

Then calling https://localhost:5001/api will redirect to https://localhost:5001/api/metadata.

ServiceStack can only see requests from /api where it's mounted at, so if you wanted to redirect the / route to the metadata page you would need to register a custom ASP.NET Core handler to do it, e.g:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseServiceStack(new AppHost {
        PathBase = "/api",
    });

    app.UseRouting();

    app.UseEndpoints(endpoints => {
        endpoints.MapGet("/", async context =>
            context.Response.Redirect("/api/metadata"));
    });
}

Note: you no longer need to set NetCoreAppSettings() which is populated by default


问:
Tuple splitting with dictionaries
This is the dictionary that I currently have.

```<code>d={'art1':{'poll1':{'v':10, 'i':9, 'r':9/10, 'prob': 0.9},'poll2':{'v':8, 'i':3, 'r':3/8, 'prob': 0.1}},
   'art2':{'poll1':{'v':11, 'i':4, 'r':4/11, 'prob': 0.4},'poll2':{'v':4, 'i':2, 'r':2/4, 'prob': 0.6}}
  }
</code>```

And the output that I am looking for is the following:

```<code>{'art1': {'poll1': {'v': 10,
   'i': 9,
   'r': 0.9,
   'prob': 0.9,
   'position': (0, 0.9)},
  'poll2': {'v': 8, 'i': 3, 'r': 0.375, 'prob': 0.1, 'position': (0.9, 1.0)}},
 'art2': {'poll1': {'v': 11,
   'i': 4,
   'r': 0.36363636363636365,
   'prob': 0.4,
   'position': (0, 0.4)},
  'poll2': {'v': 4, 'i': 2, 'r': 0.5, 'prob': 0.6, 'position': (0.4, 0.6)}}}
</code>```

I basically want the position to be an interval where we add their probabilities (prob).

I was able to come up with this chunk of code, but the position from poll2 does not start with the probability at the end of poll1 position.

```<code>for article, v in d.items():
    a=0
    print(d[article])
    print(v)
    for k,values in v.items():
        a+=values['prob']
        if k=='poll1':
            values['position']=(0,values['prob'])
        else:
            values['position']=(a,a+values['prob'])
</code>```

The output for this is:

```<code>{'art1': {'poll1': {'v': 10,
   'i': 9,
   'r': 0.9,
   'prob': 0.9,
   'position': (0, 0.9)},
  'poll2': {'v': 8, 'i': 3, 'r': 0.375, 'prob': 0.1, 'position': (1.0, 1.1)}},
 'art2': {'poll1': {'v': 11,
   'i': 4,
   'r': 0.36363636363636365,
   'prob': 0.4,
   'position': (0, 0.4)},
  'poll2': {'v': 4, 'i': 2, 'r': 0.5, 'prob': 0.6, 'position': (1.0, 1.6)}}}
</code>```

I was hoping to be able to do this with multiple polls, so I would really appreciate if it was a generalized answer. Thank you so much for your help, and if you have any other question or if what I explained isn't clear please let me know.

答:
Iterate over arts.

For each art create index_prob = 0

Then iterate over polls in this art and add prob to index_probs while also adding position key-value to poll values

```<code>for art, polls in d.items():
    index_prob = 0
    for poll, value in polls.items():
        value['position'] = (index_prob, index_prob + value['prob'])
        index_prob += value['prob']
</code>```

Title: Tuple splitting with dictionaries

Body:
This is the dictionary that I currently have.

d={'art1':{'poll1':{'v':10, 'i':9, 'r':9/10, 'prob': 0.9},'poll2':{'v':8, 'i':3, 'r':3/8, 'prob': 0.1}},
   'art2':{'poll1':{'v':11, 'i':4, 'r':4/11, 'prob': 0.4},'poll2':{'v':4, 'i':2, 'r':2/4, 'prob': 0.6}}
  }

And the output that I am looking for is the following:

{'art1': {'poll1': {'v': 10,
   'i': 9,
   'r': 0.9,
   'prob': 0.9,
   'position': (0, 0.9)},
  'poll2': {'v': 8, 'i': 3, 'r': 0.375, 'prob': 0.1, 'position': (0.9, 1.0)}},
 'art2': {'poll1': {'v': 11,
   'i': 4,
   'r': 0.36363636363636365,
   'prob': 0.4,
   'position': (0, 0.4)},
  'poll2': {'v': 4, 'i': 2, 'r': 0.5, 'prob': 0.6, 'position': (0.4, 0.6)}}}

I basically want the position to be an interval where we add their probabilities (prob).

I was able to come up with this chunk of code, but the position from poll2 does not start with the probability at the end of poll1 position.

for article, v in d.items():
    a=0
    print(d[article])
    print(v)
    for k,values in v.items():
        a+=values['prob']
        if k=='poll1':
            values['position']=(0,values['prob'])
        else:
            values['position']=(a,a+values['prob'])

The output for this is:

{'art1': {'poll1': {'v': 10,
   'i': 9,
   'r': 0.9,
   'prob': 0.9,
   'position': (0, 0.9)},
  'poll2': {'v': 8, 'i': 3, 'r': 0.375, 'prob': 0.1, 'position': (1.0, 1.1)}},
 'art2': {'poll1': {'v': 11,
   'i': 4,
   'r': 0.36363636363636365,
   'prob': 0.4,
   'position': (0, 0.4)},
  'poll2': {'v': 4, 'i': 2, 'r': 0.5, 'prob': 0.6, 'position': (1.0, 1.6)}}}

I was hoping to be able to do this with multiple polls, so I would really appreciate if it was a generalized answer. Thank you so much for your help, and if you have any other question or if what I explained isn't clear please let me know.

Body:
Iterate over arts.

For each art create index_prob = 0

Then iterate over polls in this art and add prob to index_probs while also adding position key-value to poll values

for art, polls in d.items():
    index_prob = 0
    for poll, value in polls.items():
        value['position'] = (index_prob, index_prob + value['prob'])
        index_prob += value['prob']


问:
Defining a match-case statement with the same instruction for two different cases in Python
I would like to create a match-case statement in Python in which two cases do the same instruction. For instance, if Python behaved like C++, according to this Stack Overflow question, I would write the match-case statement as:

```<code>        match x:
            case 1:
            case 2:
                # Some code
                break
            case 3:
                # Some code
                break
</code>```

The code however does not work, showing that the match-case statement needs to be written in a different way in Python. What is this way?

答:
```<code>match x:
    case 1 | 2:
        # Some code
    case 3:
        # Some code
</code>```

Python match clauses don't fall through, so you can't concatenate them as in C and you don't use break at the end of the clause.

The "OR pattern" (as shown, where | means "or") can be used with subpatterns which bind variables, but all the subpatterns need to bind the same variables.

Body:
I would like to create a match-case statement in Python in which two cases do the same instruction. For instance, if Python behaved like C++, according to this Stack Overflow question, I would write the match-case statement as:

        match x:
            case 1:
            case 2:
                # Some code
                break
            case 3:
                # Some code
                break

The code however does not work, showing that the match-case statement needs to be written in a different way in Python. What is this way?

Body:
match x:
    case 1 | 2:
        # Some code
    case 3:
        # Some code

Python match clauses don't fall through, so you can't concatenate them as in C and you don't use break at the end of the clause.

The "OR pattern" (as shown, where | means "or") can be used with subpatterns which bind variables, but all the subpatterns need to bind the same variables.


问:
Failed to load resource: the server responded with a status of 500 (Internal Server Error), Error: Request failed with status code 500
I'm working on this social media app. and every time I try to sign up/sign in to the application it gives me this error.

```<code>Failed to load resource: the server responded with a status of 500 (Internal Server Error)
Register.jsx:27 Error: Request failed with status code 500
    at createError (createError.js:16:1)
    at settle (settle.js:17:1)
    at XMLHttpRequest.onloadend (xhr.js:54:1)
</code>```

Here the server-side code

```<code>const router = require("express").Router();
const User = require("../models/User");
const bcrypt = require("bcrypt");

//REGISTER
router.post("/register", async (req, res) => {
  try {
    //generate new password
    const salt = await bcrypt.genSalt(10);
    const hashedPassword = await bcrypt.hash(req.body.password, salt);

    //create new user
    const newUser = new User({
      username: req.body.username,
      email: req.body.email,
      password: hashedPassword,
    });

    //save user and respond
    const user = await newUser.save();
    res.status(200).json(user);
  } catch (err) {
    res.status(500).json(err)
  }
});

//LOGIN
router.post("/login", async (req, res) => {
  try {
    const user = await User.findOne({ email: req.body.email });
    !user && res.status(404).json("user not found");

    const validPassword = await bcrypt.compare(req.body.password, user.password)
    !validPassword && res.status(400).json("wrong password")

    res.status(200).json(user)
  } catch (err) {
    res.status(500).json(err)
  }
});

module.exports = router;
</code>```

Tech-Stack used in API: MongoDB, Node.js, and Express

答:
When you serve the 500 error page, it is highly recommended to log the error in the output (not in the response, but in the logs):

Also, you have to return when sending the response, so that you do not write the head multiple times.

```<code>//LOGIN
router.post("/login", async (req, res) => {
  try {
    const user = await User.findOne({ email: req.body.email });
    if (!user) {
      return res.status(404).json("user not found");
    }
    const validPassword = await bcrypt.compare(req.body.password, user.password)

    if (!validPassword) {
      return res.status(400).json("wrong password")
    }

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

Body:
I'm working on this social media app. and every time I try to sign up/sign in to the application it gives me this error.

Failed to load resource: the server responded with a status of 500 (Internal Server Error)
Register.jsx:27 Error: Request failed with status code 500
    at createError (createError.js:16:1)
    at settle (settle.js:17:1)
    at XMLHttpRequest.onloadend (xhr.js:54:1)

Here the server-side code

const router = require("express").Router();
const User = require("../models/User");
const bcrypt = require("bcrypt");

//REGISTER
router.post("/register", async (req, res) => {
  try {
    //generate new password
    const salt = await bcrypt.genSalt(10);
    const hashedPassword = await bcrypt.hash(req.body.password, salt);

    //create new user
    const newUser = new User({
      username: req.body.username,
      email: req.body.email,
      password: hashedPassword,
    });

    //save user and respond
    const user = await newUser.save();
    res.status(200).json(user);
  } catch (err) {
    res.status(500).json(err)
  }
});

//LOGIN
router.post("/login", async (req, res) => {
  try {
    const user = await User.findOne({ email: req.body.email });
    !user && res.status(404).json("user not found");

    const validPassword = await bcrypt.compare(req.body.password, user.password)
    !validPassword && res.status(400).json("wrong password")

    res.status(200).json(user)
  } catch (err) {
    res.status(500).json(err)
  }
});

module.exports = router;

Tech-Stack used in API: MongoDB, Node.js, and Express

Body:
When you serve the 500 error page, it is highly recommended to log the error in the output (not in the response, but in the logs):

Also, you have to return when sending the response, so that you do not write the head multiple times.

//LOGIN
router.post("/login", async (req, res) => {
  try {
    const user = await User.findOne({ email: req.body.email });
    if (!user) {
      return res.status(404).json("user not found");
    }
    const validPassword = await bcrypt.compare(req.body.password, user.password)

    if (!validPassword) {
      return res.status(400).json("wrong password")
    }

    res.status(200).json(user)
  } catch (err) {
    console.error(err)
    res.status(500).json(err)
  }
});


问:
Resizing wpf window programmatically in c#
I have a wpf window with two usercontrols inside of which the second is only shown when needed. I only set the MinWidth of the window in XAML, the MinHeight is provided through databinding an ist set depending on if the second usercontrol is shown. Now: How can I set the size of the window to different values than the MinWidth/Height during runtime. I tried setting the values before the Show(), after the Show(), in various events (Initialized, Loaded, etc.). I tried with and without UpdateLayout(), I tried setting the Height/Width through databinding. Nothing works! But when I debug the approaches I see that the Height/Width properties of the window are set to the expected values, but ActualHeight/Width stay. I thought it would be a bagatelle but it turned out it is not (to me). Thy for any help.</p>

答:
You have no given much information, so I am just guessing here.

The only way I could reproduce the window not respecting its width and height settings was when I set SizeToContent to WidthAndHeight.