问:
Retrofit 2 add Header - Logging interceptor
I'm adding a Header to a get request - the server-side doesn't receive the header. I'm using addConverterFactory(ScalarsConverterFactory.create()).The code:

```<code>        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.HEADERS);

        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(new Interceptor() {
                    @NotNull
                    @Override
                    public okhttp3.Response intercept(@NotNull Chain chain) throws IOException {
                        Request originalRequest = chain.request();
                        Request newRequest = originalRequest.newBuilder()
                                .addHeader("Header","123")
                                .build();
                        return chain.proceed(newRequest);
                    }
                })
                .addInterceptor(loggingInterceptor)
                .build();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("URL")
                .addConverterFactory(ScalarsConverterFactory.create())
                .client(okHttpClient)
                .build();

        retrofit2.Call<String> call = apiRetrofitInterface.getString("URL");
        call.enqueue(new Callback<String>() {
            @Override
            public void onResponse(retrofit2.Call<String> call, retrofit2.Response<String> response) {
                 //
            }
</code>```

Interface Code:

```<code>public interface ApiRetrofitInterface {

    @GET
    Call <String> getString(@Url String url);
}
</code>```

Is it possible that the header is in the Logging Interceptor but the server doesn't receive it?

```<code> I/okhttp.OkHttpClient: --> GET "MY URL"
 I/okhttp.OkHttpClient: Header: 123
 I/okhttp.OkHttpClient: --> END GET
 I/okhttp.OkHttpClient: <-- 400 Bad Request "MY URL" (137ms)
 I/okhttp.OkHttpClient: X-Powered-By: Express
 I/okhttp.OkHttpClient: Access-Control-Allow-Origin: *
 I/okhttp.OkHttpClient: Access-Control-Allow-Headers: content-type
 I/okhttp.OkHttpClient: Access-Control-Allow-Methods: GET, POST, PUT, DELETE, PATCH, OPTIONS
 I/okhttp.OkHttpClient: Content-Type: text/html; charset=utf-8
 I/okhttp.OkHttpClient: Content-Length: 39
 I/okhttp.OkHttpClient: ETag: W/"27-Gy6wj20Vfpjmp7p+PeGaPrL9u2U"
 I/okhttp.OkHttpClient: Date: Sun, 31 May 2020 21:53:29 GMT
 I/okhttp.OkHttpClient: Connection: keep-alive
 I/okhttp.OkHttpClient: <-- END HTTP
</code>```

答:
If the header not in w3cschool protocol，It may be removed by the Firewall what the Gateway your data transported used.

So use the header key in http protocol.

hope to help you

Body:
I'm adding a Header to a get request - the server-side doesn't receive the header. I'm using addConverterFactory(ScalarsConverterFactory.create()).The code:

        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.HEADERS);

        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(new Interceptor() {
                    @NotNull
                    @Override
                    public okhttp3.Response intercept(@NotNull Chain chain) throws IOException {
                        Request originalRequest = chain.request();
                        Request newRequest = originalRequest.newBuilder()
                                .addHeader("Header","123")
                                .build();
                        return chain.proceed(newRequest);
                    }
                })
                .addInterceptor(loggingInterceptor)
                .build();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("URL")
                .addConverterFactory(ScalarsConverterFactory.create())
                .client(okHttpClient)
                .build();

        retrofit2.Call<String> call = apiRetrofitInterface.getString("URL");
        call.enqueue(new Callback<String>() {
            @Override
            public void onResponse(retrofit2.Call<String> call, retrofit2.Response<String> response) {
                 //
            }

Interface Code:

public interface ApiRetrofitInterface {

    @GET
    Call <String> getString(@Url String url);
}

Is it possible that the header is in the Logging Interceptor but the server doesn't receive it?

 I/okhttp.OkHttpClient: --> GET "MY URL"
 I/okhttp.OkHttpClient: Header: 123
 I/okhttp.OkHttpClient: --> END GET
 I/okhttp.OkHttpClient: <-- 400 Bad Request "MY URL" (137ms)
 I/okhttp.OkHttpClient: X-Powered-By: Express
 I/okhttp.OkHttpClient: Access-Control-Allow-Origin: *
 I/okhttp.OkHttpClient: Access-Control-Allow-Headers: content-type
 I/okhttp.OkHttpClient: Access-Control-Allow-Methods: GET, POST, PUT, DELETE, PATCH, OPTIONS
 I/okhttp.OkHttpClient: Content-Type: text/html; charset=utf-8
 I/okhttp.OkHttpClient: Content-Length: 39
 I/okhttp.OkHttpClient: ETag: W/"27-Gy6wj20Vfpjmp7p+PeGaPrL9u2U"
 I/okhttp.OkHttpClient: Date: Sun, 31 May 2020 21:53:29 GMT
 I/okhttp.OkHttpClient: Connection: keep-alive
 I/okhttp.OkHttpClient: <-- END HTTP


来源: stackexchange

问:
How to Convert Arabic Characters to Unicode Using PHP
I want to to know how can I convert a word into unicode exactly like:
http://www.arabunic.free.fr/

can anyone know how to do that using PHP considering that Arabic text may contains ligatures?

thanks

Edit

I'm not sure what is that "unicode" but I need to have the Arabic Character in it's equivalent machine number considering that arabic characters have different  contextual forms depending on their position - see here:

http://en.wikipedia.org/wiki/Arabic_alphabet#Table_of_basic_letters

the same character in different position:

ب | ـب |    ـبـ | بـ

I think it must be a way to convert each Arabic character into it's equivalent number, but how?

Edit

I still believe there's a way to convert each character to it's form depending on positions

any idea is appreciated..

答:
i assume you wnat to convert بهروز to \u0628\u0647\u0631\u0648\u0632 take a look at http://hsivonen.iki.fi/php-utf8/ all you have to do after calling unicodeToUtf8('بهروز') is to convert integers you got in array to hex & make sure they have 4digigts & prefix em with \u & you're done. also you can get same using json_encode

```
json_encode('بهروز') // returns "\u0628\u0647\u0631\u0648\u0632"
```

EDIT:

seems you want to get character codes of بب which first one differs from second one, all you have to do is applying bidi algorithm on your text using fribidi_log2vis then getting character code by one of ways i said before.

here's example:

```
$string = 'بب'; // \u0628\u0628
$bidiString = fribidi_log2vis($string, FRIBIDI_LTR, FRIBIDI_CHARSET_UTF8);
json_encode($bidiString); // \ufe90\ufe91
```

EDIT:

i just remembered that tcpdf has bidi algorithm which implemented using pure php so if you can not get fribidi extension of php to work, you can use tcpdf (utf8Bidi by default is protected so you need to make it public)

```
require_once('utf8.inc'); // http://hsivonen.iki.fi/php-utf8/
require_once('tcpdf.php'); // http://www.tcpdf.org/
$t = new TCPDF();
$text = 'بب';
$t->utf8Bidi(utf8ToUnicode($text)); // will return an array like array(0 => 65168, 1 => 65169)
```

ContentLicense: CC BY-SA 3.0

Body:
i assume you wnat to convert بهروز to \u0628\u0647\u0631\u0648\u0632 take a look at http://hsivonen.iki.fi/php-utf8/ all you have to do after calling unicodeToUtf8('بهروز') is to convert integers you got in array to hex & make sure they have 4digigts & prefix em with \u & you're done. also you can get same using json_encode

json_encode('بهروز') // returns "\u0628\u0647\u0631\u0648\u0632"

EDIT:

seems you want to get character codes of بب which first one differs from second one, all you have to do is applying bidi algorithm on your text using fribidi_log2vis then getting character code by one of ways i said before.

here's example:

$string = 'بب'; // \u0628\u0628
$bidiString = fribidi_log2vis($string, FRIBIDI_LTR, FRIBIDI_CHARSET_UTF8);
json_encode($bidiString); // \ufe90\ufe91

EDIT:

i just remembered that tcpdf has bidi algorithm which implemented using pure php so if you can not get fribidi extension of php to work, you can use tcpdf (utf8Bidi by default is protected so you need to make it public)

require_once('utf8.inc'); // http://hsivonen.iki.fi/php-utf8/
require_once('tcpdf.php'); // http://www.tcpdf.org/
$t = new TCPDF();
$text = 'بب';
$t->utf8Bidi(utf8ToUnicode($text)); // will return an array like array(0 => 65168, 1 => 65169)


问:
Why does Visual Studio Code show that type `NonNullableUserPropertyKeys = never`?
this my code

```<code> type NonNullablePropertyKeys<T> = {
    [P in keyof T]: null extends T[P] ? never : P;
  }[keyof T];

  type User = {
    name: string;
    email: string | null;
  };

  type NonNullableUserPropertyKeys = NonNullablePropertyKeys<User>;
</code>```

Why does Visual Studio Code show that type NonNullableUserPropertyKeys = never ?.

答:
My guess is that you have not enabled the --strictNullChecks compiler option.  I'd suggest you use the --strict compiler option (which includes --strictNullChecks along with some other flags that improve type safety).  It's off by default, for backwards compatibility reasons, which is really too bad.

Anyway, with --strictNullChecks disabled, null and undefined are assignable to every type, and therefore null extends T[P] is always true.  If all types are nullable, then NonNullableUserPropertyKeys should be never:

Playground link to code with --strictNullChecks disabled

If you enable --strictNullChecks, then null is no longer assignable to every type, and NonNullableUserPropertyKeys should evaluate to "name":

```<code>type NonNullableUserPropertyKeys = NonNullablePropertyKeys<User>;
// type NonNullableUserPropertyKeys = "name"
</code>```

Playground link to code with --strictNullChecks enabled.

Hope that helps; good luck!

ContentLicense: CC BY-SA 4.0

Body:
this my code

 type NonNullablePropertyKeys<T> = {
    [P in keyof T]: null extends T[P] ? never : P;
  }[keyof T];

  type User = {
    name: string;
    email: string | null;
  };

  type NonNullableUserPropertyKeys = NonNullablePropertyKeys<User>;

Why does Visual Studio Code show that type NonNullableUserPropertyKeys = never ?.

Body:
My guess is that you have not enabled the --strictNullChecks compiler option.  I'd suggest you use the --strict compiler option (which includes --strictNullChecks along with some other flags that improve type safety).  It's off by default, for backwards compatibility reasons, which is really too bad.

Anyway, with --strictNullChecks disabled, null and undefined are assignable to every type, and therefore null extends T[P] is always true.  If all types are nullable, then NonNullableUserPropertyKeys should be never:

Playground link to code with --strictNullChecks disabled

If you enable --strictNullChecks, then null is no longer assignable to every type, and NonNullableUserPropertyKeys should evaluate to "name":

type NonNullableUserPropertyKeys = NonNullablePropertyKeys<User>;
// type NonNullableUserPropertyKeys = "name"

Playground link to code with --strictNullChecks enabled.

Hope that helps; good luck!


问:
Custom font on simple html website will not load
I have been following code and examples online to try and use a custom font on my very basic html website. If it matters, I am using django.

Files of note:

aurebesh_translator.html

```<code><!DOCTYPE html>
<html>
    <link rel="stylesheet" type="text/css" href="main.css">
    <p>This should be in aurebesh</p>
</html>
</code>```

main.css

```<code>@font-face {
    font-family: "aurebesh";
    src: url(aurebesh.ttf);
    font-style: normal;
    font-weight: 100;
}

p {
    font-family: aurebesh;
    font-weight: 100;
}
</code>```

These are arranged as follows:

```<code>| templates
| - ...
| - main.css
| - aurebesh_translator.html
| - fonts
| -- aurebesh.ttf

</code>```

... where the aurebesh.ttf file is the associated font file for the font I want to use.

From what I can tell online, this seems to be the way it is supposed to be formatted to use my custom font. The weird thing is, if I just copy the above files to my desktop (so that only main.css, aurebesh_translator.html, and fonts/aurebesh.ttf are present) and run the aurebesh_translator.html in a browser, it loads and uses the font successfully! This is super weird to me, because when I include these files in the context of the rest of my website's files, it somehow stops working! I have tried opening it in chrome as well as firefox and neither work (they both just load in without my custom font).

This is the error I get from my terminal running my server when I try to access the page:

```<code>[01/Jun/2020 00:08:18] "GET /articles/aurebesh_translator HTTP/1.1" 200 127
Not Found: /articles/main.css
[01/Jun/2020 00:08:18] "GET /articles/main.css HTTP/1.1" 404 4061
</code>```

How can I fix this error?

答:
In Django when you link css/js static files use static tag in href attribute i.e. href = "{% static 'path_of_file' %}"
In this case use  href = "{% static 'main.css' %}"

Body:
I have been following code and examples online to try and use a custom font on my very basic html website. If it matters, I am using django.

Files of note:

aurebesh_translator.html

<!DOCTYPE html>

    <link rel="stylesheet" type="text/css" href="main.css">

This should be in aurebesh

main.css

@font-face {
    font-family: "aurebesh";
    src: url(aurebesh.ttf);
    font-style: normal;
    font-weight: 100;
}

p {
    font-family: aurebesh;
    font-weight: 100;
}

These are arranged as follows:

| templates
| - ...
| - main.css
| - aurebesh_translator.html
| - fonts
| -- aurebesh.ttf

... where the aurebesh.ttf file is the associated font file for the font I want to use.

From what I can tell online, this seems to be the way it is supposed to be formatted to use my custom font. The weird thing is, if I just copy the above files to my desktop (so that only main.css, aurebesh_translator.html, and fonts/aurebesh.ttf are present) and run the aurebesh_translator.html in a browser, it loads and uses the font successfully! This is super weird to me, because when I include these files in the context of the rest of my website's files, it somehow stops working! I have tried opening it in chrome as well as firefox and neither work (they both just load in without my custom font).

This is the error I get from my terminal running my server when I try to access the page:

[01/Jun/2020 00:08:18] "GET /articles/aurebesh_translator HTTP/1.1" 200 127
Not Found: /articles/main.css
[01/Jun/2020 00:08:18] "GET /articles/main.css HTTP/1.1" 404 4061

How can I fix this error?


问:
Check if each row in a pandas series contains a string from a list using apply?
I'm trying to add a column to the DF, depending on whether other column's value contains any of the strings in a list.

The list is:

```<code>services = [
        "TELECOM",
        "AYSA",
        "PERSONAL"
]
</code>```

And so far I've tried:

```<code>payments["category"] = "services" if payments["concept"].contains(service for service in services) else ""
</code>```

And this:

```<code>payments["category"] = payments["concept"].apply(lambda x: "services" if x.contains(service) for service in services) else ""
</code>```

Among some other variations... I've seen other questions but they're mostly related to the opposite problem (checking whether a column's value is contained by a string in a list)

I could use your help! Thanks!!

答:
i think you can use isin

payments['category'] = np.where(
    payments['concept'].isin(services),
    'services', '')
```

<pre class="lang-py prettyprint-override"><code>import pandas
import numpy

dic = {"concept": ["TELECOM", "NULL"]}

payments = pandas.DataFrame.from_dict(dic)

payments["category"] = numpy.where(payments["concept"].isin(["TELECOM", "AYSA", "PERSONAL"]), "services", "")

print(payments)
</code>```

Body:
I'm trying to add a column to the DF, depending on whether other column's value contains any of the strings in a list.

The list is:

services = [
        "TELECOM",
        "AYSA",
        "PERSONAL"
]

And so far I've tried:

payments["category"] = "services" if payments["concept"].contains(service for service in services) else ""

And this:

payments["category"] = payments["concept"].apply(lambda x: "services" if x.contains(service) for service in services) else ""

Among some other variations... I've seen other questions but they're mostly related to the opposite problem (checking whether a column's value is contained by a string in a list)

I could use your help! Thanks!!

Body:
i think you can use isin

payments['category'] = np.where(
    payments['concept'].isin(services),
    'services', '')

import pandas
import numpy

dic = {"concept": ["TELECOM", "NULL"]}

payments = pandas.DataFrame.from_dict(dic)

payments["category"] = numpy.where(payments["concept"].isin(["TELECOM", "AYSA", "PERSONAL"]), "services", "")

print(payments)


问:
How to Visualize The frequency of a categorical variable in R
I have 2 variables in my dataframe that I am trying to use ggplot to graph. On the x-axis I want the date which has a daily frequency. On the y-axis I want the count of unique names that show up on that given day.

The variables look something like this in the dataframe.

```<code>     Date           Name

1   2016-03-01      Joe
2   2016-03-01      Joe
3   2016-03-01      Joe
4   2016-03-01      Mark
5   2016-03-01      Sue
6   2016-03-02      Mark
7   2016-03-02      Joe
8   2016-03-03      Joe
9   2016-03-03      Joe
10  2016-03-03      Bill
</code>```

So the frequency on the y-axis on the first day would show 3, 2 on the second, and 2 on the third.

My question is how do I produce that graph.

答:
count number of unique Name for each Date and then plot with geom_bar/geom_col.

```<code>library(dplyr)
library(ggplot2)
df %>%
  group_by(Date) %>%
  summarise(n = n_distinct(Name)) %>%
  ggplot()  + geom_col(aes(Date, n))
  #ggplot() + geom_bar(aes(Date, n), stat = "identity")
</code>```

data

```<code>df <- structure(list(Date = c("2016-03-01", "2016-03-01", "2016-03-01",
"2016-03-01", "2016-03-01", "2016-03-02", "2016-03-02", "2016-03-03",
"2016-03-03", "2016-03-03"), Name = c("Joe", "Joe", "Joe", "Mark",
"Sue", "Mark", "Joe", "Joe", "Joe", "Bill")), class = "data.frame",
 row.names = c(NA, -10L))
</code>```

Body:
I have 2 variables in my dataframe that I am trying to use ggplot to graph. On the x-axis I want the date which has a daily frequency. On the y-axis I want the count of unique names that show up on that given day.

The variables look something like this in the dataframe.

     Date           Name

1   2016-03-01      Joe
2   2016-03-01      Joe
3   2016-03-01      Joe
4   2016-03-01      Mark
5   2016-03-01      Sue
6   2016-03-02      Mark
7   2016-03-02      Joe
8   2016-03-03      Joe
9   2016-03-03      Joe
10  2016-03-03      Bill

So the frequency on the y-axis on the first day would show 3, 2 on the second, and 2 on the third.

My question is how do I produce that graph.

Body:
count number of unique Name for each Date and then plot with geom_bar/geom_col.

library(dplyr)
library(ggplot2)
df %>%
  group_by(Date) %>%
  summarise(n = n_distinct(Name)) %>%
  ggplot()  + geom_col(aes(Date, n))
  #ggplot() + geom_bar(aes(Date, n), stat = "identity")

data

df <- structure(list(Date = c("2016-03-01", "2016-03-01", "2016-03-01",
"2016-03-01", "2016-03-01", "2016-03-02", "2016-03-02", "2016-03-03",
"2016-03-03", "2016-03-03"), Name = c("Joe", "Joe", "Joe", "Mark",
"Sue", "Mark", "Joe", "Joe", "Joe", "Bill")), class = "data.frame",
 row.names = c(NA, -10L))


问:
Can't find method in module
I am learning Rust and trying to figure out why I can't call a method from a module I have written. The code is very simple as it's a learning exercise and I have read this and this but I still don't know what the problem is. I have also tried using the code from this question almost exactly however the error persists.

The code for main.rs and helper.rs are below.

main.rs:

```<code>mod helpers;

fn main() {
    let h = helpers::new("TestString");
    println!("{}", h.get_name().to_string());
    helpers::test_func();
}
</code>```

helpers.rs

```<code>struct Helper{
    name: String
}

impl Helper {
    pub fn new(name: &String) -> Helper {
        let helper = Helper{ name: name.to_string()};
        return helper;
    }
}

impl Helper {
    pub fn get_name(&self) -> &String {
        return &self.name;
    }
}

pub fn test_func(){
    println!("test_func was called.");
}
</code>```

The error I am getting is:

```<code>error[E0425]: cannot find function `new` in module `helpers`
 --> src/main.rs:4:30
  |
4 |     let h = helpers::new("TestString");
  |                              ^^^ not found in `helpers`

error: aborting due to previous error
</code>```

I know the file is being read because if you commend out lines 4 & 5 from main.rs and just run helpers::test_func() it works fine however I don't know why it can't find the new method.

Any help would be very much appreciated.

答:
The error is constructor call. When calling constructors in rust you can use this syntax:

let h = Helper{ name: "TestString".to_string() };
```

Also you need to use to_string method to convert &str to String.

Title: Can't find method in module

Body:
I am learning Rust and trying to figure out why I can't call a method from a module I have written. The code is very simple as it's a learning exercise and I have read this and this but I still don't know what the problem is. I have also tried using the code from this question almost exactly however the error persists.

The code for main.rs and helper.rs are below.

main.rs:

mod helpers;

fn main() {
    let h = helpers::new("TestString");
    println!("{}", h.get_name().to_string());
    helpers::test_func();
}

helpers.rs

struct Helper{
    name: String
}

impl Helper {
    pub fn new(name: &String) -> Helper {
        let helper = Helper{ name: name.to_string()};
        return helper;
    }
}

impl Helper {
    pub fn get_name(&self) -> &String {
        return &self.name;
    }
}

pub fn test_func(){
    println!("test_func was called.");
}

The error I am getting is:

error[E0425]: cannot find function `new` in module `helpers`
 --> src/main.rs:4:30
  |
4 |     let h = helpers::new("TestString");
  |                              ^^^ not found in `helpers`

error: aborting due to previous error

I know the file is being read because if you commend out lines 4 & 5 from main.rs and just run helpers::test_func() it works fine however I don't know why it can't find the new method.

Any help would be very much appreciated.

Body:
The error is constructor call. When calling constructors in rust you can use this syntax:

let h = Helper{ name: "TestString".to_string() };

Also you need to use to_string method to convert &str to String.


问:
Laravel - send email with model observer on one-to-many relationship
I am making an order submission feature for my eCommerce app in Laravel. For every order submission, I created an order record in my orders table. And them add items to order_items table pointing to the order I just created. My controller is as below:

```<code>DB::transaction(function () use ($customer, $request) {
        $order = Order::create([
            'order_number' => Order::createOrderNumber(),
            'customer_id' => $customer->id,
            'note' => $request->input('note'),
            'status' => 'PENDING',
            'request_date' => $request->input('date'),
        ]);

        $parts = json_decode($request->input('parts'));
        foreach ($parts as $part) {
            foreach ($part->selections as $selection) {
                $order_item = OrderItem::create([
                    'order_id' => $order->id,
                    'selection_id' => $selection->id,
                    'quantity' => $selection->quantity,
                    'price' => Selection::find($selection->id)->first()->price
                ]);
                if (isset($selection->file)) {
                    $file = $request->file('files')[$selection->file];
                    $filename_original = $file->getClientOriginalName();
                    $extension = $file->extension();
                    $filename = md5(microtime()).'.'.$extension;
                    try {
                        $file->storeAs('/files/order/'.$order->order_number, $filename);
                    } catch (Exception $e) {
                    }
                    $order_item->filename = $filename;
                    $order_item->filename_original = $filename_original;
                    $order_item->save();
                }
            }
        }
</code>```

This works all fine with order creation. Now I am trying to send a confirmation email containing all the order details when this is done. I can directly add the mailable to my controller and that would work all fine. But I am trying to separate all the "side effect" from controller by using a model observer. So I tried to send the email from Order observer, listening to the created

```<code>public function created(Order $order)
{
    Mail::to($order->customer->email)->send(new OrderMail($order, 'confirmation'));
}
</code>```

Though email sent out, it terms out since my Order was created before adding all items, and the observer fire as soon as the model created, when I use relationship in my email view, it always return empty array

```<code>    @foreach($order->items as $item)
      <tr>
        <td>{{ $item->name }}</td>
        <td>{{ $item->quantity }}</td>
        <td class="alignright">$ {{ number_format($item->subtotal, 2, '.', ',') }}</td>
       </tr>
    @endforeach
</code>```

Is there any way that I can still separate my email sending process from controller, but will wait until my "adding item to order" process complete ?

答:
For segregating the email process, you can make use of Laravel Event/Listener system. For example, you can create event called OrderSubmitted and its listener called SendEmailNotification

For more info about Laravel event/listener system: https://laravel.com/docs/7.x/events

Body:
I am making an order submission feature for my eCommerce app in Laravel. For every order submission, I created an order record in my orders table. And them add items to order_items table pointing to the order I just created. My controller is as below:

DB::transaction(function () use ($customer, $request) {
        $order = Order::create([
            'order_number' => Order::createOrderNumber(),
            'customer_id' => $customer->id,
            'note' => $request->input('note'),
            'status' => 'PENDING',
            'request_date' => $request->input('date'),
        ]);

        $parts = json_decode($request->input('parts'));
        foreach ($parts as $part) {
            foreach ($part->selections as $selection) {
                $order_item = OrderItem::create([
                    'order_id' => $order->id,
                    'selection_id' => $selection->id,
                    'quantity' => $selection->quantity,
                    'price' => Selection::find($selection->id)->first()->price
                ]);
                if (isset($selection->file)) {
                    $file = $request->file('files')[$selection->file];
                    $filename_original = $file->getClientOriginalName();
                    $extension = $file->extension();
                    $filename = md5(microtime()).'.'.$extension;
                    try {
                        $file->storeAs('/files/order/'.$order->order_number, $filename);
                    } catch (Exception $e) {
                    }
                    $order_item->filename = $filename;
                    $order_item->filename_original = $filename_original;
                    $order_item->save();
                }
            }
        }

This works all fine with order creation. Now I am trying to send a confirmation email containing all the order details when this is done. I can directly add the mailable to my controller and that would work all fine. But I am trying to separate all the "side effect" from controller by using a model observer. So I tried to send the email from Order observer, listening to the created

public function created(Order $order)
{
    Mail::to($order->customer->email)->send(new OrderMail($order, 'confirmation'));
}

Though email sent out, it terms out since my Order was created before adding all items, and the observer fire as soon as the model created, when I use relationship in my email view, it always return empty array

    @foreach($order->items as $item)

        {{ $item->name }}
        {{ $item->quantity }}
        $ {{ number_format($item->subtotal, 2, '.', ',') }}

    @endforeach

Is there any way that I can still separate my email sending process from controller, but will wait until my "adding item to order" process complete ?


问:
Read a text file, replace its words, output to another text file
So I am trying to make a program in GO to take a text file full of code and convert that into GO code and then save that file into a GO file or text file. I have been trying to figure out how to save the changes I made to the text file, but the only way I can see the changes is through a println statement because I am using strings.replace to search the string array that the text file is stored in and change each occurrence of a word that needs to be changed (ex. BEGIN -> { and END -> }). So is there any other way of searching and replacing in GO I don't know about or is there a way to edit a text file that I don't know about or is this impossible?

Thanks

Here is the code I have so far.

```<code>package main

import (
    "os"
    "bufio"
    "bytes"
    "io"
    "fmt"
    "strings"
)

func readLines(path string) (lines []string, errr error) {
    var (
        file *os.File
        part []byte
        prefix bool
    )
    if file, errr = os.Open(path); errr != nil {
        return
    }
    defer file.Close()

    reader := bufio.NewReader(file)
    buffer := bytes.NewBuffer(make([]byte, 0))
    for {
        if part, prefix, errr = reader.ReadLine(); errr != nil {
            break
        }
    buffer.Write(part)
        if !prefix {
            lines = append(lines, buffer.String())
            buffer.Reset()
        }
    }
    if errr == io.EOF {
        errr = nil
    }
    return
}

func writeLines(lines []string, path string) (errr error) {
    var (
        file *os.File
    )

    if file, errr = os.Create(path); errr != nil {
        return
    }
    defer file.Close()

    for _,item := range lines {

        _, errr := file.WriteString(strings.TrimSpace(item) + "\n");

        if errr != nil {

            fmt.Println(errr)
            break
        }
    }

    return
}

func FixBegin(lines []string) (errr error) {
    var(
    a string

    )
for i := 0; ; i++ {
        a = lines[i];

        fmt.Println(strings.Replace(a, "BEGIN", "{", -1))
    }

    return
}

func FixEnd(lines []string) (errr error) {
    var(
    a string

    )
for i := 0; ; i++ {
        a = lines[i];

        fmt.Println(strings.Replace(a, "END", "}", -1))
    }
    return
}

func main() {
    lines, errr := readLines("foo.txt")
    if errr != nil {
        fmt.Println("Error: %s\n", errr)
        return
    }
    for _, line := range lines {
        fmt.Println(line)
    }

    errr = FixBegin(lines)

    errr = writeLines(lines, "beer2.txt")
    fmt.Println(errr)

    errr = FixEnd(lines)
    lines, errr = readLines("beer2.txt")
    if errr != nil {
        fmt.Println("Error: %s\n", errr)
        return
    }
    errr = writeLines(lines, "beer2.txt")
    fmt.Println(errr)
}
</code>```

答:
If your file size is huge, reading everything in memory might not be possible nor advised. Give BytesReplacingReader a try as it is done replacement in streaming fashion. And it's reasonably performant. If you want to replace two strings (such as BEGIN -> { and END -> }), just need to wrap two BytesReplacingReader over original reader, one for BEGIN and one for END:

```<code>r := NewBytesReplacingReader(
    NewBytesReplacingReader(inputReader, []byte("BEGIN"), []byte("{"),
    []byte("END"), []byte("}")
// use r normally and all non-overlapping occurrences of
// "BEGIN" and "END" will be replaced with "{" and "}"
</code>```

Body:
So I am trying to make a program in GO to take a text file full of code and convert that into GO code and then save that file into a GO file or text file. I have been trying to figure out how to save the changes I made to the text file, but the only way I can see the changes is through a println statement because I am using strings.replace to search the string array that the text file is stored in and change each occurrence of a word that needs to be changed (ex. BEGIN -> { and END -> }). So is there any other way of searching and replacing in GO I don't know about or is there a way to edit a text file that I don't know about or is this impossible?

Thanks

Here is the code I have so far.

package main

import (
    "os"
    "bufio"
    "bytes"
    "io"
    "fmt"
    "strings"
)

func readLines(path string) (lines []string, errr error) {
    var (
        file *os.File
        part []byte
        prefix bool
    )
    if file, errr = os.Open(path); errr != nil {
        return
    }
    defer file.Close()

    reader := bufio.NewReader(file)
    buffer := bytes.NewBuffer(make([]byte, 0))
    for {
        if part, prefix, errr = reader.ReadLine(); errr != nil {
            break
        }
    buffer.Write(part)
        if !prefix {
            lines = append(lines, buffer.String())
            buffer.Reset()
        }
    }
    if errr == io.EOF {
        errr = nil
    }
    return
}

func writeLines(lines []string, path string) (errr error) {
    var (
        file *os.File
    )

    if file, errr = os.Create(path); errr != nil {
        return
    }
    defer file.Close()

    for _,item := range lines {

        _, errr := file.WriteString(strings.TrimSpace(item) + "\n");

        if errr != nil {

            fmt.Println(errr)
            break
        }
    }

    return
}

func FixBegin(lines []string) (errr error) {
    var(
    a string

    )
for i := 0; ; i++ {
        a = lines[i];

        fmt.Println(strings.Replace(a, "BEGIN", "{", -1))
    }

    return
}

func FixEnd(lines []string) (errr error) {
    var(
    a string

    )
for i := 0; ; i++ {
        a = lines[i];

        fmt.Println(strings.Replace(a, "END", "}", -1))
    }
    return
}

func main() {
    lines, errr := readLines("foo.txt")
    if errr != nil {
        fmt.Println("Error: %s\n", errr)
        return
    }
    for _, line := range lines {
        fmt.Println(line)
    }

    errr = FixBegin(lines)

    errr = writeLines(lines, "beer2.txt")
    fmt.Println(errr)

    errr = FixEnd(lines)
    lines, errr = readLines("beer2.txt")
    if errr != nil {
        fmt.Println("Error: %s\n", errr)
        return
    }
    errr = writeLines(lines, "beer2.txt")
    fmt.Println(errr)
}

Body:
If your file size is huge, reading everything in memory might not be possible nor advised. Give BytesReplacingReader a try as it is done replacement in streaming fashion. And it's reasonably performant. If you want to replace two strings (such as BEGIN -> { and END -> }), just need to wrap two BytesReplacingReader over original reader, one for BEGIN and one for END:

r := NewBytesReplacingReader(
    NewBytesReplacingReader(inputReader, []byte("BEGIN"), []byte("{"),
    []byte("END"), []byte("}")
// use r normally and all non-overlapping occurrences of
// "BEGIN" and "END" will be replaced with "{" and "}"


问:
Is there an editor that can allow me to see code snippets with references and declaration?
just like how in sublime / atom, you can view usage and declaration of a function, I want to be able to view the usage and declaration, not only as a file and a line number, but when I hover over it, it will also show the lines of context around the declaration and usage in a popup / hover window that I can copy paste from.</p>

答: Source Insight does what you want but a little bit pricy and windows only.</p>


问:
I want to know the tag approach defined in javascript innerHTML
```<code>var list = document.createElement("div");

list.innerHTML = '<ul>'+
        '<li>'+
            '<span>1</span>'+
        '</li>'+
        '<li>'+
            '<span>2</span>'+
        '</li>'+
        '<li>'+
            '<span>3</span>'+
        '</li>'+
        '<li>'+
            '<span>4</span>'+
        '</li>'+
        '<li>'+
            '<span>5</span>'+
        '</li>'+
    '</ul>';
</code>```

After creating a div element with createElement

I filled the inner content through innerHTML.

I don't know how to access each li or ul here.

If anyone knows, thank you for your reply!

答:
if you want any action on each element then you need to create an element like div.

Or

```<code>var list = document.createElement("div");

list.innerHTML = '<ul>'+
        '<li>'+
            '<span>1</span>'+
        '</li>'+
        '<li>'+
            '<span>2</span>'+
        '</li>'+
        '<li>'+
            '<span>3</span>'+
        '</li>'+
        '<li>'+
            '<span>4</span>'+
        '</li>'+
        '<li>'+
            '<span>5</span>'+
        '</li>'+
    '</ul>';
var liElements = list.querySelectorAll('li')
console.log(liElements)
</code>```

'liElements' contain all li elements in your div.

you can refer this link https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll

Body:
var list = document.createElement("div");

list.innerHTML = '
'+
        '
'+
            '1'+
        '
'+
        '
'+
            '2'+
        '
'+
        '
'+
            '3'+
        '
'+
        '
'+
            '4'+
        '
'+
        '
'+
            '5'+
        '
'+
    '
';

After creating a div element with createElement

I filled the inner content through innerHTML.

I don't know how to access each li or ul here.

If anyone knows, thank you for your reply!

Body:
if you want any action on each element then you need to create an element like div.

Or

var list = document.createElement("div");

list.innerHTML = '<ul>'+
        '<li>'+
            '<span>1</span>'+
        '</li>'+
        '<li>'+
            '<span>2</span>'+
        '</li>'+
        '<li>'+
            '<span>3</span>'+
        '</li>'+
        '<li>'+
            '<span>4</span>'+
        '</li>'+
        '<li>'+
            '<span>5</span>'+
        '</li>'+
    '</ul>';
var liElements = list.querySelectorAll('li')
console.log(liElements)

'liElements' contain all li elements in your div.

you can refer this link https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll


问:
Why can't I webscrape the table that I want?
I am new to BeautifulSoup and I wanted to try out some web scraping. For my little project, I wanted to get the Golden State Warrior win rate from Wikipedia. I was planning to get the table that had that information and make it into a panda so I could graph it over the years. However, my code selects the Table Key table instead of the Seasons table. I know this is because they are the same type of table (wikitable), but I don't know how to solve this problem. I am sure that there is an easy explanation that I am missing. Can someone please explain how to fix my code and explain how I could choose which tables to web scrape in the future? Thanks!</p>

```<code>c_data = "https://en.wikipedia.org/wiki/List_of_Golden_State_Warriors_seasons" #wikipedia page
c_page = urllib.request.urlopen(c_data)
c_soup = BeautifulSoup(c_page, "lxml")
c_table=c_soup.find('table', class_='wikitable') #this is the problem
c_year = []
c_rate = []
for row in c_table.findAll('tr'): #setup for dataframe
  cells=row.findAll('td')
  if len(cells)==13:
    c_year = c_year.append(cells[0].find(text=True))
    c_rate = c_rate.append(cells[9].find(text=True))
print(c_year, c_rate)
</code>```

答:
Use pd.read_html to get all the tables

This function returns a list of dataframes

tables[0] through tables[17], in this case

import pandas as pd

# read tables
tables = pd.read_html('https://en.wikipedia.org/wiki/List_of_Golden_State_Warriors_seasons')

print(len(tables))
>>> 18

tables[0]
          0                                             1
0       AHC                  NBA All-Star Game Head Coach
1      AMVP            All-Star Game Most Valuable Player
2       COY                             Coach of the Year
3      DPOY                  Defensive Player of the Year
4    Finish          Final position in division standings
5        GB  Games behind first-place team in division[b]
6   Italics                            Season in progress
7    Losses               Number of regular season losses
8       EOY                         Executive of the Year
9      FMVP                   Finals Most Valuable Player
10      MVP                          Most Valuable Player
11      ROY                            Rookie of the Year
12      SIX                         Sixth Man of the Year
13     SPOR                           Sportsmanship Award
14     Wins                 Number of regular season wins

# display all dataframes in tables
for i, table in enumerate(tables):
    print(f'Table {i}')
    display(table)
    print('\n')
```

<h2>Select specific table</h2>

<pre class="lang-py prettyprint-override"><code>df_i_want = tables[x]  # x is the specified table, 0 indexed

# delete tables
del(tables)
</code>```

Body:
I am new to BeautifulSoup and I wanted to try out some web scraping. For my little project, I wanted to get the Golden State Warrior win rate from Wikipedia. I was planning to get the table that had that information and make it into a panda so I could graph it over the years. However, my code selects the Table Key table instead of the Seasons table. I know this is because they are the same type of table (wikitable), but I don't know how to solve this problem. I am sure that there is an easy explanation that I am missing. Can someone please explain how to fix my code and explain how I could choose which tables to web scrape in the future? Thanks!

c_data = "https://en.wikipedia.org/wiki/List_of_Golden_State_Warriors_seasons" #wikipedia page
c_page = urllib.request.urlopen(c_data)
c_soup = BeautifulSoup(c_page, "lxml")
c_table=c_soup.find('table', class_='wikitable') #this is the problem
c_year = []
c_rate = []
for row in c_table.findAll('tr'): #setup for dataframe
  cells=row.findAll('td')
  if len(cells)==13:
    c_year = c_year.append(cells[0].find(text=True))
    c_rate = c_rate.append(cells[9].find(text=True))
print(c_year, c_rate)

Body:
Use pd.read_html to get all the tables

This function returns a list of dataframes

tables[0] through tables[17], in this case

import pandas as pd

# read tables
tables = pd.read_html('https://en.wikipedia.org/wiki/List_of_Golden_State_Warriors_seasons')

print(len(tables))
>>> 18

tables[0]
          0                                             1
0       AHC                  NBA All-Star Game Head Coach
1      AMVP            All-Star Game Most Valuable Player
2       COY                             Coach of the Year
3      DPOY                  Defensive Player of the Year
4    Finish          Final position in division standings
5        GB  Games behind first-place team in division[b]
6   Italics                            Season in progress
7    Losses               Number of regular season losses
8       EOY                         Executive of the Year
9      FMVP                   Finals Most Valuable Player
10      MVP                          Most Valuable Player
11      ROY                            Rookie of the Year
12      SIX                         Sixth Man of the Year
13     SPOR                           Sportsmanship Award
14     Wins                 Number of regular season wins

# display all dataframes in tables
for i, table in enumerate(tables):
    print(f'Table {i}')
    display(table)
    print('\n')

Select specific table

df_i_want = tables[x]  # x is the specified table, 0 indexed

# delete tables
del(tables)


问:
C++ Gapful Numbers Crashing
I was doing this program in which I am supossed to print gapful numbers all the way up to a specific value. The operations are correct, however, for some reason after printing a couple of values the program crashes, what can I do to fix this problem?

Here's my code:

```<code>#include<math.h>
#include<stdlib.h>
using namespace std;

void gapful(int);
bool gapCheck(int);

int main(){
    int n;

    cout<<"Enter a top number: ";
    cin>>n;

    gapful(n);

    system("pause");
    return 0;
}

void gapful(int og){
    for(int i=0; i<=og; i++){
        fflush(stdin);
        if(gapCheck(i)){
            cout<<i<<" ";
        }
    }
}

bool gapCheck(int n){
    int digits=0;
    int n_save,n1,n2,n3;

    if(n<100){
        return false;
    }
    else{
        n_save=n;
        while(n>10){
            n/=10;
            digits++;
        }
        digits++;
        n=n_save;
        n1=n/pow(10, digits);
        n2=n%10;
        n3=n1*10 + n2;
        if(n%n3 == 0){
            return true;
        }
        else{
            return false;
        }
    }
}
</code>```

I'm open to any suggestions and comments, thank you. :)

答:
You would benefit from more functions. Breaking things down into minimal blocks of code which represent a single purpose makes debugging code much easier. You need to ask yourself, what is a gapful number. It is a number that is evenly divisible by its first and last digit. So, what do we need to solve this?

We need to know how many digits a number has.
We need to know the first digit and the last digit of the number.

So start out by creating a function to resolve those problems. Then, you would have an easier time figuring out the final solution.

```<code>#include<math.h>
#include <iostream>
using namespace std;

void gapful(int);
bool gapCheck(int);
int getDigits(int);
int digitAt(int,int);

int main(){
    int n;
    cout<<"Enter a top number: " << endl;
    cin>>n;
    gapful(n);
    return 0;
}

void gapful(int og){
    for(int i=1; i<=og; ++i){
        if(gapCheck(i)){
            cout<<i << '-' <<endl;
        }
    }
}

int getDigits(int number) {
    int digitCount = 0;
    while (number >= 10) {
        ++digitCount;
        number /= 10;
    }
    return ++digitCount;
}

int digitAt(int number,int digit) {
    int numOfDigits = getDigits(number);
    int curDigit = 0;
    if (digit >=1 && digit <= numOfDigits) { //Verify digit is in range
        while (numOfDigits != digit) { //Count back to the digit requested
            number /=10;
            numOfDigits -=1;
        }
        curDigit = number%10; //Get the current digit to be returned.
    } else {
        throw "Digit requested is out of range!";
    }
    return curDigit;
}

bool gapCheck(int n){
    int digitsN = getDigits(n);
    if (digitsN < 3) { //Return false if less than 3 digits. Single digits do not apply and doubles result in themselves.
        return false;
    }
    int first = digitAt(n,1) * 10; //Get the first number in the 10s place
    int second = digitAt(n,digitsN); //Get the second number
    int total = first + second; //Add them
    return n % total == 0; //Return whether it evenly divides
}
</code>```

Title: C++ Gapful Numbers Crashing

Body:
I was doing this program in which I am supossed to print gapful numbers all the way up to a specific value. The operations are correct, however, for some reason after printing a couple of values the program crashes, what can I do to fix this problem?

Here's my code:

#include<math.h>
#include<stdlib.h>
using namespace std;

void gapful(int);
bool gapCheck(int);

int main(){
    int n;

    cout<<"Enter a top number: ";
    cin>>n;

    gapful(n);

    system("pause");
    return 0;
}

void gapful(int og){
    for(int i=0; i<=og; i++){
        fflush(stdin);
        if(gapCheck(i)){
            cout<<i<<" ";
        }
    }
}

bool gapCheck(int n){
    int digits=0;
    int n_save,n1,n2,n3;

    if(n<100){
        return false;
    }
    else{
        n_save=n;
        while(n>10){
            n/=10;
            digits++;
        }
        digits++;
        n=n_save;
        n1=n/pow(10, digits);
        n2=n%10;
        n3=n1*10 + n2;
        if(n%n3 == 0){
            return true;
        }
        else{
            return false;
        }
    }
}

I'm open to any suggestions and comments, thank you. :)

Body:
You would benefit from more functions. Breaking things down into minimal blocks of code which represent a single purpose makes debugging code much easier. You need to ask yourself, what is a gapful number. It is a number that is evenly divisible by its first and last digit. So, what do we need to solve this?

We need to know how many digits a number has.
We need to know the first digit and the last digit of the number.

So start out by creating a function to resolve those problems. Then, you would have an easier time figuring out the final solution.

#include<math.h>
#include <iostream>
using namespace std;

void gapful(int);
bool gapCheck(int);
int getDigits(int);
int digitAt(int,int);

int main(){
    int n;
    cout<<"Enter a top number: " << endl;
    cin>>n;
    gapful(n);
    return 0;
}

void gapful(int og){
    for(int i=1; i<=og; ++i){
        if(gapCheck(i)){
            cout<<i << '-' <<endl;
        }
    }
}

int getDigits(int number) {
    int digitCount = 0;
    while (number >= 10) {
        ++digitCount;
        number /= 10;
    }
    return ++digitCount;
}

int digitAt(int number,int digit) {
    int numOfDigits = getDigits(number);
    int curDigit = 0;
    if (digit >=1 && digit <= numOfDigits) { //Verify digit is in range
        while (numOfDigits != digit) { //Count back to the digit requested
            number /=10;
            numOfDigits -=1;
        }
        curDigit = number%10; //Get the current digit to be returned.
    } else {
        throw "Digit requested is out of range!";
    }
    return curDigit;
}

bool gapCheck(int n){
    int digitsN = getDigits(n);
    if (digitsN < 3) { //Return false if less than 3 digits. Single digits do not apply and doubles result in themselves.
        return false;
    }
    int first = digitAt(n,1) * 10; //Get the first number in the 10s place
    int second = digitAt(n,digitsN); //Get the second number
    int total = first + second; //Add them
    return n % total == 0; //Return whether it evenly divides
}


答:
What I would do is use the

```<code>rem
</code>```

command to draw out each line producing ASCII art and making it more fancy or you can always do the

```<code>type
</code>```

command and refrence a Python file with the text inside.

Title: Windows batch: Can't echo ASCII art with ._|_

Body:
I made ASCII art and I'm trying to have it shown when a .bat file is open. This is the (overwhelmingly basic) code I have. I've checked online and can't really find anything that could help me. Any suggestions?

@echo off
echo    __  __    _______    _____     _____     __  __
echo   / /_/ /   / ___  /   /  _  /   /  _  /   / /_/  /
echo  / __  /   / /__/ /   / ____/   /  ___/     \   /
echo /_/ /_/   /_/  /_/   /_/       /_/          /__/
echo    _____          _____     _______  __  __
echo   /  _ /  ____   /  _   /  / ___  / / /_/  /
echo  /  _ /  /___/  /  _/  /  / /__/ /  \    /
echo /____/         /______/  /_/  /_/    /__/
pause
echo
echo     #      #        #      #         #
echo .__|_|____|_|______|_|____|_|_______|_|____.
echo ############################################
echo |                                          |
echo ############################################
echo ############################################
echo |__________________________________________|
pause

I can already see myself crying because I didn't notice a tiny mistake.

It crashes on this line: echo .__|_|____|_|______|_|____|_|_______|_|____.

Body:
What I would do is use the

rem

command to draw out each line producing ASCII art and making it more fancy or you can always do the

type

command and refrence a Python file with the text inside.


问:
Transfer Data to specific Excel Sheet
I am trying to transfer the data to specific sheet at last row but not able to data transferring but after some empty cells in sheet b c d e help needed to solve data is transferring in each sheet but not at next empty cell:</p>

```<code> Sub transferData()
      Application.ScreenUpdating = False
      'Dim myData As Worksheet, ItemA As Worksheet, ItemB As Worksheet, ItemC As Worksheet, ItemD As
       Worksheet, ItemE As Worksheet
      Dim ItemName As String
      Dim price As Long, qty As Long

      Dim r1 As Long, r2 As Long, erow As Long, lastrow As Long
      r1 = 2
      r2 = 2
      Sheets(Array("Sheet2", "Sheet3", "Sheet4", "Sheet5", "Sheet6")).Select
      Sheets("Sheet2").Activate
      Cells.Select
      Selection.ClearContents
      Sheets(Array("Sheet2", "Sheet3", "Sheet4", "Sheet5", "Sheet6")).Select
      Sheets("Sheet2").Activate
      range("A1").Select
      ActiveCell.Value = "Item"
      range("B1").Select
      ActiveCell.Value = "Price"
      range("C1").Select
      ActiveCell.Value = "Quantity"

       MYDATA.Activate

      Do While Cells(r2, 1) <> ""
      ItemName = Cells(r2, 1).Value
      price = Cells(r2, 2).Value

      qty = Cells(r2, 3).Value

       p = Worksheets.Count
       For q = 1 To p
       If ActiveWorkbook.Worksheets(q).CodeName = UCase(ItemName) Then
       Worksheets(q).Activate
       erow = Worksheets(q).Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
       Cells(r2, 1).Value = ItemName
      Cells(r2, 2).Value = price
       Cells(r2, 3).Value = qty
       r2 = r2 + 1

        enter code here

       End If
       Next q
       MYDATA.Activate
        Loop
       Application.ScreenUpdating = True
    End Sub
</code>```

答:
A few comment:

Adding some indentation will make your code more understandable

Avoid using Range().Select then ActiveCell.Value=xxx, it will be very slow. Simply use Range().Value = xxx.  This applies to other entities such as worksheets, cells, etc.

Within your For...Next loop, r2 should be replaced by erow in order to copy your value to the other worksheets.

Title: Transfer Data to specific Excel Sheet

Body:
I am trying to transfer the data to specific sheet at last row but not able to data transferring but after some empty cells in sheet b c d e help needed to solve data is transferring in each sheet but not at next empty cell:

 Sub transferData()
      Application.ScreenUpdating = False
      'Dim myData As Worksheet, ItemA As Worksheet, ItemB As Worksheet, ItemC As Worksheet, ItemD As
       Worksheet, ItemE As Worksheet
      Dim ItemName As String
      Dim price As Long, qty As Long

      Dim r1 As Long, r2 As Long, erow As Long, lastrow As Long
      r1 = 2
      r2 = 2
      Sheets(Array("Sheet2", "Sheet3", "Sheet4", "Sheet5", "Sheet6")).Select
      Sheets("Sheet2").Activate
      Cells.Select
      Selection.ClearContents
      Sheets(Array("Sheet2", "Sheet3", "Sheet4", "Sheet5", "Sheet6")).Select
      Sheets("Sheet2").Activate
      range("A1").Select
      ActiveCell.Value = "Item"
      range("B1").Select
      ActiveCell.Value = "Price"
      range("C1").Select
      ActiveCell.Value = "Quantity"

       MYDATA.Activate

      Do While Cells(r2, 1) <> ""
      ItemName = Cells(r2, 1).Value
      price = Cells(r2, 2).Value

      qty = Cells(r2, 3).Value

       p = Worksheets.Count
       For q = 1 To p
       If ActiveWorkbook.Worksheets(q).CodeName = UCase(ItemName) Then
       Worksheets(q).Activate
       erow = Worksheets(q).Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
       Cells(r2, 1).Value = ItemName
      Cells(r2, 2).Value = price
       Cells(r2, 3).Value = qty
       r2 = r2 + 1

        enter code here

       End If
       Next q
       MYDATA.Activate
        Loop
       Application.ScreenUpdating = True
    End Sub


问:
Is there a way to accmplish the following loop without all the repetitive if statements?
The following is to fill out the values for a histogram:

```<code>for(index=0; index<256; index++) {
         while(1) {
             if(store[index] < bin_edge[1]) {
                 bins[0]++;
                 break;
             }
             if(store[index] < bin_edge[2]) {
                 bins[1]++;
                 break;
             }
             if(store[index] < bin_edge[3]) {
                 bins[2]++;
                 break;
             }
             if(store[index] < bin_edge[4]) {
                 bins[3]++;
                 break;
             }
             if(store[index] < bin_edge[5]) {
                 bins[4]++;
                 break;
             }
             if(store[index] < bin_edge[6]) {
                bins[5]++;
                break;
             }
             if(store[index] < bin_edge[7]) {
                bins[6]++;
                break;
             }
             if(store[index] < bin_edge[8]) {
                bins[7]++;
                break;
             }
             if(store[index] < bin_edge[9]) {
                bins[8]++;
                break;
             }
             if(store[index] < bin_edge[10]) {
                bins[9]++;
                break;
             }
             if(store[index] < bin_edge[11]) {
                bins[10]++;
                break;
             }
             if(store[index] < bin_edge[12]) {
                bins[11]++;
                break;
             }
             if(store[index] < bin_edge[13]) {
                bins[12]++;
                break;
             }
             if(store[index] < bin_edge[14]) {
                bins[13]++;
                break;
             }
             if(store[index] < bin_edge[15]) {
                bins[14]++;
                break;
             }
                bins[15]++;                       /* Default case */
                break;
         }
     }
</code>```

store is an integer array I am graphing, bins array is the graph values, bin_edge array holds the right hand edge of each bin. I admit to being a novice at the "c" language". This works but is clumsy and tedious to code.

答:
Add one more inner cycle and indicator whether case in non-default:</p>

```<code>for (index = 0; index < 256; index++) {
     int bin_incremented = 0;  // indicator
     for (int bin_index = 0; bin_index < 15; bin_index++) {
         if(store[index] < bin_edge[bin_index + 1]) {
             bins[bin_index]++;
             bin_incremented = 1;
             break;
         }
     }
     if (!bin_incremented) {
          bins[15]++;
     }
 }
</code>```

Body:
The following is to fill out the values for a histogram:

for(index=0; index<256; index++) {
         while(1) {
             if(store[index] < bin_edge[1]) {
                 bins[0]++;
                 break;
             }
             if(store[index] < bin_edge[2]) {
                 bins[1]++;
                 break;
             }
             if(store[index] < bin_edge[3]) {
                 bins[2]++;
                 break;
             }
             if(store[index] < bin_edge[4]) {
                 bins[3]++;
                 break;
             }
             if(store[index] < bin_edge[5]) {
                 bins[4]++;
                 break;
             }
             if(store[index] < bin_edge[6]) {
                bins[5]++;
                break;
             }
             if(store[index] < bin_edge[7]) {
                bins[6]++;
                break;
             }
             if(store[index] < bin_edge[8]) {
                bins[7]++;
                break;
             }
             if(store[index] < bin_edge[9]) {
                bins[8]++;
                break;
             }
             if(store[index] < bin_edge[10]) {
                bins[9]++;
                break;
             }
             if(store[index] < bin_edge[11]) {
                bins[10]++;
                break;
             }
             if(store[index] < bin_edge[12]) {
                bins[11]++;
                break;
             }
             if(store[index] < bin_edge[13]) {
                bins[12]++;
                break;
             }
             if(store[index] < bin_edge[14]) {
                bins[13]++;
                break;
             }
             if(store[index] < bin_edge[15]) {
                bins[14]++;
                break;
             }
                bins[15]++;                       /* Default case */
                break;
         }
     }

store is an integer array I am graphing, bins array is the graph values, bin_edge array holds the right hand edge of each bin. I admit to being a novice at the "c" language". This works but is clumsy and tedious to code.

Body:
Add one more inner cycle and indicator whether case in non-default:

for (index = 0; index < 256; index++) {
     int bin_incremented = 0;  // indicator
     for (int bin_index = 0; bin_index < 15; bin_index++) {
         if(store[index] < bin_edge[bin_index + 1]) {
             bins[bin_index]++;
             bin_incremented = 1;
             break;
         }
     }
     if (!bin_incremented) {
          bins[15]++;
     }
 }


问:
Microsoft Graph Expired Token
I'm trying to perform a request in Microsoft Graph like this one with Postman

https://graph.windows.net/<Tenant>/users?api-version=1.6

For the Authorization, I'm using Bearer. I'm retrieving the token manually and decoding it here https://jwt.io/ That way I know that it's well formed and that it's not expired yet.

However, I'm getting the following error on the response:

```<code>{
    "odata.error": {
        "code": "Authentication_ExpiredToken",
        "message": {
            "lang": "en",
            "value": "Your access token has expired. Please renew it before submitting the request."
        }
    }
}
</code>```

What am I doing wrong?

答:
You an try Get App-Only Access Token with the Microsoft Graph POST API:</p>

```<code>https://login.microsoftonline.com/{{TenantID}}/oauth2/v2.0/token
</code>```

Title: Microsoft Graph Expired Token

Body:
I'm trying to perform a request in Microsoft Graph like this one with Postman

https://graph.windows.net/<Tenant>/users?api-version=1.6

For the Authorization, I'm using Bearer. I'm retrieving the token manually and decoding it here https://jwt.io/ That way I know that it's well formed and that it's not expired yet.

However, I'm getting the following error on the response:

{
    "odata.error": {
        "code": "Authentication_ExpiredToken",
        "message": {
            "lang": "en",
            "value": "Your access token has expired. Please renew it before submitting the request."
        }
    }
}

What am I doing wrong?

Body:
You an try Get App-Only Access Token with the Microsoft Graph POST API:

https://login.microsoftonline.com/{{TenantID}}/oauth2/v2.0/token


答:
Replace all those if statements with a single for loop:

```<code>for (index = 0; index < 256; index++) {
    while (1) {
        for (size_t i = 1; i < 16; i++) {
            if (store[index] < bin_edge[i]) {
                bins[i - 1]++;
                goto outer_for;
            }
        }
        bins[15]++;
        break;
    }
    outer_for: ;
}
</code>```

Which can be simplified:

```<code>for (index = 0; index < 256; index++) {
    for (size_t i = 1; i < 16; i++) {
        if (store[index] < bin_edge[i]) {
            bins[i - 1]++;
            goto no_default;
        }
    }
    bins[15]++;
    no_default: ;
}
</code>```

Flag instead of goto:

```<code>for (index = 0; index < 256; index++) {
    int default_flag = 1;
    for (size_t i = 1; i < 16; i++) {
        if (store[index] < bin_edge[i]) {
            bins[i - 1]++;
            default_flag = 0;
            break;
        }
    }
    if (default_flag) {
        bins[15]++;
    }
}
</code>```

Title: Is there a way to accmplish the following loop without all the repetitive if statements?

Body:
Replace all those if statements with a single for loop:

for (index = 0; index < 256; index++) {
    while (1) {
        for (size_t i = 1; i < 16; i++) {
            if (store[index] < bin_edge[i]) {
                bins[i - 1]++;
                goto outer_for;
            }
        }
        bins[15]++;
        break;
    }
    outer_for: ;
}

Which can be simplified:

for (index = 0; index < 256; index++) {
    for (size_t i = 1; i < 16; i++) {
        if (store[index] < bin_edge[i]) {
            bins[i - 1]++;
            goto no_default;
        }
    }
    bins[15]++;
    no_default: ;
}

Flag instead of goto:

for (index = 0; index < 256; index++) {
    int default_flag = 1;
    for (size_t i = 1; i < 16; i++) {
        if (store[index] < bin_edge[i]) {
            bins[i - 1]++;
            default_flag = 0;
            break;
        }
    }
    if (default_flag) {
        bins[15]++;
    }
}


问:
Javascript - Multiple external files
I have a page which receives data from multiple sources and I need to create a set of handlers files to configure and display the different kinds of data. There could be 10-15 different kinds of data, each with it's own display logic. Each handler would be fairly large and not just 1 or two methods.

I'm trying to figure out what would be the best way deliver an application like this, the only two options I can see are:

1) Create an individual handler file
  for each type of data and externally load it in
  when the page loads. The problem with
  this is obviously including 10-15
  different javascript files probably
  isn't a smart idea. Would I need to compress all the handlers into one file, minify it and deliver it compressed?

or

2) Do all the configurations on the
  server before pushing the data to the
  user. Here the problem is that the
  JSON data pushed back could be very
  large (plus would include HTML) and put a lot of
  strain on the server.

Can anyone shed any light on how best to deliver complex javascript apps?

答:
Actually I prefer your first option.

Combine and minify these JavaScript source files into a single one and cache it let Web browsers cache them in the client, meaning that subsequent requests wouldn't need to download this combined-and-minified large file, boosting Web site's performance and reducing network traffic.

Title: Javascript - Multiple external files


问:
Return one word at a time
I have a function that takes in a text file and prints each word in the file one by one, each on a new line.

Here's the code that does what I said above:

```<code>def print_one_word():
    with open("test_script.txt", "r") as f:
        lines = f.readlines()
        word_current = []
        for line in lines:
            for word in line.split():
                word_current.append(word)
                print("".join(word_current))
                word_current.clear()
</code>```

Example, with specified text file content:

test_script.txt has the content (as formatted): stack, hello test python's name

The function print_one_word() will print the following to stdout (as formatted):

```<code>stack,
hello
test
python's
name
</code>```

The goal is to pass each word, one by one, into a second function that will perform some operations on it (Ex: capitalize the first letter). However, the most important part is that it sends to the second function only one word, and once the operation is performed, the next word is sent.

To do this, I've replaced print with return, after realizing that that wouldn't work (would only send one word), I tried using yield. However, it still only sends one word to the second function and then stops (it won't continue sending the following words).

I've also tried methods besides what I have currently (creating a list of one word, printing that list without formatting, and then clearing the list), such as simply printing word and so forth. Unfortunately, I got the same result; I could print each word one at a time, but not send to the second function each word one at a time.

Does anyone have any suggestions? Thanks in advance.

Edit, for clarity:

The second function takes in an argument, and I use the first function as the argument.

Example:

```<code>def operation(script):
    does some things
</code>```

operation(print_one_word())

答:
Here is an example of how to return a list and yield from functions, keep in mind yield returns a generator object and if you want to reuse yielded results you need to listify them:

def yield_words():
    with open("test_script.txt", "r") as f:
        lines = f.readlines()
        for line in lines:
            for word in line.split():
                yield word

def list_words():
    with open("test_script.txt", "r") as f:
        return [word
                for line in f.readlines()
                for word in line.split()]

def operation(prefix, word):
    print(f'{prefix} {word}')

yielded_words = list(yield_words())
listed_words = list_words()

for word in listed_words:
    operation('listed', word)

for word in yielded_words:
    operation('yielded', word)
```

<p>Output:</p>

```listed this
listed is
listed a
listed test
listed hello
listed there
yielded this
yielded is
yielded a
yielded test
yielded hello
yielded there
```

Title: Return one word at a time

Body:
I have a function that takes in a text file and prints each word in the file one by one, each on a new line.

Here's the code that does what I said above:

def print_one_word():
    with open("test_script.txt", "r") as f:
        lines = f.readlines()
        word_current = []
        for line in lines:
            for word in line.split():
                word_current.append(word)
                print("".join(word_current))
                word_current.clear()

Example, with specified text file content:

test_script.txt has the content (as formatted): stack, hello test python's name

The function print_one_word() will print the following to stdout (as formatted):

stack,
hello
test
python's
name

The goal is to pass each word, one by one, into a second function that will perform some operations on it (Ex: capitalize the first letter). However, the most important part is that it sends to the second function only one word, and once the operation is performed, the next word is sent.

To do this, I've replaced print with return, after realizing that that wouldn't work (would only send one word), I tried using yield. However, it still only sends one word to the second function and then stops (it won't continue sending the following words).

I've also tried methods besides what I have currently (creating a list of one word, printing that list without formatting, and then clearing the list), such as simply printing word and so forth. Unfortunately, I got the same result; I could print each word one at a time, but not send to the second function each word one at a time.

Does anyone have any suggestions? Thanks in advance.

Edit, for clarity:

The second function takes in an argument, and I use the first function as the argument.

Example:

def operation(script):
    does some things

operation(print_one_word())

Body:
Here is an example of how to return a list and yield from functions, keep in mind yield returns a generator object and if you want to reuse yielded results you need to listify them:

def yield_words():
    with open("test_script.txt", "r") as f:
        lines = f.readlines()
        for line in lines:
            for word in line.split():
                yield word

def list_words():
    with open("test_script.txt", "r") as f:
        return [word
                for line in f.readlines()
                for word in line.split()]

def operation(prefix, word):
    print(f'{prefix} {word}')

yielded_words = list(yield_words())
listed_words = list_words()

for word in listed_words:
    operation('listed', word)

for word in yielded_words:
    operation('yielded', word)

Output:

listed this
listed is
listed a
listed test
listed hello
listed there
yielded this
yielded is
yielded a
yielded test
yielded hello
yielded there


问:
unterminated dollar-quoted string postgress for creating function
this question might ask many here but I have tried their advice, but it still doesn't work on me, so I am going to ask this
I am trying to create a function where to trigger update_at automatically when i update something on tables
here is my syntax on .sql file:

```<code>CREATE OR REPLACE FUNCTION trigger_set_timestamp()
RETURNS TRIGGER AS $BODY$
BEGIN
  NEW.updated_at = NOW();
  RETURN NEW;
END;
$BODY$ LANGUAGE plpgsql;
</code>```

i always got error:

```<code>unterminated dollar-quoted string at or near "$BODY$
BEGIN
  NEW.updated_at = NOW()"
</code>```

I have tried to change it to $$ but still doesn't work,
I am using Go for this case with the migration tool called sql-migrate

can anyone has a solution for this? I have tried from yesterday and I get really stuck now for this

答:
It might come from your client, that does not recognize dollar quoting.

A typical workaround is to use regular single quotes. This requires double quoting all embedded single quotes, but fortunately you code has none, so:

```<code>CREATE OR REPLACE FUNCTION trigger_set_timestamp()
RETURNS TRIGGER AS '
BEGIN
  NEW.updated_at = NOW();
  RETURN NEW;
END;
' LANGUAGE plpgsql;
</code>```

Body:
this question might ask many here but I have tried their advice, but it still doesn't work on me, so I am going to ask this
I am trying to create a function where to trigger update_at automatically when i update something on tables
here is my syntax on .sql file:

CREATE OR REPLACE FUNCTION trigger_set_timestamp()
RETURNS TRIGGER AS $BODY$
BEGIN
  NEW.updated_at = NOW();
  RETURN NEW;
END;
$BODY$ LANGUAGE plpgsql;

i always got error:

unterminated dollar-quoted string at or near "$BODY$
BEGIN
  NEW.updated_at = NOW()"

I have tried to change it to $$ but still doesn't work,
I am using Go for this case with the migration tool called sql-migrate

can anyone has a solution for this? I have tried from yesterday and I get really stuck now for this

Body:
It might come from your client, that does not recognize dollar quoting.

A typical workaround is to use regular single quotes. This requires double quoting all embedded single quotes, but fortunately you code has none, so:

CREATE OR REPLACE FUNCTION trigger_set_timestamp()
RETURNS TRIGGER AS '
BEGIN
  NEW.updated_at = NOW();
  RETURN NEW;
END;
' LANGUAGE plpgsql;


问:
Full screen tkinter canvas python
Hello how can I make a full screen tkinter.Canvas? Can you help me? This is my code:

```<code>import tkinter
import datetime
import sys
import os

uvodcanvas = tkinter.Canvas(width=400,height=200,bg="white")
uvodcanvas.pack()

tkinter.mainloop()
</code>```

答:
You can set root.attributes to fullscreen.

The following example shows how to toggle from fullscreen to a sized window, and vice-versa, upon pressing the Escape key

```<code>import tkinter as tk

def toggle_fs(dummy=None):
    state = False if root.attributes('-fullscreen') else True
    root.attributes('-fullscreen', state)
    if not state:
        root.geometry('300x300+100+100')

root = tk.Tk()
tk.Canvas(root, bg='cyan').pack(expand=True, fill=tk.BOTH)
root.attributes('-fullscreen', True)

root.bind('<Escape>', toggle_fs)

root.mainloop()
</code>```

Title: Full screen tkinter canvas python

Body:
Hello how can I make a full screen tkinter.Canvas? Can you help me? This is my code:

import tkinter
import datetime
import sys
import os

uvodcanvas = tkinter.Canvas(width=400,height=200,bg="white")
uvodcanvas.pack()

tkinter.mainloop()

Body:
You can set root.attributes to fullscreen.

The following example shows how to toggle from fullscreen to a sized window, and vice-versa, upon pressing the Escape key

import tkinter as tk

def toggle_fs(dummy=None):
    state = False if root.attributes('-fullscreen') else True
    root.attributes('-fullscreen', state)
    if not state:
        root.geometry('300x300+100+100')

root = tk.Tk()
tk.Canvas(root, bg='cyan').pack(expand=True, fill=tk.BOTH)
root.attributes('-fullscreen', True)

root.bind('<Escape>', toggle_fs)

root.mainloop()


问:
Command is working on terminal but not giving syntax error in bash script
Below is my script placed in /usr/bin as I want to make it available globally

```<code>#!/bin/bash
cd /app/data/zips
rm -rf -i -v !(*.zip)
cd /app/cronscripts/import
> import_output.log
nohup ./import.sh > import_output.log & disown
</code>```

Everything in the above script is working perfectly fine apart from the below-given line, however, this command is working perfectly fine when running it from the terminal directly. It's for deleting all files and folders except .zip files in the directory

```<code>rm -rf -i -v !(*.zip)
</code>```

Whenever I try to run this script it gives me the following error.

```<code>/usr/bin/importdata.sh: line 3: syntax error near unexpected token `('
/usr/bin/importdata.sh: line 3: `rm -rf -i -v !(*.zip)'
</code>```

My which bash output is:

```<code>/bin/bash
</code>```

OS information:

```<code>Distributor ID: Ubuntu
Description:    Ubuntu 18.04.3 LTS
Release:        18.04
Codename:       bionic
</code>```

答:
In bash, !(pattern) is an extended glob pattern. Turn on the shell option which enables that:

```<code>shopt -s extglob
</code>```

shopt should appear on its own line at the start of the script, along with any other options which you may be relying on. See wooledge: https://mywiki.wooledge.org/glob#Options_which_change_globbing_behavior

extglob changes the way certain characters are parsed. It is necessary to have a newline (not just a semicolon) between shopt -s extglob and any subsequent commands to use it. You cannot enable extended globs inside a group command that uses them, because the entire block is parsed before the shopt is evaluated.

Body:
Below is my script placed in /usr/bin as I want to make it available globally

#!/bin/bash
cd /app/data/zips
rm -rf -i -v !(*.zip)
cd /app/cronscripts/import
> import_output.log
nohup ./import.sh > import_output.log & disown

Everything in the above script is working perfectly fine apart from the below-given line, however, this command is working perfectly fine when running it from the terminal directly. It's for deleting all files and folders except .zip files in the directory

rm -rf -i -v !(*.zip)

Whenever I try to run this script it gives me the following error.

/usr/bin/importdata.sh: line 3: syntax error near unexpected token `('
/usr/bin/importdata.sh: line 3: `rm -rf -i -v !(*.zip)'

My which bash output is:

/bin/bash

OS information:

Distributor ID: Ubuntu
Description:    Ubuntu 18.04.3 LTS
Release:        18.04
Codename:       bionic

Body:
In bash, !(pattern) is an extended glob pattern. Turn on the shell option which enables that:

shopt -s extglob

shopt should appear on its own line at the start of the script, along with any other options which you may be relying on. See wooledge: https://mywiki.wooledge.org/glob#Options_which_change_globbing_behavior

extglob changes the way certain characters are parsed. It is necessary to have a newline (not just a semicolon) between shopt -s extglob and any subsequent commands to use it. You cannot enable extended globs inside a group command that uses them, because the entire block is parsed before the shopt is evaluated.


答:
Can have an inner for loop that iterates over bin_edge:

```<code>for(index=0; index<256; index++) {
    for (bin_ix = 1; bin_ix < 16; bin_ix++) {
        if(store[index] < bin_edge[bin_ix]) {
            bins[bin_ix-1]++;
            break;
        }
    }
    if (bin_ix == 16) {
         bins[bin_ix-1]++;
    }
}
</code>```

Body:
Can have an inner for loop that iterates over bin_edge:

for(index=0; index<256; index++) {
    for (bin_ix = 1; bin_ix < 16; bin_ix++) {
        if(store[index] < bin_edge[bin_ix]) {
            bins[bin_ix-1]++;
            break;
        }
    }
    if (bin_ix == 16) {
         bins[bin_ix-1]++;
    }
}


问:
Element with that ID already exists in the database
I am working on a practice Spring Boot project that lists/adds/updates/deletes math problems from a mysql database. I am using Spring Boot with JPA to do the database operations. In my case, the db already has the problems and the button 'listproblems' returns all the buttons to a table. I can edit/delete without a problem. But when it comes to adding a new problem, I don't know how to add the new entry to the database. At this point, I don't know what to share but here is the current addProblem method:

```<code>//This is in the ProblemController.java on the server side application

@PostMapping("/post")
    public void addProduct(@RequestParam("cont") String pcont) {

        // Get a valid pid first
        Iterable<Problem> problist = probRepository.findAll();
        int min = 100000;
        int max = 0;
        int gap = 0;

        for (Problem myprod : problist) {
            if (myprod.getPid() < min) {
                min = myprod.getPid();
            }
            if (myprod.getPid() > max) {
                max = myprod.getPid();
            }
        }

        for (int i = min + 1; i < max; i++) {
            if (!probRepository.existsById(i)) {
                gap = i;
                break;
            }
        }

        if (gap == 0) {
            gap = max + 1;
        }

        System.out.println("max: " + max);

        max = max + 1;

        Problem prob = new Problem();
        prob.setPid(max);
        prob.setContent(pcont);
        probRepository.save(prob);
    }
</code>```

Problem.java Entity class

```<code>@Entity
public class Problem {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Integer pid;

    @Column(name = "content")
    private String content;

    public Integer getPid() {
        return pid;
    }

    public void setPid(Integer pid) {
        this.pid = pid;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

}
</code>```

This function is basically iterating through the items to find the maximum index, then incrementing the index by 1 to get the next index. But It still doesn't work.

Please let me know if you want to see anything in particular to help me understand this.

答:
It looks like you're explicitly overriding the id here
prob.setPid(max);

which is meaning that spring is not auto-generating the next id. Resulting in primary/foreign key constraint violations.

Body:
I am working on a practice Spring Boot project that lists/adds/updates/deletes math problems from a mysql database. I am using Spring Boot with JPA to do the database operations. In my case, the db already has the problems and the button 'listproblems' returns all the buttons to a table. I can edit/delete without a problem. But when it comes to adding a new problem, I don't know how to add the new entry to the database. At this point, I don't know what to share but here is the current addProblem method:

//This is in the ProblemController.java on the server side application

@PostMapping("/post")
    public void addProduct(@RequestParam("cont") String pcont) {

        // Get a valid pid first
        Iterable<Problem> problist = probRepository.findAll();
        int min = 100000;
        int max = 0;
        int gap = 0;

        for (Problem myprod : problist) {
            if (myprod.getPid() < min) {
                min = myprod.getPid();
            }
            if (myprod.getPid() > max) {
                max = myprod.getPid();
            }
        }

        for (int i = min + 1; i < max; i++) {
            if (!probRepository.existsById(i)) {
                gap = i;
                break;
            }
        }

        if (gap == 0) {
            gap = max + 1;
        }

        System.out.println("max: " + max);

        max = max + 1;

        Problem prob = new Problem();
        prob.setPid(max);
        prob.setContent(pcont);
        probRepository.save(prob);
    }

Problem.java Entity class

@Entity
public class Problem {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Integer pid;

    @Column(name = "content")
    private String content;

    public Integer getPid() {
        return pid;
    }

    public void setPid(Integer pid) {
        this.pid = pid;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

}

This function is basically iterating through the items to find the maximum index, then incrementing the index by 1 to get the next index. But It still doesn't work.

Please let me know if you want to see anything in particular to help me understand this.


问:
Encription with chances
I am new to Python so help. I want it to minus the chance if the password is wrong. Its stuck on 2 if I enter a wrong password</p>

```<code>while True:
    password = input("Password for activation ")
    chance = 3

    if password == "LUN":
            print("access granted")
            break

    if password != "LUN":
        wrong = chance - 1
        print("Try again. your chance is {0}".format(wrong))

    if chance == 0:
        break
</code>```

答: You have chance = 3 inside your while loop.  So every loop, chance goes back to being 3.

Title: Encription with chances

Body:
I am new to Python so help. I want it to minus the chance if the password is wrong. Its stuck on 2 if I enter a wrong password

while True:
    password = input("Password for activation ")
    chance = 3

    if password == "LUN":
            print("access granted")
            break

    if password != "LUN":
        wrong = chance - 1
        print("Try again. your chance is {0}".format(wrong))

    if chance == 0:
        break


问:
Install GitHub repo within GitHub Action Workflow
I'm trying to build a GitHub action workflow that involves installing dependencies that exist within other private reps. I've tried all sorts of permutations (I've kinda lost track now) and I can't get any of them working.

I've created a secret, stored within TOKEN_GITHUB that grants access to other repositories, so I can install correctly, as I believe the provided one is scoped to just the current rep.

Here's an example GitHub workflow file, that ultimately deploys multiple Lambdas via CDK, but I've excluded that for simplicity:

deploy.yml

```<code>name: Lint, Audit, Test & Deploy

on:
    push:
        branches: [master]

jobs:
    build:
        runs-on: ubuntu-latest
        if: "!contains(github.event.head_commit.message, 'ci skip')"

        steps:
            - uses: actions/checkout@v2
            - uses: actions/setup-node@v1
              with:
                  node-version: 12
            - name: getList Lambda
              run: |
                  cd lambdas
                  cd getList
                  npm ci
                  npm audit --production --audit-level=moderate
            - name: getItem Lambda
              run: |
                  cd lambdas
                  cd getItem
                  npm ci
                  npm audit --production --audit-level=moderate
            - name: saveItem Lambda
              run: |
                  cd lambdas
                  cd saveItem
                  npm ci
                  npm audit --production --audit-level=moderate

</code>```

So basically this fails during the npm ci for the getList lambda. I've had various errors such as:

npm ERR! git@github.com: Permission denied (publickey).
  npm ERR! fatal: Could not read from remote repository.

The package.json for my getList lambda looks like:

```<code>{
    "name": "getList",
    "version": "1.0.0",
    "description": "",
    "main": "index.js",
    "scripts": {
        "test": "jest"
    },
    "dependencies": {
        "dotenv": "^8.2.0",
        "mongodb": "^3.5.7",
        "get-db": "MyUsername/getDB"
    },
    "devDependencies": {
        "jest": "^26.0.1"
    }
}
</code>```

I've also tried including the username:token in the package.json file although I'm not comfortable having my token in their rather than a secret, but this didn't work anyway. I've also tried npm installing using an https path:

https://x-oauth-basic@github.com/MyUsername/getDB.git

with a gitconfig line of
git config --global url."https://${{secrets.TOKEN_GITHUB}}:x-oauth-basic@github.com/".insteadOf https://x-oauth-basic@github.com/

Can anyone see what I might be doing wrong here? The only thing that jumps to mind is maybe setting the gitconfig isn't shared across steps?

It is worth noting all my steps need a private dependency install which is why I split it up this way. Also pretty much everything I tried worked fine locally, it's just in actions it failed.

答:
The reason that your git config line doesn't work is because of the way authentication works with actions/checkout. Your attempt to change the authentication is being overridden by the credentials persisted by the action. I've bumped into other issues related to this before and you can read a bit about what I discovered here if you are interested.

You'll be glad to know there is an easy fix here. Just disable authentication being persisted in git config by actions/checkout.

```<code>      - uses: actions/checkout@v2
        with:
          persist-credentials: false
</code>```

Your package.json dependencies are fine as they are.

```<code>    "dependencies": {
        ...
        "get-db": "MyUsername/getDB"
    },
</code>```

Here is an example workflow. PAT is a repo scoped Personal Access Token. Note that the git config change persists between steps so you only need to run it once per job.

```<code>      - uses: actions/checkout@v2
        with:
          persist-credentials: false
      - uses: actions/setup-node@v1
        with:
          node-version: 12.x
      - run: git config --global url."https://${{ secrets.PAT }}@github.com/".insteadOf ssh://git@github.com/
      - run: npm ci
      ...
</code>```

Body:
I'm trying to build a GitHub action workflow that involves installing dependencies that exist within other private reps. I've tried all sorts of permutations (I've kinda lost track now) and I can't get any of them working.

I've created a secret, stored within TOKEN_GITHUB that grants access to other repositories, so I can install correctly, as I believe the provided one is scoped to just the current rep.

Here's an example GitHub workflow file, that ultimately deploys multiple Lambdas via CDK, but I've excluded that for simplicity:

deploy.yml

name: Lint, Audit, Test & Deploy

on:
    push:
        branches: [master]

jobs:
    build:
        runs-on: ubuntu-latest
        if: "!contains(github.event.head_commit.message, 'ci skip')"

        steps:
            - uses: actions/checkout@v2
            - uses: actions/setup-node@v1
              with:
                  node-version: 12
            - name: getList Lambda
              run: |
                  cd lambdas
                  cd getList
                  npm ci
                  npm audit --production --audit-level=moderate
            - name: getItem Lambda
              run: |
                  cd lambdas
                  cd getItem
                  npm ci
                  npm audit --production --audit-level=moderate
            - name: saveItem Lambda
              run: |
                  cd lambdas
                  cd saveItem
                  npm ci
                  npm audit --production --audit-level=moderate

So basically this fails during the npm ci for the getList lambda. I've had various errors such as:

npm ERR! git@github.com: Permission denied (publickey).
  npm ERR! fatal: Could not read from remote repository.

The package.json for my getList lambda looks like:

{
    "name": "getList",
    "version": "1.0.0",
    "description": "",
    "main": "index.js",
    "scripts": {
        "test": "jest"
    },
    "dependencies": {
        "dotenv": "^8.2.0",
        "mongodb": "^3.5.7",
        "get-db": "MyUsername/getDB"
    },
    "devDependencies": {
        "jest": "^26.0.1"
    }
}

I've also tried including the username:token in the package.json file although I'm not comfortable having my token in their rather than a secret, but this didn't work anyway. I've also tried npm installing using an https path:

https://x-oauth-basic@github.com/MyUsername/getDB.git

with a gitconfig line of
git config --global url."https://${{secrets.TOKEN_GITHUB}}:x-oauth-basic@github.com/".insteadOf https://x-oauth-basic@github.com/

Can anyone see what I might be doing wrong here? The only thing that jumps to mind is maybe setting the gitconfig isn't shared across steps?

It is worth noting all my steps need a private dependency install which is why I split it up this way. Also pretty much everything I tried worked fine locally, it's just in actions it failed.

Body:
The reason that your git config line doesn't work is because of the way authentication works with actions/checkout. Your attempt to change the authentication is being overridden by the credentials persisted by the action. I've bumped into other issues related to this before and you can read a bit about what I discovered here if you are interested.

You'll be glad to know there is an easy fix here. Just disable authentication being persisted in git config by actions/checkout.

      - uses: actions/checkout@v2
        with:
          persist-credentials: false

Your package.json dependencies are fine as they are.

    "dependencies": {
        ...
        "get-db": "MyUsername/getDB"
    },

Here is an example workflow. PAT is a repo scoped Personal Access Token. Note that the git config change persists between steps so you only need to run it once per job.

      - uses: actions/checkout@v2
        with:
          persist-credentials: false
      - uses: actions/setup-node@v1
        with:
          node-version: 12.x
      - run: git config --global url."https://${{ secrets.PAT }}@github.com/".insteadOf ssh://git@github.com/
      - run: npm ci
      ...


问:
How to update React context on successful login
When a user successfully logs in, I get a response of 200 from the server and then I want to update the variable in my ReactContext Provider. However, I am unable to do so as I can get the toggleAuth function inside render (as shown below) and cannot send to the function handleSubmit. The toggleAuth is a toggling function in AuthContext.

```<code>import {
    AuthContext
} from './AuthContext'
class SignIn extends React.Component {

    async handleSubmit(event) {
        // I get a 200 in status if it works
        const status = await res.status
        const json = await res.json();
        if (status === 200) {
            //I want to call toggleAuth here.

        }
    }

    static contextType = AuthContext;

    render() {
        const {
            toggleAuth
        } = this.context
        return (
            <Form onSubmit = {
                this.handleSubmit} >
            <div>

            <Form.Group controlId = "formBasicUsername" >
            <Form.Label> Username </Form.Label>
            <Form.Control required name = "username"
            type = "text"
            placeholder = "Enter username" / >
            </Form.Group>

            <Form.Group controlId = "formBasicPassword" >
            <Form.Label > Password < /Form.Label>
            <Form.Control required name = "password"
            type = "password"
            placeholder = "Enter password" / >
            </Form.Group>

            <Button variant = "warning"
            type = "submit" >
            Submit
            </Button>
            </div>
            </div>
            </Form>
        );
    }
}
</code>```

AuthContext:

```<code>import React, {
    Component,
    createContext
} from 'react';

export const AuthContext = createContext();

class AuthContextProvider extends Component {
    state = {
        isAuthenticated: false
    }
    toggleAuth = () => {
        this.setState({
            isAuthenticated: this.state.isAuthenticated
        })
    }

    render() {
        return ( <
            AuthContext.Provider value = {
                {
                    ...this.state,
                    toggleAuth: this.toggleAuth
                }
            } > {
                this.props.children
            } </AuthContext.Provider>
        )
    }
}

export default AuthContextProvider;
</code>```

答:
just make handleSubmit as arrow function so you can access this.context

```<code>handleSubmit = async (event) => {
    // I get a 200 in status if it works
    const status = await res.status
    const json = await res.json();
    if (status === 200) {
         const {toggleAuth} = this.context;
         toggleAuth();
    }
}
</code>```

Body:
When a user successfully logs in, I get a response of 200 from the server and then I want to update the variable in my ReactContext Provider. However, I am unable to do so as I can get the toggleAuth function inside render (as shown below) and cannot send to the function handleSubmit. The toggleAuth is a toggling function in AuthContext.

import {
    AuthContext
} from './AuthContext'
class SignIn extends React.Component {

    async handleSubmit(event) {
        // I get a 200 in status if it works
        const status = await res.status
        const json = await res.json();
        if (status === 200) {
            //I want to call toggleAuth here.

        }
    }

    static contextType = AuthContext;

    render() {
        const {
            toggleAuth
        } = this.context
        return (
            <Form onSubmit = {
                this.handleSubmit} >

            <Form.Group controlId = "formBasicUsername" >
            <Form.Label> Username </Form.Label>
            <Form.Control required name = "username"
            type = "text"
            placeholder = "Enter username" / >
            </Form.Group>

            <Form.Group controlId = "formBasicPassword" >
            <Form.Label > Password < /Form.Label>
            <Form.Control required name = "password"
            type = "password"
            placeholder = "Enter password" / >
            </Form.Group>

            <Button variant = "warning"
            type = "submit" >
            Submit
            </Button>

            </Form>
        );
    }
}

AuthContext:

import React, {
    Component,
    createContext
} from 'react';

export const AuthContext = createContext();

class AuthContextProvider extends Component {
    state = {
        isAuthenticated: false
    }
    toggleAuth = () => {
        this.setState({
            isAuthenticated: this.state.isAuthenticated
        })
    }

    render() {
        return ( <
            AuthContext.Provider value = {
                {
                    ...this.state,
                    toggleAuth: this.toggleAuth
                }
            } > {
                this.props.children
            } </AuthContext.Provider>
        )
    }
}

export default AuthContextProvider;

Body:
just make handleSubmit as arrow function so you can access this.context

handleSubmit = async (event) => {
    // I get a 200 in status if it works
    const status = await res.status
    const json = await res.json();
    if (status === 200) {
         const {toggleAuth} = this.context;
         toggleAuth();
    }
}