问:
How to underline a field on a form except text in the cell
I've been asked to make a form that has labels in cells (not underlined) followed by an underlined area that indicates where someone is supposed to put information. I don't personally like this design approach, but it is what I've been asked to do.

Something like this:

```<code>First Name: ________
Last Name: ________
Street Address: ________
</code>```

In other words, everything in the table cell is underlined except the label and the trailing space character.

The labels contain varying information and clearly will not align. However, all the underlines should right-align in their respective cells.

Here's a pen that hopefully illustrates what I'm trying to do. https://codepen.io/timmerbu/pen/pojMypE?editors=1100

html {
  font-size: 16px;
}

body {
  background: #9f9;
}

div {
  background: #fff;
  padding: 1rem;
  margin: auto;
  width: 200px;
}

table,
tr,
td {
  margin: 0;
  padding: 0;
  border-collapse: collapse;
}

table {
  width: 100%;
}

tr:nth-child(odd) {
  background: #fd4;
}

td {
  padding: 3px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <p>This is a test.</p>
  <table>
    <tbody>
      <tr>
        <td>Word: __________________</td>
      </tr>
      <tr>
        <td>Word word: ______________</td>
      </tr>
      <tr>
        <td>Word word word: _________</td>
      </tr>
      <tr>
        <td>Word word word word: ____</td>
      </tr>
    </tbody>
  </table>
  <p>End of test.</p>
</div></code>```

答:
simply use use css after ?

.underlined:after {
  content: '______________'
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>  <p class="underlined">First Name: </p>
  <p class="underlined">Last Name: </p>
  <p class="underlined">Street Address: </p></code>```

Body:
I've been asked to make a form that has labels in cells (not underlined) followed by an underlined area that indicates where someone is supposed to put information. I don't personally like this design approach, but it is what I've been asked to do.

Something like this:

First Name: ________
Last Name: ________
Street Address: ________

In other words, everything in the table cell is underlined except the label and the trailing space character.

The labels contain varying information and clearly will not align. However, all the underlines should right-align in their respective cells.

Here's a pen that hopefully illustrates what I'm trying to do. https://codepen.io/timmerbu/pen/pojMypE?editors=1100

html {
  font-size: 16px;
}

body {
  background: #9f9;
}

div {
  background: #fff;
  padding: 1rem;
  margin: auto;
  width: 200px;
}

table,
tr,
td {
  margin: 0;
  padding: 0;
  border-collapse: collapse;
}

table {
  width: 100%;
}

tr:nth-child(odd) {
  background: #fd4;
}

td {
  padding: 3px;
}

This is a test.

        Word: __________________

        Word word: ______________

        Word word word: _________

        Word word word word: ____

End of test.

Body:
simply use use css after ?

.underlined:after {
  content: '______________'
}

  <p class="underlined">First Name: </p>
  <p class="underlined">Last Name: </p>
  <p class="underlined">Street Address: </p>


来源: stackexchange

问:
Show popup if user selects a a sequence of options in dropdown menu
I have a multi-step signup form with multiple fields. Relevant to this question are fields asking for the user's country, whether they are employed/earn a steady salary and if they would like to pay for services in installments or upfront.

I would like to show a popup page in cases where the user selects the country as Nigeria, indicates that they are employed and that they would like to pay for services in installments.

So the popup form would occur the moment the person selects yes to wanting to pay in installments after having selected Nigeria as a country and indicating that they are employed.

Here is my html and what I have tried:

```<code>    <div class="row">
        {% if form.errors %}
            <div class="alert alert-error">
                <ul>
                    {% for error in form.non_field_errors %}
                        <li>{{ error }}</li>
                    {% endfor %}
                </ul>
            </div>
        {% endif %}
    </div>
    <div class="row">
        <div class="col-md-10 col-md-offset-1">
            <!--  -->
            <form  id="msform" method="post" action="" >
                {% csrf_token %}
                <input type="hidden" name="next" value="{{ next }}" class="form-control">
                <ul id="progressbar">
                    <li>More about you</li>
                    <li>Contact Details</li>
                </ul>
                <fieldset>
                    <h2 class="fs-title">More about you</h2>
                    {{form.city}}
                    <br>
                    <select name='country' required class="form-control my-2">
                        <option value="" disabled selected hidden>Country</option>
                        {% for value, name in form.fields.country.choices %}
                            <option value="{{value}}">{{name}}</option>
                        {% endfor %}
                    </select>
                    <input type="button" name="previous" class="previous action-button-previous" value="Previous" />
                    <input type="button" name="next" class="next action-button" value="Next" />
                </fieldset>
                <fieldset>
                    <h2 class="fs-title">Contact Details</h2>
                    <select name='installments' required class="form-control my-2">
                        <option value="" disabled selected hidden>Would you like to pay the $350 fee upfront or in installments?</option>
                        {% for value, name in form.fields.installments.choices %}
                            <option value="{{value}}">{{name}}</option>
                        {% endfor %}
                    </select>
                    <input type="button" name="previous" class="previous action-button-previous" value="Previous" />
                    <input type="submit"  class="submit action-button" value="Sign Up" />

                </fieldset>
            </form>
        </div>
    </div>
    {% endblock %}
{% block mainjs %}
{% endblock mainjs %}
{% block extrajs %}
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script src='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.3/jquery.easing.min.js'></script>
<script >

//jQuery time
var current_fs, next_fs, previous_fs; //fieldsets
var left, opacity, scale; //fieldset properties which we will animate
var animating; //flag to prevent quick multi-click glitches

$(".next").click(function(){
    if(animating) return false;
    animating = true;

    current_fs = $(this).parent();
    next_fs = $(this).parent().next();

    //activate next step on progressbar using the index of next_fs
    $("#progressbar li").eq($("fieldset").index(next_fs)).addClass("active");

    //show the next fieldset
    next_fs.show();
    //hide the current fieldset with style
    current_fs.animate({opacity: 0}, {
        step: function(now, mx) {
            //as the opacity of current_fs reduces to 0 - stored in "now"
            //1. scale current_fs down to 80%
            scale = 1 - (1 - now) * 0.
      ;
            //2. bring next_fs from the right(50%)
            left = (now * 50)+"%";
            //3. increase opacity of next_fs to 1 as it moves in
            opacity = 1 - now;
            current_fs.css({
        'transform': 'scale('+scale+')',
        'position': 'absolute'
      });
            next_fs.css({'left': left, 'opacity': opacity});
        },
        duration: 800,
        complete: function(){
            current_fs.hide();
            animating = false;
        },
        //this comes from the custom easing plugin
        easing: 'easeInOutBack'
    });
});

$(".previous").click(function(){
    if(animating) return false;
    animating = true;

    current_fs = $(this).parent();
    previous_fs = $(this).parent().prev();

    $("#progressbar li").eq($("fieldset").index(current_fs)).removeClass("active");
    previous_fs.show();
    current_fs.animate({opacity: 0}, {
        step: function(now, mx) {
            scale = 0.8 + (1 - now) * 0.2;
            left = ((1-now) * 50)+"%";
            opacity = 1 - now;
            current_fs.css({'left': left});
            previous_fs.css({'transform': 'scale('+scale+')', 'opacity': opacity});
        },
        duration: 800,
        complete: function(){
            current_fs.hide();
            animating = false;
        },
        easing: 'easeInOutBack'
    });
});

$(".submit").click(function(){
    return true;
})
</script>
<script>
    $("#installments").bind("change", function() {
        var value = this.value;
        switch (value) {
            case "installments":
            window.open("https://www.google.com/", "Google");
            break;
            }
    });
</script>
{% endblock extrajs %}
</code>```

To clarify this is the code I am trying to use to open the popup:

```<code><script>
    $("#installments").bind("change", function() {
        var value = this.value;
        switch (value) {
            case "installments":
            window.open("https://www.google.com/", "Google");
            break;
            }
    });
</script>
</code>```

These are the selection options in forms.py:

```<code>employed_choices = (
    ('yes', 'Yes'),
    ('no', 'No'),
)
installment_choices = (
    ('upfront', 'Upfront'),
    ('installments', 'Installments'),
)
country_choices = (
    ('kenya', 'Kenya'),
    ('nigeria', 'Nigeria'),
    ('south africa', 'South Africa'),
)
</code>```

Just to clarify the question one more time. I would like to open a popup if a user's selections meet these conditions:
i.) the user has selected Nigeria as a country choice
ii.) the user has selected yes for whether they are employed or not
and iii.) if the user finally selects installments for installment choices

答:
In your HTML there's missing the part where the user can choose between "Yes" and "No" for employment. Assuming that there are 2 radio buttons named "employed" the following works (just change "employed" in the code to whatever name you are using):</p>

```<code> $(document).ready(function() {
    $("input[name='employed'], select[name='country'], select[name='installments']").on("change", function() {
       let employed = $("input[name='employed']").val();
       let country = $("select[name='country']").val();
       let installment = $("select[name='installments']").val();
       if (employed == "yes" && country == "nigeria" && installment == "installments") {
          window.open("https://www.google.com/", "Google");
       }
    });
 });
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a multi-step signup form with multiple fields. Relevant to this question are fields asking for the user's country, whether they are employed/earn a steady salary and if they would like to pay for services in installments or upfront.

I would like to show a popup page in cases where the user selects the country as Nigeria, indicates that they are employed and that they would like to pay for services in installments.

So the popup form would occur the moment the person selects yes to wanting to pay in installments after having selected Nigeria as a country and indicating that they are employed.

Here is my html and what I have tried:

        {% if form.errors %}

                    {% for error in form.non_field_errors %}

{{ error }}

                    {% endfor %}

        {% endif %}

            <form  id="msform" method="post" action="" >
                {% csrf_token %}
                <input type="hidden" name="next" value="{{ next }}" class="form-control">

More about you

Contact Details

                <fieldset>

More about you

                    {{form.city}}

                    <select name='country' required class="form-control my-2">
                        <option value="" disabled selected hidden>Country</option>
                        {% for value, name in form.fields.country.choices %}
                            <option value="{{value}}">{{name}}</option>
                        {% endfor %}
                    </select>
                    <input type="button" name="previous" class="previous action-button-previous" value="Previous" />
                    <input type="button" name="next" class="next action-button" value="Next" />
                </fieldset>
                <fieldset>

Contact Details

                    <select name='installments' required class="form-control my-2">
                        <option value="" disabled selected hidden>Would you like to pay the $350 fee upfront or in installments?</option>
                        {% for value, name in form.fields.installments.choices %}
                            <option value="{{value}}">{{name}}</option>
                        {% endfor %}
                    </select>
                    <input type="button" name="previous" class="previous action-button-previous" value="Previous" />
                    <input type="submit"  class="submit action-button" value="Sign Up" />

                </fieldset>
            </form>

    {% endblock %}
{% block mainjs %}
{% endblock mainjs %}
{% block extrajs %}

{% endblock extrajs %}

To clarify this is the code I am trying to use to open the popup:

These are the selection options in forms.py:

employed_choices = (
    ('yes', 'Yes'),
    ('no', 'No'),
)
installment_choices = (
    ('upfront', 'Upfront'),
    ('installments', 'Installments'),
)
country_choices = (
    ('kenya', 'Kenya'),
    ('nigeria', 'Nigeria'),
    ('south africa', 'South Africa'),
)

Just to clarify the question one more time. I would like to open a popup if a user's selections meet these conditions:
i.) the user has selected Nigeria as a country choice
ii.) the user has selected yes for whether they are employed or not
and iii.) if the user finally selects installments for installment choices

Body:
In your HTML there's missing the part where the user can choose between "Yes" and "No" for employment. Assuming that there are 2 radio buttons named "employed" the following works (just change "employed" in the code to whatever name you are using):

 $(document).ready(function() {
    $("input[name='employed'], select[name='country'], select[name='installments']").on("change", function() {
       let employed = $("input[name='employed']").val();
       let country = $("select[name='country']").val();
       let installment = $("select[name='installments']").val();
       if (employed == "yes" && country == "nigeria" && installment == "installments") {
          window.open("https://www.google.com/", "Google");
       }
    });
 });


问:
Array PHP to javascript?
I am not sure whether I am asking a dumb question again or not but because I am really a newbie in javascript and php so do hope that someone can help me out on this.

The problem I am facing now is I now have a PHP array named "$horse_info" which consists of all info of horses. Now I will like to display selected horse info once at a time.  I was told to use javascript so that it does not need to query from server each time. But how should I do that?

Here is my code and output:

```<code><td> Horse </td>
    <td colspan=2>
        <select onChange='goto(this.options[this.selectedIndex].value)'>
        <?php foreach ($horse_info as $h_list) { ?>
            <option<?php if($h_list->HID==$horse_id){?> selected ="selected"<?php } ?>><?php echo $h_list->HNAME;?></option>
        <?php } ?>
        </select>
    </td>
</tr>

<tr>
    <td> Date Last Meeting </td>
    <td colspan= 2>  </td> <!-- this is where I will need to show last meeting of each horse once at a time. -->
</code>```

答:
Why don't you output the php array as a javascript object using json_encode?  It will convert the array to a JS object.

Assuming that you are using inline PHP, you could do something like this in your script tag.

```<code>var jsObj = <?php echo json_encode($arrayName);?>;
</code>```

ContentLicense: CC BY-SA 3.0

Title: Array PHP to javascript?

Body:
I am not sure whether I am asking a dumb question again or not but because I am really a newbie in javascript and php so do hope that someone can help me out on this.

The problem I am facing now is I now have a PHP array named "$horse_info" which consists of all info of horses. Now I will like to display selected horse info once at a time.  I was told to use javascript so that it does not need to query from server each time. But how should I do that?

Here is my code and output:

 Horse

        <select onChange='goto(this.options[this.selectedIndex].value)'>
        <?php foreach ($horse_info as $h_list) { ?>
            <option<?php if($h_list->HID==$horse_id){?> selected ="selected"<?php } ?>><?php echo $h_list->HNAME;?></option>
        <?php } ?>
        </select>

     Date Last Meeting

Body:
Why don't you output the php array as a javascript object using json_encode?  It will convert the array to a JS object.

Assuming that you are using inline PHP, you could do something like this in your script tag.

var jsObj = <?php echo json_encode($arrayName);?>;


问:
How to allocate array of pointers for strings by malloc in C?
I have this struct in C
Example:

```<code>typedef struct
{
    const char * array_pointers_of_strings [ 30 ];
    // etc.
} message;
</code>```

I need copy this array_pointers_of_strings to new array for sort strings. I need only copy adress.

```<code>while ( i < 30 )
{
   new_array [i] = new_message->array_pointers_of_strings [i];
   // I need only copy adress of strings
}
</code>```

My question is: How to allocate new_array [i] by malloc() for only adress of strings?

答:
is it mandatory for you to use Malloc? Because Calloc is the function in the C Standard Library which will make the job:

"The calloc() function allocates memory for an array of nmemb elements of size bytes each and returns a pointer to the allocated memory". (Source: here)

I'm just creating a hash table and it has an array of pointers to nodes, and a easy way to do it is this:

```<code>hash_table_t *hash_table_create(unsigned long int size){
hash_table_t *ptr = NULL;

ptr = malloc(sizeof(hash_table_t) * 1);
if (ptr == NULL)
    return (NULL);

ptr->array = calloc(size, sizeof(hash_node_t *)); #HERE
if (ptr->array == NULL)
    return (NULL);
ptr->size = size;
return (ptr);}
</code>```

Hope it works for you guys!

calloc c

Body:
I have this struct in C
Example:

typedef struct
{
    const char * array_pointers_of_strings [ 30 ];
    // etc.
} message;

I need copy this array_pointers_of_strings to new array for sort strings. I need only copy adress.

while ( i < 30 )
{
   new_array [i] = new_message->array_pointers_of_strings [i];
   // I need only copy adress of strings
}

My question is: How to allocate new_array [i] by malloc() for only adress of strings?

Body:
is it mandatory for you to use Malloc? Because Calloc is the function in the C Standard Library which will make the job:

"The calloc() function allocates memory for an array of nmemb elements of size bytes each and returns a pointer to the allocated memory". (Source: here)

I'm just creating a hash table and it has an array of pointers to nodes, and a easy way to do it is this:

hash_table_t *hash_table_create(unsigned long int size){
hash_table_t *ptr = NULL;

ptr = malloc(sizeof(hash_table_t) * 1);
if (ptr == NULL)
    return (NULL);

ptr->array = calloc(size, sizeof(hash_node_t *)); #HERE
if (ptr->array == NULL)
    return (NULL);
ptr->size = size;
return (ptr);}

Hope it works for you guys!

calloc c


问:
Pandas rank valus in rows of DataFrame
Learning Python. I have a dataframe like this

```<code>     cand1    cand2    cand3
0    40.0900  39.6700  36.3700
1    44.2800  44.2800  35.4200
2    43.0900  51.2200  46.3500
3    35.7200  55.2700  36.4700
</code>```

and I want to rank each row according to the value of the columns, so that I get

```<code>     cand1    cand2    cand3
0    1        2        3
1    1        1        3
2    1        3        2
3    3        1        2
</code>```

I have now

```<code>    for index, row in df.iterrows():
        df.loc['Rank'] = df.loc[index].rank(ascending=False).astype(int)
        print (df)
</code>```

However, this keeps on repeating the whole dataframe. Note also the special case in row 2, where two values are the same.

Suggestion appreciated

答:
Use df.rank instead of series rank

```<code>df_rank = df.rank(axis=1, ascending=False, method='min').astype(int)

Out[165]:
   cand1  cand2  cand3
0      1      2      3
1      1      1      3
2      3      1      2
3      3      1      2
</code>```

Title: Pandas rank valus in rows of DataFrame

Body:
Learning Python. I have a dataframe like this

     cand1    cand2    cand3
0    40.0900  39.6700  36.3700
1    44.2800  44.2800  35.4200
2    43.0900  51.2200  46.3500
3    35.7200  55.2700  36.4700

and I want to rank each row according to the value of the columns, so that I get

     cand1    cand2    cand3
0    1        2        3
1    1        1        3
2    1        3        2
3    3        1        2

I have now

    for index, row in df.iterrows():
        df.loc['Rank'] = df.loc[index].rank(ascending=False).astype(int)
        print (df)

However, this keeps on repeating the whole dataframe. Note also the special case in row 2, where two values are the same.

Suggestion appreciated

Body:
Use df.rank instead of series rank

df_rank = df.rank(axis=1, ascending=False, method='min').astype(int)

Out[165]:
   cand1  cand2  cand3
0      1      2      3
1      1      1      3
2      3      1      2
3      3      1      2


问:
With Combine, how to deallocate the Subscription after a network request
If you use Combine for network requests with URLSession, then you need to save the Subscription (aka, the AnyCancellable) - otherwise it gets immediately deallocated, which cancels the network request. Later, when the network response has been processed, you want to deallocate the subscription, because keeping it around would be a waste of memory.

Below is some code that does this. It's kind of awkward, and it may not even be correct. I can imagine a race condition where network request could start and complete on another thread before sub is set to the non-nil value.

Is there a nicer way to do this?

```<code>class SomeThing {
    var subs = Set<AnyCancellable>()
    func sendNetworkRequest() {
        var request: URLRequest = ...
        var sub: AnyCancellable? = nil
        sub = URLSession.shared.dataTaskPublisher(for: request)
            .map(\.data)
            .decode(type: MyResponse.self, decoder: JSONDecoder())
            .sink(
                receiveCompletion: { completion in
                    self.subs.remove(sub!)
                },
                receiveValue: { response in ... }
            }
        subs.insert(sub!)
</code>```

答:
Below is some code that does this. It's kind of awkward, and it may not even be correct. I can imagine a race condition where network request could start and complete on another thread before sub is set to the non-nil value.

Danger! Swift.Set is not thread safe. If you want to access a Set from two different threads, it is up to you to serialize the accesses so they don't overlap.

What is possible in general (although not perhaps with URLSession.DataTaskPublisher) is that a publisher emits its signals synchronously, before the sink operator even returns. This is how Just, Result.Publisher, Publishers.Sequence, and others behave. So those produce the problem you're describing, without involving thread safety.

Now, how to solve the problem? If you don't think you want to actually be able to cancel the subscription, then you can avoid creating an AnyCancellable at all by using Subscribers.Sink instead of the sink operator:

```<code>        URLSession.shared.dataTaskPublisher(for: request)
            .map(\.data)
            .decode(type: MyResponse.self, decoder: JSONDecoder())
            .subscribe(Subscribers.Sink(
                receiveCompletion: { completion in ... },
                receiveValue: { response in ... }
            ))
</code>```

Combine will clean up the subscription and the subscriber after the subscription completes (with either .finished or .failure).

But what if you do want to be able to cancel the subscription? Maybe sometimes your SomeThing gets destroyed before the subscription is complete, and you don't need the subscription to complete in that case. Then you do want to create an AnyCancellable and store it in an instance property, so that it gets cancelled when SomeThing is destroyed.

In that case, set a flag indicating that the sink won the race, and check the flag before storing the AnyCancellable.

```<code>        var sub: AnyCancellable? = nil
        var isComplete = false
        sub = URLSession.shared.dataTaskPublisher(for: request)
            .map(\.data)
            .decode(type: MyResponse.self, decoder: JSONDecoder())
            // This ensures thread safety, if the subscription is also created
            // on DispatchQueue.main.
            .receive(on: DispatchQueue.main)
            .sink(
                receiveCompletion: { [weak self] completion in
                    isComplete = true
                    if let theSub = sub {
                        self?.subs.remove(theSub)
                    }
                },
                receiveValue: { response in ... }
            }
        if !isComplete {
            subs.insert(sub!)
        }
</code>```

Body:
If you use Combine for network requests with URLSession, then you need to save the Subscription (aka, the AnyCancellable) - otherwise it gets immediately deallocated, which cancels the network request. Later, when the network response has been processed, you want to deallocate the subscription, because keeping it around would be a waste of memory.

Below is some code that does this. It's kind of awkward, and it may not even be correct. I can imagine a race condition where network request could start and complete on another thread before sub is set to the non-nil value.

Is there a nicer way to do this?

class SomeThing {
    var subs = Set<AnyCancellable>()
    func sendNetworkRequest() {
        var request: URLRequest = ...
        var sub: AnyCancellable? = nil
        sub = URLSession.shared.dataTaskPublisher(for: request)
            .map(\.data)
            .decode(type: MyResponse.self, decoder: JSONDecoder())
            .sink(
                receiveCompletion: { completion in
                    self.subs.remove(sub!)
                },
                receiveValue: { response in ... }
            }
        subs.insert(sub!)

Body:
Below is some code that does this. It's kind of awkward, and it may not even be correct. I can imagine a race condition where network request could start and complete on another thread before sub is set to the non-nil value.

Danger! Swift.Set is not thread safe. If you want to access a Set from two different threads, it is up to you to serialize the accesses so they don't overlap.

What is possible in general (although not perhaps with URLSession.DataTaskPublisher) is that a publisher emits its signals synchronously, before the sink operator even returns. This is how Just, Result.Publisher, Publishers.Sequence, and others behave. So those produce the problem you're describing, without involving thread safety.

Now, how to solve the problem? If you don't think you want to actually be able to cancel the subscription, then you can avoid creating an AnyCancellable at all by using Subscribers.Sink instead of the sink operator:

        URLSession.shared.dataTaskPublisher(for: request)
            .map(\.data)
            .decode(type: MyResponse.self, decoder: JSONDecoder())
            .subscribe(Subscribers.Sink(
                receiveCompletion: { completion in ... },
                receiveValue: { response in ... }
            ))

Combine will clean up the subscription and the subscriber after the subscription completes (with either .finished or .failure).

But what if you do want to be able to cancel the subscription? Maybe sometimes your SomeThing gets destroyed before the subscription is complete, and you don't need the subscription to complete in that case. Then you do want to create an AnyCancellable and store it in an instance property, so that it gets cancelled when SomeThing is destroyed.

In that case, set a flag indicating that the sink won the race, and check the flag before storing the AnyCancellable.

        var sub: AnyCancellable? = nil
        var isComplete = false
        sub = URLSession.shared.dataTaskPublisher(for: request)
            .map(\.data)
            .decode(type: MyResponse.self, decoder: JSONDecoder())
            // This ensures thread safety, if the subscription is also created
            // on DispatchQueue.main.
            .receive(on: DispatchQueue.main)
            .sink(
                receiveCompletion: { [weak self] completion in
                    isComplete = true
                    if let theSub = sub {
                        self?.subs.remove(theSub)
                    }
                },
                receiveValue: { response in ... }
            }
        if !isComplete {
            subs.insert(sub!)
        }


问:
Unable to use discord.py and quarry at the same time
I am trying to make a discord bot using discord.py that uses the library quarry to interact with a minecraft server.

Unfortunately once I start the discord bot using bot.run() I can't start the reactor for quarry with reactor.run().

I've looked around including aiostream and asyncio but I can't find a solution. I also looked into twisted as quarry uses that.

EDIT: Including current code.

```<code>import asyncio
from twisted.internet import asyncioreactor

asyncioreactor.install(asyncio.get_event_loop())

from quarry.net.client import SpawningClientProtocol, ClientFactory
from quarry.net.auth import Profile
from discord.ext import commands

profile = Profile.from_credentials("email", "password")
bot = commands.Bot(command_prefix=">")

async def start():
    loop = asyncio.get_event_loop()

    loop.create_task(bot.start("token"))

    client = MinecraftBotFactory(profile)

    client.connect("creative.starlegacy.net", 25565)

class MinecraftBotProtocol(SpawningClientProtocol):
    pass

class MinecraftBotFactory(ClientFactory):
    protocol = MinecraftBotProtocol

asyncio.get_event_loop().create_task(start())
asyncio.get_event_loop().run_forever()
</code>```

答:
bot.run() is a blocking call, meaning that it stops the execution of the program until it is done. Try an alternative like await bot.start():

import asyncio
from discord.ext import tasks

async def start_bot():
    await bot.start('my_token_goes_here')
@tasks.loop(count=1)
async def login_quarry():
    # login to quarry here #
login_quarry.start()

# put any code you need BEFORE this:
asyncio.get_event_loop().run_until_complete(start_bot())
```

<p>In python 3.7 and up, there is a simpler alternative:</p>

<pre class="lang-py prettyprint-override"><code>import asyncio
from discord.ext import tasks

async def start_bot():
    await bot.start('my_token_goes_here')
@tasks.loop(count=1)
async def login_quarry():
    # login to quarry here #
login_quarry.start()

# put any code you need BEFORE this:
asyncio.run(start_bot())
</code>```

Body:
I am trying to make a discord bot using discord.py that uses the library quarry to interact with a minecraft server.

Unfortunately once I start the discord bot using bot.run() I can't start the reactor for quarry with reactor.run().

I've looked around including aiostream and asyncio but I can't find a solution. I also looked into twisted as quarry uses that.

EDIT: Including current code.

import asyncio
from twisted.internet import asyncioreactor

asyncioreactor.install(asyncio.get_event_loop())

from quarry.net.client import SpawningClientProtocol, ClientFactory
from quarry.net.auth import Profile
from discord.ext import commands

profile = Profile.from_credentials("email", "password")
bot = commands.Bot(command_prefix=">")

async def start():
    loop = asyncio.get_event_loop()

    loop.create_task(bot.start("token"))

    client = MinecraftBotFactory(profile)

    client.connect("creative.starlegacy.net", 25565)

class MinecraftBotProtocol(SpawningClientProtocol):
    pass

class MinecraftBotFactory(ClientFactory):
    protocol = MinecraftBotProtocol

asyncio.get_event_loop().create_task(start())
asyncio.get_event_loop().run_forever()

Body:
bot.run() is a blocking call, meaning that it stops the execution of the program until it is done. Try an alternative like await bot.start():

import asyncio
from discord.ext import tasks

async def start_bot():
    await bot.start('my_token_goes_here')
@tasks.loop(count=1)
async def login_quarry():
    # login to quarry here #
login_quarry.start()

# put any code you need BEFORE this:
asyncio.get_event_loop().run_until_complete(start_bot())

In python 3.7 and up, there is a simpler alternative:

import asyncio
from discord.ext import tasks

async def start_bot():
    await bot.start('my_token_goes_here')
@tasks.loop(count=1)
async def login_quarry():
    # login to quarry here #
login_quarry.start()

# put any code you need BEFORE this:
asyncio.run(start_bot())


问:
How to rotate an object around a vector in POV-Ray?
I find it surprisingly difficult to find the rotation that moves an object from one given point to another one in POV-Ray.

Geometrically it's simple enough to find: I calculate the distance Dist from the origin to the target point PointT (green), and create Point0 at <Dist, 0, 0> (blue). Then I calculate from Point0 and PointT the angle between them and the perpendicular to them. The rotation by AngleD around Perp moves Point0 to Point1 = PointT.

In POV-Ray I can use vaxis_rotate to calculate Point1. But I want to actually rotate an object (which, of course, will not be a sphere), and I don't see an obvious way to do this. I tried rotate -AngleD*Perp, but that gives a slightly different result (red).

How can I do to an object, what vaxis_rotate does to a point?

```<code>#declare PointT = <2, 2, 2>;

#declare Dist = VDist(<0, 0, 0>, PointT);
#declare Point0 = <Dist, 0, 0>;
#declare AngleD = VAngleD(PointT, Point0);
#declare Perp = VPerp_To_Plane(PointT, Point0);
#declare Point1 = vaxis_rotate(Point0, Perp, -AngleD);

sphere{Point0, R   pigment{color Blue}  }
sphere{Point1, R   pigment{color Green}  }

sphere{
    Point0, R
    rotate -AngleD*Perp
    pigment{color Red}
}
</code>```

答: So, for short, let be a unit vector, and suppose you want a rotation about it by alpha degrees. Then v1 v2 v3 *alpha WILL NOT yield the desired transformation. It is a bug, a serious one.</p>

Body:
I find it surprisingly difficult to find the rotation that moves an object from one given point to another one in POV-Ray.

Geometrically it's simple enough to find: I calculate the distance Dist from the origin to the target point PointT (green), and create Point0 at <Dist, 0, 0> (blue). Then I calculate from Point0 and PointT the angle between them and the perpendicular to them. The rotation by AngleD around Perp moves Point0 to Point1 = PointT.

In POV-Ray I can use vaxis_rotate to calculate Point1. But I want to actually rotate an object (which, of course, will not be a sphere), and I don't see an obvious way to do this. I tried rotate -AngleD*Perp, but that gives a slightly different result (red).

How can I do to an object, what vaxis_rotate does to a point?

#declare PointT = <2, 2, 2>;

#declare Dist = VDist(<0, 0, 0>, PointT);
#declare Point0 = <Dist, 0, 0>;
#declare AngleD = VAngleD(PointT, Point0);
#declare Perp = VPerp_To_Plane(PointT, Point0);
#declare Point1 = vaxis_rotate(Point0, Perp, -AngleD);

sphere{Point0, R   pigment{color Blue}  }
sphere{Point1, R   pigment{color Green}  }

sphere{
    Point0, R
    rotate -AngleD*Perp
    pigment{color Red}
}


问:
Proximity Monitoring on the iPhone without blacking out the screen?
I'm able to detect proximity on the iPhone SDK, but the screen blacks out whenever the proximity state is triggered.

is there a way I can prevent the proximity sensor from blacking out the screen, but still monitor a proximity sensor's state?

Thanks!

答: You could normally override the -(void)proximityStateChanged:(BOOL) changed method and do your thing in there, still getting the changed BOOL state.

ContentLicense: CC BY-SA 2.5


问:
Capturing consecutive year ranges with break in hive
I am trying to write a query in hive to return a data with the year range if they are consecutive years along with the gap year, if there are gaps between the years.

I am trying to get my head around it, but can't seem to find the logic to achieve the results. How does hive logic work for this. Please help.

Input

```<code>group_no            year
1111                2003
1111                2004
1111                2005
1111                2008
1111                2010
1111                2011
1111                2012
2222                2015
3333                2014
3333                2015
3333                2017
3333                2019
4444                2010
4444                2012
</code>```

Output:

```<code>group_no year
1111    [2003-2005,2008,2010-2012]
2222    [2015]
3333    [2014-2015,2017,2019]
4444    [2010,2012]
</code>```

答:
This is a gaps and islands problem, where you want to group together rows having the same group_no and whose years are consecutive.

Here is an approach using window functions: the idea is to use the difference between row_number() and year to build the groups. You can then aggregate once for each group of adjacent record, and finally aggregate by group_no.

```<code>select
    group_no,
    collect_list(
        case when min_year <> max_year
            then concat(min_year, '-', max_year)
            else min_year
        end
    ) year
from (
    select group_no, min(year) min_year, max(year) max_year
    from (
        select  t.*, row_number() over(partition by group_no order by year) rn
        from mytable t
    ) t
    group by group_no, year - rn
) t
group by group_no
</code>```

I am unsure whether hive supports order by in collect_list() as an aggregate function - it seems like it does when used as a window function though, so this might be better:

```<code>select distinct
    group_no,
    collect_list(
        case when min_year <> max_year
            then concat(min_year, '-', max_year)
            else min_year
        end
    ) over(
        partition by group_no
        order by min_year
        rows between unbounded preceding and unbounded following
    ) year
from (
    select group_no, min(year) min_year, max(year) max_year
    from (
        select  t.*, row_number() over(partition by group_no order by year) rn
        from mytable t
    ) t
    group by group_no, year - rn
) t
</code>```

Body:
I am trying to write a query in hive to return a data with the year range if they are consecutive years along with the gap year, if there are gaps between the years.

I am trying to get my head around it, but can't seem to find the logic to achieve the results. How does hive logic work for this. Please help.

Input

group_no            year
1111                2003
1111                2004
1111                2005
1111                2008
1111                2010
1111                2011
1111                2012
2222                2015
3333                2014
3333                2015
3333                2017
3333                2019
4444                2010
4444                2012

Output:

group_no year
1111    [2003-2005,2008,2010-2012]
2222    [2015]
3333    [2014-2015,2017,2019]
4444    [2010,2012]

Body:
This is a gaps and islands problem, where you want to group together rows having the same group_no and whose years are consecutive.

Here is an approach using window functions: the idea is to use the difference between row_number() and year to build the groups. You can then aggregate once for each group of adjacent record, and finally aggregate by group_no.

select
    group_no,
    collect_list(
        case when min_year <> max_year
            then concat(min_year, '-', max_year)
            else min_year
        end
    ) year
from (
    select group_no, min(year) min_year, max(year) max_year
    from (
        select  t.*, row_number() over(partition by group_no order by year) rn
        from mytable t
    ) t
    group by group_no, year - rn
) t
group by group_no

I am unsure whether hive supports order by in collect_list() as an aggregate function - it seems like it does when used as a window function though, so this might be better:

select distinct
    group_no,
    collect_list(
        case when min_year <> max_year
            then concat(min_year, '-', max_year)
            else min_year
        end
    ) over(
        partition by group_no
        order by min_year
        rows between unbounded preceding and unbounded following
    ) year
from (
    select group_no, min(year) min_year, max(year) max_year
    from (
        select  t.*, row_number() over(partition by group_no order by year) rn
        from mytable t
    ) t
    group by group_no, year - rn
) t


问:
2 Tables 1 Result, a tricky SQL
After many years lurking stackoverflow, I finally have the need to come to you dev gurus in search for a little bit of help.

Context:

I'm a developer that is playing with information that I extract from SAP.
I'm extracting the info and I'm creating two tables in memory using H2 database.

My tables look like this:

```<code>CREATE TABLE USERS
(
     SID VARCHAR(255),
     SYSID VARCHAR(5),
     MANDT VARCHAR(3),
     BNAME VARCHAR(255),
     GLTGV DATE,
     GLTGB DATE,
     USTYP VARCHAR(2),
     LOCNT VARCHAR(3),
     UFLAG VARCHAR(3),
     TRDAT DATE,
     LTIME VARCHAR(255),
     CLASS VARCHAR(255),
     PWDCHGDATE DATE,
     PROFILE VARCHAR(255)
)

CREATE TABLE ROLES
(
     SID VARCHAR(255),
     SYSID VARCHAR(5),
     MANDT VARCHAR(3),
     UNAME VARCHAR(255),
     AGR_NAME VARCHAR(255)
)
</code>```

Do not worry about the definitions, I'm just "dummyfing" them for the sake of simplicity.

One user can have none or many roles. How do you tie them together?

Well SYSID, MANDT and BNAME from table USERS have to match the content of the ROLES table, columns SYSID, MANDT and UNAME (all of the same type)

So I have created this query

```<code>SELECT DISTINCT
    t1.SID,
    t1.SYSID,
    t1.MANDT,
    t1.BNAME,
    t1.GLTGV,
    t1.GLTGB,
    t1.USTYP,
    t1.LOCNT,
    t1.UFLAG,
    t1.TRDAT,
    t1.LTIME,
    t1.CLASS,
    t1.PWDCHGDATE,
    t1.PROFILE
FROM
    USERS AS t1,
    ROLES AS t2
WHERE
    t1.SYSID = t2.SYSID AND
    t1.MANDT = t2.MANDT AND
    t1.BNAME = t2.UNAME AND
    (t2.AGR_NAME = "ZTEST_ROLE")
</code>```

which works well as long as I only query by one ROLE.

To query for more than one role, I do

```<code>SELECT DISTINCT
    t1.SID,
    t1.SYSID,
    t1.MANDT,
    t1.BNAME,
    t1.GLTGV,
    t1.GLTGB,
    t1.USTYP,
    t1.LOCNT,
    t1.UFLAG,
    t1.TRDAT,
    t1.LTIME,
    t1.CLASS,
    t1.PWDCHGDATE,
    t1.PROFILE
FROM
    USERS AS t1,
    ROLES AS t2
WHERE
    t1.SYSID = t2.SYSID AND
    t1.MANDT = t2.MANDT AND
    t1.BNAME = t2.UNAME AND
    (t2.AGR_NAME = "ZTEST_ROLE" OR t2.AGR_NAME = "ZTEST_ROLE2")
</code>```

It also works. You would use this query if you want to get info from all the users that either have ZTEST_ROLE or ZTEST_ROLE2 as roles.

Now, here is my problem, I cannot make it to work if I want to select all the users that have both roles ZTEST_ROLE and ZTEST_ROLE2. my query always return 0 rows

Here is the query that I'm using

```<code>SELECT DISTINCT
    t1.SID,
    t1.SYSID,
    t1.MANDT,
    t1.BNAME,
    t1.GLTGV,
    t1.GLTGB,
    t1.USTYP,
    t1.LOCNT,
    t1.UFLAG,
    t1.TRDAT,
    t1.LTIME,
    t1.CLASS,
    t1.PWDCHGDATE,
    t1.PROFILE
FROM
    USERS AS t1,
    ROLES AS t2
WHERE
    t1.SYSID = t2.SYSID AND
    t1.MANDT = t2.MANDT AND
    t1.BNAME = t2.UNAME AND
    (t2.AGR_NAME = "ZTEST_ROLE" AND t2.AGR_NAME = "ZTEST_ROLE")
</code>```

I have been playing with this for a while and I do not see where my error is

For convenience and in case you want to try this online, I have been using https://sqliteonline.com/

I appreciate your help and my apologies for the long post

答:
I think that a solution like this is what you are looking for.. I might be done in diffrent ways but I think you get the idea.</p>

```<code>SELECT DISTINCT
    t1.SID,
    t1.SYSID,
    t1.MANDT,
    t1.BNAME,
    t1.GLTGV,
    t1.GLTGB,
    t1.USTYP,
    t1.LOCNT,
    t1.UFLAG,
    t1.TRDAT,
    t1.LTIME,
    t1.CLASS,
    t1.PWDCHGDATE,
    t1.PROFILE
FROM (
    SELECT DISTINCT
        t1.SID,
        t1.SYSID,
        t1.MANDT,
        t1.BNAME,
        t1.GLTGV,
        t1.GLTGB,
        t1.USTYP,
        t1.LOCNT,
        t1.UFLAG,
        t1.TRDAT,
        t1.LTIME,
        t1.CLASS,
        t1.PWDCHGDATE,
        t1.PROFILE,
        case when t2.AGR_NAME = "ZTEST_ROLE" then 1 else 0 end as t2t1,
        case when t2.AGR_NAME = "ZTEST_ROLE2" then 1 else 0 end as t2t2
    FROM
        USERS AS t1,
        ROLES AS t2
    WHERE
        t1.SYSID = t2.SYSID AND
        t1.MANDT = t2.MANDT AND
        t1.BNAME = t2.UNAME AND
        (t2.AGR_NAME = "ZTEST_ROLE" or t2.AGR_NAME = "ZTEST_ROLE")
    ) as tmp
    WHERE t2t1 = 1 and t2t2 = 1
</code>```

Title: 2 Tables 1 Result, a tricky SQL

Body:
After many years lurking stackoverflow, I finally have the need to come to you dev gurus in search for a little bit of help.

Context:

I'm a developer that is playing with information that I extract from SAP.
I'm extracting the info and I'm creating two tables in memory using H2 database.

My tables look like this:

CREATE TABLE USERS
(
     SID VARCHAR(255),
     SYSID VARCHAR(5),
     MANDT VARCHAR(3),
     BNAME VARCHAR(255),
     GLTGV DATE,
     GLTGB DATE,
     USTYP VARCHAR(2),
     LOCNT VARCHAR(3),
     UFLAG VARCHAR(3),
     TRDAT DATE,
     LTIME VARCHAR(255),
     CLASS VARCHAR(255),
     PWDCHGDATE DATE,
     PROFILE VARCHAR(255)
)

CREATE TABLE ROLES
(
     SID VARCHAR(255),
     SYSID VARCHAR(5),
     MANDT VARCHAR(3),
     UNAME VARCHAR(255),
     AGR_NAME VARCHAR(255)
)

Do not worry about the definitions, I'm just "dummyfing" them for the sake of simplicity.

One user can have none or many roles. How do you tie them together?

Well SYSID, MANDT and BNAME from table USERS have to match the content of the ROLES table, columns SYSID, MANDT and UNAME (all of the same type)

So I have created this query

SELECT DISTINCT
    t1.SID,
    t1.SYSID,
    t1.MANDT,
    t1.BNAME,
    t1.GLTGV,
    t1.GLTGB,
    t1.USTYP,
    t1.LOCNT,
    t1.UFLAG,
    t1.TRDAT,
    t1.LTIME,
    t1.CLASS,
    t1.PWDCHGDATE,
    t1.PROFILE
FROM
    USERS AS t1,
    ROLES AS t2
WHERE
    t1.SYSID = t2.SYSID AND
    t1.MANDT = t2.MANDT AND
    t1.BNAME = t2.UNAME AND
    (t2.AGR_NAME = "ZTEST_ROLE")

which works well as long as I only query by one ROLE.

To query for more than one role, I do

SELECT DISTINCT
    t1.SID,
    t1.SYSID,
    t1.MANDT,
    t1.BNAME,
    t1.GLTGV,
    t1.GLTGB,
    t1.USTYP,
    t1.LOCNT,
    t1.UFLAG,
    t1.TRDAT,
    t1.LTIME,
    t1.CLASS,
    t1.PWDCHGDATE,
    t1.PROFILE
FROM
    USERS AS t1,
    ROLES AS t2
WHERE
    t1.SYSID = t2.SYSID AND
    t1.MANDT = t2.MANDT AND
    t1.BNAME = t2.UNAME AND
    (t2.AGR_NAME = "ZTEST_ROLE" OR t2.AGR_NAME = "ZTEST_ROLE2")

It also works. You would use this query if you want to get info from all the users that either have ZTEST_ROLE or ZTEST_ROLE2 as roles.

Now, here is my problem, I cannot make it to work if I want to select all the users that have both roles ZTEST_ROLE and ZTEST_ROLE2. my query always return 0 rows

Here is the query that I'm using

SELECT DISTINCT
    t1.SID,
    t1.SYSID,
    t1.MANDT,
    t1.BNAME,
    t1.GLTGV,
    t1.GLTGB,
    t1.USTYP,
    t1.LOCNT,
    t1.UFLAG,
    t1.TRDAT,
    t1.LTIME,
    t1.CLASS,
    t1.PWDCHGDATE,
    t1.PROFILE
FROM
    USERS AS t1,
    ROLES AS t2
WHERE
    t1.SYSID = t2.SYSID AND
    t1.MANDT = t2.MANDT AND
    t1.BNAME = t2.UNAME AND
    (t2.AGR_NAME = "ZTEST_ROLE" AND t2.AGR_NAME = "ZTEST_ROLE")

I have been playing with this for a while and I do not see where my error is

For convenience and in case you want to try this online, I have been using https://sqliteonline.com/

I appreciate your help and my apologies for the long post

Body:
I think that a solution like this is what you are looking for.. I might be done in diffrent ways but I think you get the idea.

SELECT DISTINCT
    t1.SID,
    t1.SYSID,
    t1.MANDT,
    t1.BNAME,
    t1.GLTGV,
    t1.GLTGB,
    t1.USTYP,
    t1.LOCNT,
    t1.UFLAG,
    t1.TRDAT,
    t1.LTIME,
    t1.CLASS,
    t1.PWDCHGDATE,
    t1.PROFILE
FROM (
    SELECT DISTINCT
        t1.SID,
        t1.SYSID,
        t1.MANDT,
        t1.BNAME,
        t1.GLTGV,
        t1.GLTGB,
        t1.USTYP,
        t1.LOCNT,
        t1.UFLAG,
        t1.TRDAT,
        t1.LTIME,
        t1.CLASS,
        t1.PWDCHGDATE,
        t1.PROFILE,
        case when t2.AGR_NAME = "ZTEST_ROLE" then 1 else 0 end as t2t1,
        case when t2.AGR_NAME = "ZTEST_ROLE2" then 1 else 0 end as t2t2
    FROM
        USERS AS t1,
        ROLES AS t2
    WHERE
        t1.SYSID = t2.SYSID AND
        t1.MANDT = t2.MANDT AND
        t1.BNAME = t2.UNAME AND
        (t2.AGR_NAME = "ZTEST_ROLE" or t2.AGR_NAME = "ZTEST_ROLE")
    ) as tmp
    WHERE t2t1 = 1 and t2t2 = 1


问:
Number of ways to change a coin
I am doing this question https://leetcode.com/problems/coin-change-2/. I need to find number of ways to change a coin given the amount and denominations.

I came up with the solution to try every possibility of denominations for an amount and caching it if its already seen before.

```<code>class Solution(object):
    def change(self, amount, coins):
        """
        :type amount: int
        :type coins: List[int]
        :rtype: int
        """
        dp = [[-1]*len(coins)]*(amount+1)
        def changeHelper(amount, coins, index):
            if amount == 0:
                return 1

            if index<0:
                return 0

            if dp[amount][index]!=-1:
                return dp[amount][index]

            total_ways = 0
            if amount>=coins[index]:
                total_ways = changeHelper(amount-coins[index], coins, index)

            total_ways += changeHelper(amount, coins, index-1)

            dp[amount][index] = total_ways
            return dp[amount][index]

        return changeHelper(amount, coins, len(coins)-1)
</code>```

I am getting wrong answer and have spent hours figuring out the bug.

```<code>Test case
500
[1,2,5]
expected answer 12701
my output 301
</code>```

答:
Here's the DP you need.</p>

```<code>def change(amount, coins):
        dp = [0] * (amount + 1)
        dp[0] = 1
        for x in range(amount + 1):
            for c in coins:
                if c > x: continue
                dp[x] += dp[x - c]
        return dp[amount]
</code>```

Title: Number of ways to change a coin

Body:
I am doing this question https://leetcode.com/problems/coin-change-2/. I need to find number of ways to change a coin given the amount and denominations.

I came up with the solution to try every possibility of denominations for an amount and caching it if its already seen before.

class Solution(object):
    def change(self, amount, coins):
        """
        :type amount: int
        :type coins: List[int]
        :rtype: int
        """
        dp = [[-1]*len(coins)]*(amount+1)
        def changeHelper(amount, coins, index):
            if amount == 0:
                return 1

            if index<0:
                return 0

            if dp[amount][index]!=-1:
                return dp[amount][index]

            total_ways = 0
            if amount>=coins[index]:
                total_ways = changeHelper(amount-coins[index], coins, index)

            total_ways += changeHelper(amount, coins, index-1)

            dp[amount][index] = total_ways
            return dp[amount][index]

        return changeHelper(amount, coins, len(coins)-1)

I am getting wrong answer and have spent hours figuring out the bug.

Test case
500
[1,2,5]
expected answer 12701
my output 301

Body:
Here's the DP you need.

def change(amount, coins):
        dp = [0] * (amount + 1)
        dp[0] = 1
        for x in range(amount + 1):
            for c in coins:
                if c > x: continue
                dp[x] += dp[x - c]
        return dp[amount]


问:
Express creating 404 error on non-index route with nginx proxy but not on local
I have an express server that handles my routing and am using nginx to proxy my requests. However, when accessing a route that is not '/', I receive a 404 error from express. I've looked at a lot of other answers so far and they all seem to be 404s from nginx and are resolved by removing try_files $uri $uri/ =404;, but that's not the case for me. I also see a lot of questions about 404-ing for static files with express/nginx, but I don't think that's necessarily the case here. Rather, I'm unsure how my situation relates to those questions since I'm templating through pug with express.

The error I get is:

```<code>NotFoundError: Not Found
    at /root/my-app/app.js:27:10
    at Layer.handle [as handle_request] (/root/my-app/node_modules/express/lib/router/layer.js:95:5)
    at trim_prefix (/root/my-app/node_modules/express/lib/router/index.js:317:13)
    at /root/my-app/node_modules/express/lib/router/index.js:284:7
    at Function.process_params (/root/my-app/node_modules/express/lib/router/index.js:335:12)
    at next (/root/my-app/node_modules/express/lib/router/index.js:275:10)
    at /root/my-app/node_modules/express/lib/router/index.js:635:15
    at next (/root/my-app/node_modules/express/lib/router/index.js:260:14)
    at Function.handle (/root/my-app/node_modules/express/lib/router/index.js:174:3)
    at router (/root/my-app/node_modules/express/lib/router/index.js:47:12)
</code>```

which is triggered by (in app.js):

```<code>app.use((req, res, next) => {
    next(createError(404));
});
</code>```

My router looks like:

```<code>router.get('/', (req, res) => {
    res.render('index');                        // does not give me 404 error
});

router.get('/other-route', (req, res) => {
    res.render('other-route-pug-file');         // gives me 404 error
});
</code>```

My nginx config looks like:

```<code>server {
    listen 80;
    server_name example.com;
    rewrite ^/(.*) https://example.com/$1 permanent;
}

server {
    listen 443 ssl default_server;
    listen [::]:443 ssl default_server;
    # ssl config details

    server_name example.com www.example.com;

    location / {
        proxy_pass http://localhost:3000; # the port that my express server is listening to
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
}
</code>```

So this error only shows up when I route my app through nginx into my domain. On localhost I can see /other-route fine. I'm also just unsure how I can go about debugging something like this since I can't really console.log() to somewhere easily and I'm pretty new to proxying through nginx, so any help in either area/solving this is much appreciated. Thanks!

答: I fixed my problem. I am using an inefficient method to sync my code on the server and github. I did not yarn install in my directory after I cloned it the since the first time. I don't know why I didn't just pull inside my directory on the server. I'm not necessarily sure why other parts of my project were working, but that fixed it for me. Thanks for the help!

Body:
I have an express server that handles my routing and am using nginx to proxy my requests. However, when accessing a route that is not '/', I receive a 404 error from express. I've looked at a lot of other answers so far and they all seem to be 404s from nginx and are resolved by removing try_files $uri $uri/ =404;, but that's not the case for me. I also see a lot of questions about 404-ing for static files with express/nginx, but I don't think that's necessarily the case here. Rather, I'm unsure how my situation relates to those questions since I'm templating through pug with express.

The error I get is:

NotFoundError: Not Found
    at /root/my-app/app.js:27:10
    at Layer.handle [as handle_request] (/root/my-app/node_modules/express/lib/router/layer.js:95:5)
    at trim_prefix (/root/my-app/node_modules/express/lib/router/index.js:317:13)
    at /root/my-app/node_modules/express/lib/router/index.js:284:7
    at Function.process_params (/root/my-app/node_modules/express/lib/router/index.js:335:12)
    at next (/root/my-app/node_modules/express/lib/router/index.js:275:10)
    at /root/my-app/node_modules/express/lib/router/index.js:635:15
    at next (/root/my-app/node_modules/express/lib/router/index.js:260:14)
    at Function.handle (/root/my-app/node_modules/express/lib/router/index.js:174:3)
    at router (/root/my-app/node_modules/express/lib/router/index.js:47:12)

which is triggered by (in app.js):

app.use((req, res, next) => {
    next(createError(404));
});

My router looks like:

router.get('/', (req, res) => {
    res.render('index');                        // does not give me 404 error
});

router.get('/other-route', (req, res) => {
    res.render('other-route-pug-file');         // gives me 404 error
});

My nginx config looks like:

server {
    listen 80;
    server_name example.com;
    rewrite ^/(.*) https://example.com/$1 permanent;
}

server {
    listen 443 ssl default_server;
    listen [::]:443 ssl default_server;
    # ssl config details

    server_name example.com www.example.com;

    location / {
        proxy_pass http://localhost:3000; # the port that my express server is listening to
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
}

So this error only shows up when I route my app through nginx into my domain. On localhost I can see /other-route fine. I'm also just unsure how I can go about debugging something like this since I can't really console.log() to somewhere easily and I'm pretty new to proxying through nginx, so any help in either area/solving this is much appreciated. Thanks!


问:
Dynamically create UI5-Controls with properties from json-string. Problems with events in json-string
in my actual development i create an app which needs to create UI5-Controls dynmaically at runtime from an database customizing-table.

As an simplyfied example when creating an input field:

```<code>var loProObj = JSON.parse(pData.TEMPLATE);
var loInp = new sap.m.Input(loProObj);

</code>```

This works so far for most of the properties when pData.TEMPLATE is a JSON-String.
But it does not work for Event-Method Properties.Then i get an error like: Uncaught TypeError: I.fFunction.call is not a function

So as simpliefied JSON-String for code above take this string:

```<code>'{"value":"{boundVariable}","change":"onChange"}'
</code>```

When this string is parsed (remember its a string comming from a database to be parsed to JSON, not a JSON-Object), onChange is still a string. this might be the problem. But what can i do to transport the information about the eventhandler methods in a json-string?

Any hints would be great

Kind regards
MatHay

答:
As suggested in the comment, there are public APIs by which controls can be created from string values.

Given: UI definition in XML format

Creating view from XML string

Creating control from XML string

Given: view definition in JSON format

Same as XMLView.create but using JSONView.create instead:

sap.ui.getCore().attachInit(() => sap.ui.require([
  "sap/ui/core/mvc/JSONView",
], JSONView => JSONView.create({
  definition: `{
    "Type":"sap.ui.core.mvc.JSONView",
    "content": [
      {
        "Type":"sap.m.Input",
        "width": "12rem",
        "placeholder": "Edit me",
        "change": "alert('Sample global handler triggered')"
      }
    ]
  }`,
}).then(view => view.placeAt("content"))));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script id="sap-ui-bootstrap"
  src="https://openui5.hana.ondemand.com/resources/sap-ui-core.js"
  data-sap-ui-libs="sap.ui.core, sap.m"
  data-sap-ui-async="true"
  data-sap-ui-theme="sap_fiori_3"
  data-sap-ui-compatversion="edge"
  data-sap-ui-xx-waitfortheme="init"
></script>
<body id="content" class="sapUiBody sapUiSizeCompact"></body></code>```

Doc: JSON View

Unfortunately, there is no factory function for creating a single control out of JSON text yet (Currently, only XML, JS, and HTML are supported). But if it's really required, here is my attempt:

sap.ui.getCore().attachInit(() => sap.ui.require([
  "sap/m/Input",
  "sap/ui/model/json/JSONModel",
], (Input, JSONModel) => {
  "use strict";

  const myController = {
    onInit: function() {
      createControlViaJSON({
        definition: `{
          "placeholder": "{/myPlaceHolder}",
          "change": "onInputChange",
          "width": "12rem"
        }`,
        TargetControl: Input,
        controller: this,
      }).setModel(new JSONModel({ myPlaceHolder: "Edit me" }))
        .addStyleClass("sapUiTinyMargin")
        .placeAt("content");
    },
    onInputChange: function(event) {
      alert(`You typed: ${event.getParameter("value")}`);
    },
  };

  // Emulating controller initialization:
  myController.onInit();

  // Could be a separate module:
  function createControlViaJSON({ id, definition, TargetControl, controller }) {
    // Very primitive sample! Ignoring aggregations, associations, etc..
    const control = new TargetControl(id);
    JSON.parse(definition, (key, value) => {
      if (typeof controller[value] == "function") {
        control.applySettings({
          [key]: [controller[value], controller],
        });
      } else if (key) {
        control.applySettings({
          [key]: value,
        });
      }
    });
    return control;
  }

}));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script id="sap-ui-bootstrap"
  src="https://openui5.hana.ondemand.com/resources/sap-ui-core.js"
  data-sap-ui-libs="sap.ui.core, sap.m"
  data-sap-ui-async="true"
  data-sap-ui-theme="sap_fiori_3"
  data-sap-ui-compatversion="edge"
  data-sap-ui-xx-waitfortheme="init"
></script>
<body id="content" class="sapUiBody sapUiSizeCompact"></body></code>```

Body:
in my actual development i create an app which needs to create UI5-Controls dynmaically at runtime from an database customizing-table.

As an simplyfied example when creating an input field:

var loProObj = JSON.parse(pData.TEMPLATE);
var loInp = new sap.m.Input(loProObj);

This works so far for most of the properties when pData.TEMPLATE is a JSON-String.
But it does not work for Event-Method Properties.Then i get an error like: Uncaught TypeError: I.fFunction.call is not a function

So as simpliefied JSON-String for code above take this string:

'{"value":"{boundVariable}","change":"onChange"}'

When this string is parsed (remember its a string comming from a database to be parsed to JSON, not a JSON-Object), onChange is still a string. this might be the problem. But what can i do to transport the information about the eventhandler methods in a json-string?

Any hints would be great

Kind regards
MatHay

Body:
As suggested in the comment, there are public APIs by which controls can be created from string values.

Given: UI definition in XML format

Creating view from XML string

Creating control from XML string

Given: view definition in JSON format

Same as XMLView.create but using JSONView.create instead:

sap.ui.getCore().attachInit(() => sap.ui.require([
  "sap/ui/core/mvc/JSONView",
], JSONView => JSONView.create({
  definition: `{
    "Type":"sap.ui.core.mvc.JSONView",
    "content": [
      {
        "Type":"sap.m.Input",
        "width": "12rem",
        "placeholder": "Edit me",
        "change": "alert('Sample global handler triggered')"
      }
    ]
  }`,
}).then(view => view.placeAt("content"))));

<script id="sap-ui-bootstrap"
  src="https://openui5.hana.ondemand.com/resources/sap-ui-core.js"
  data-sap-ui-libs="sap.ui.core, sap.m"
  data-sap-ui-async="true"
  data-sap-ui-theme="sap_fiori_3"
  data-sap-ui-compatversion="edge"
  data-sap-ui-xx-waitfortheme="init"
></script>
<body id="content" class="sapUiBody sapUiSizeCompact"></body>

Doc: JSON View

Unfortunately, there is no factory function for creating a single control out of JSON text yet (Currently, only XML, JS, and HTML are supported). But if it's really required, here is my attempt:

sap.ui.getCore().attachInit(() => sap.ui.require([
  "sap/m/Input",
  "sap/ui/model/json/JSONModel",
], (Input, JSONModel) => {
  "use strict";

  const myController = {
    onInit: function() {
      createControlViaJSON({
        definition: `{
          "placeholder": "{/myPlaceHolder}",
          "change": "onInputChange",
          "width": "12rem"
        }`,
        TargetControl: Input,
        controller: this,
      }).setModel(new JSONModel({ myPlaceHolder: "Edit me" }))
        .addStyleClass("sapUiTinyMargin")
        .placeAt("content");
    },
    onInputChange: function(event) {
      alert(`You typed: ${event.getParameter("value")}`);
    },
  };

  // Emulating controller initialization:
  myController.onInit();

  // Could be a separate module:
  function createControlViaJSON({ id, definition, TargetControl, controller }) {
    // Very primitive sample! Ignoring aggregations, associations, etc..
    const control = new TargetControl(id);
    JSON.parse(definition, (key, value) => {
      if (typeof controller[value] == "function") {
        control.applySettings({
          [key]: [controller[value], controller],
        });
      } else if (key) {
        control.applySettings({
          [key]: value,
        });
      }
    });
    return control;
  }

}));

<script id="sap-ui-bootstrap"
  src="https://openui5.hana.ondemand.com/resources/sap-ui-core.js"
  data-sap-ui-libs="sap.ui.core, sap.m"
  data-sap-ui-async="true"
  data-sap-ui-theme="sap_fiori_3"
  data-sap-ui-compatversion="edge"
  data-sap-ui-xx-waitfortheme="init"
></script>
<body id="content" class="sapUiBody sapUiSizeCompact"></body>


问:
UIColor does not match standard RGB color wheel?
Hue in UIColor is not the same as a standard RGB color wheel. What I mean by that is, two opposing colors on a color wheel will match (i.e., yellow and purple), but if you take two opposing colors in UIColor, for example:

Color 1: Hue 0.45

Color 2: Hue 0.95

they don't match. Is there any way to find the opposite color in the spectrum through UIColor?

答: I answered a question just like this not all that long ago. The gist of it is that there are lots of different color models. Even in your question, you seem to be thinking about two different models: yellow and purple may be complimentary in a red-yellow-blue model, but not so much in a red-green-blue model.</p>


问:
Flutter PageView prevent swiping when there's no widget
On iOS the user can swipe right or left even when there's no item there, it rebounds but the user can still see part of a white screen. Is there anyway to prevent this?</p>

答:
This is related to the physics your widget is using. Try this on your PageView:</p>

```<code>  physics: BouncingScrollPhysics(),
</code>```

Body:
This is related to the physics your widget is using. Try this on your PageView:

  physics: BouncingScrollPhysics(),


问:
Laravel 7 Error message: 'SQLSTATE[23000]: Integrity constraint violation: 19 NOT NULL constraint failed: profiles.url

UPDATE: PROBLEM SOLVED!

I'm refreshing my Laravel skills (using version 7.13.0), following the freecodecamp.org tutorial, here: https://www.youtube.com/watch?v=ImtZ5yENzgE&t=11889s (1:21:49 to 1:22:50). When I get to the task of adding a profile manually with php artisan tinker, like I did on the frontend, it can not save. The database is sqlite.

THIS IS THE FULL ERROR:

Illuminate/Database/QueryException with message 'SQLSTATE[23000]:
  Integrity constraint violation: 19 NOT NULL constraint failed:
  profiles.url (SQL: insert into "profiles" ("title", "description",
  "user_id", "updated_at", "created_at") values (Cool Title,
  Description, 1, 2020-05-29 18:41:02, 2020-05-29 18:41:02))'

My function in profiles_table.php in database\migrations folder seems OK. It is this:

```<code>public function up()
    {
        Schema::create('profiles', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->unsignedBigInteger('user_id');
            $table->string('title')->nullable();
            $table->text('description')->nullable();
            $table->string('url')->nullable();
            $table->timestamps();

            $table->index('user_id');

        });
    }
</code>```

The Profile.php model function is:

```<code>public function user()
{
    return $this->belongsTo(User::class);
}
</code>```

And the User.php model function is:

```<code>public function profile()
{
    return $this->hasOne(Profile::class);
}
</code>```

So, in the terminal, after entering php artisan tinker, I filled in the following before it failed to save:

```<code>>>> $profile = new \App\Profile();
=> App\Profile {#3056}
>>> $profile->title = 'Cool Title';
=> "Cool Title"
>>> $profile->description = 'Description';
=> "Description"
>>> $profile->user_id = 1;
=> 1
>>> $profile->save();
</code>```

EDIT: this is the controller file ProfilesController.php, if it helps to solve the problem:

```<code><?php

namespace App\Http\Controllers;

use \App\User;
use Illuminate\Http\Request;

class ProfilesController extends Controller
{
    public function index($user)
    {
        $user = User::find($user);

        return view('home', [
            'user' => $user,
        ]);
    }
}
</code>```

All parts went OK, and after I typed the SAVE - it showed the error above. Therefore I can't continue ahead to show the new profile made manualy.

I searched up Google and looked here for answers, like in this question and that question. It didn't solve my problem, and others I think are not as relevant.

What should I do in order to fix it?

Solution

Tanks to @mrhn, adding a new null table + installing composer require doctrine/dbal as suggested here: https://stackoverflow.com/a/37533819/12952748.

答:
The problem is your database does not allow the column url to be null. Your code is fine and nothing wrong with it, thou it seems you have maybe ran the migration and changed columns definition after.

In Laravel migrations only run once and secures the database has the same structure across systems. For getting the field nullable make a new migration.

```<code>php artisan make:migration url_nullable
</code>```

For you new migration file, add the following migration. Which simply tells the migration to update url to be a string and nullable.

```<code>Schema::table('profiles', function (Blueprint $table) {
    $table->string('url')->nullable()->change();
});
</code>```

After that run your migration and you database should be up to date.

```<code>php artisan migrate
</code>```

Body:
UPDATE: PROBLEM SOLVED!

I'm refreshing my Laravel skills (using version 7.13.0), following the freecodecamp.org tutorial, here: https://www.youtube.com/watch?v=ImtZ5yENzgE&t=11889s (1:21:49 to 1:22:50). When I get to the task of adding a profile manually with php artisan tinker, like I did on the frontend, it can not save. The database is sqlite.

THIS IS THE FULL ERROR:

Illuminate/Database/QueryException with message 'SQLSTATE[23000]:
  Integrity constraint violation: 19 NOT NULL constraint failed:
  profiles.url (SQL: insert into "profiles" ("title", "description",
  "user_id", "updated_at", "created_at") values (Cool Title,
  Description, 1, 2020-05-29 18:41:02, 2020-05-29 18:41:02))'

My function in profiles_table.php in database\migrations folder seems OK. It is this:

public function up()
    {
        Schema::create('profiles', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->unsignedBigInteger('user_id');
            $table->string('title')->nullable();
            $table->text('description')->nullable();
            $table->string('url')->nullable();
            $table->timestamps();

            $table->index('user_id');

        });
    }

The Profile.php model function is:

public function user()
{
    return $this->belongsTo(User::class);
}

And the User.php model function is:

public function profile()
{
    return $this->hasOne(Profile::class);
}

So, in the terminal, after entering php artisan tinker, I filled in the following before it failed to save:

>>> $profile = new \App\Profile();
=> App\Profile {#3056}
>>> $profile->title = 'Cool Title';
=> "Cool Title"
>>> $profile->description = 'Description';
=> "Description"
>>> $profile->user_id = 1;
=> 1
>>> $profile->save();

EDIT: this is the controller file ProfilesController.php, if it helps to solve the problem:

<?php

namespace App\Http\Controllers;

use \App\User;
use Illuminate\Http\Request;

class ProfilesController extends Controller
{
    public function index($user)
    {
        $user = User::find($user);

        return view('home', [
            'user' => $user,
        ]);
    }
}

All parts went OK, and after I typed the SAVE - it showed the error above. Therefore I can't continue ahead to show the new profile made manualy.

I searched up Google and looked here for answers, like in this question and that question. It didn't solve my problem, and others I think are not as relevant.

What should I do in order to fix it?

Solution

Tanks to @mrhn, adding a new null table + installing composer require doctrine/dbal as suggested here: https://stackoverflow.com/a/37533819/12952748.

Body:
The problem is your database does not allow the column url to be null. Your code is fine and nothing wrong with it, thou it seems you have maybe ran the migration and changed columns definition after.

In Laravel migrations only run once and secures the database has the same structure across systems. For getting the field nullable make a new migration.

php artisan make:migration url_nullable

For you new migration file, add the following migration. Which simply tells the migration to update url to be a string and nullable.

Schema::table('profiles', function (Blueprint $table) {
    $table->string('url')->nullable()->change();
});

After that run your migration and you database should be up to date.

php artisan migrate


问:
Using ehcache in front of memcached
We have a web application that loads a User object from database. Its a high volume application with thousands of concurrent users so we're looking at ways to cache the User objects to minimise database load.

Currently using ehcache but are looking at memcached to lower the memory requirements of the application, and make it more scaleable.

Problem we are currently having with using memcached is the cpu load that serializing the User instance brings. We're looking at ways to speed up the serialization, but ar also considering if we could use a smaller ehcache cache backed by memcached server.

Has anyone had any experience using ehcache backed by memcached (ie. first look in ehcache, if user not there, look in memcache, if not there look in database)?

Any downsides to this kind of approach?

答:
Infinispan can store objects as instances and minimize serialization overhead, also instead of replicating the data on each node it can distribute data to make better usage of your memory, or you can limit the amount of entries to keep in memory.
You can also have it just send invalidation messages to other nodes when you update a value, instead of sending the serialized values around.

In addition, for when it still needs to serialize it uses a very efficient Marshaller instead of Java's serialization, and since version 5 you can plug in your custom Externalizers to customize the wire format of some types to give it a extra push (generally not needed, but nice to have).

In case you where looking at memcached for other reasons as well, be aware that Infinispan also "speaks" the memcached text protocol so if you have other clients around you can still integrate with it.

Title: Using ehcache in front of memcached


问:
split the String by given number of letters
Is there a way to split a string by like splitting

```<code>"The quick brown fox jumps over the lazy dog."
</code>```

to

['The qu', 'ick br', 'own fo', 'x jump', 's over', ' the l', 'azy do', 'g.']

?

答:
If you are trying to split by a particular number of characters, consider using a list comprehension alongside the step parameter of range:

```<code>>>> x = "The quick brown fox jumps over the lazy dog."
>>> N = 6
>>> [x[i:i+N] for i in range(0, len(x), N)]
['The qu', 'ick br', 'own fo', 'x jump', 's over', ' the l', 'azy do', 'g.']
>>>
</code>```

range(0, len(x), N) will return increments of N until len(x). We may use this as the starting index for each slice, and then take N characters after that index, as x[i:i+N].

Body:
Is there a way to split a string by like splitting

"The quick brown fox jumps over the lazy dog."

to

['The qu', 'ick br', 'own fo', 'x jump', 's over', ' the l', 'azy do', 'g.']

?

Body:
If you are trying to split by a particular number of characters, consider using a list comprehension alongside the step parameter of range:

>>> x = "The quick brown fox jumps over the lazy dog."
>>> N = 6
>>> [x[i:i+N] for i in range(0, len(x), N)]
['The qu', 'ick br', 'own fo', 'x jump', 's over', ' the l', 'azy do', 'g.']
>>>

range(0, len(x), N) will return increments of N until len(x). We may use this as the starting index for each slice, and then take N characters after that index, as x[i:i+N].


问: Getting

答:
With Plotly 4, use plotly.io.to_html:

import plotly

# Returns a `<div>` and `<script>`
plotly.io.to_html(figure, include_plotlyjs=False, full_html=False)

# Returns a full standalone HTML
plotly.io.to_html(figure)
```

Reference: https://plotly.com/python-api-reference/generated/plotly.io.to_html.html

Title: Getting <script> and <div> tags from Plotly using Python

Body: I was wondering if anyone knew a good way (preferably a built in method, but I'm open to writing my own of course) to get the

Body:
With Plotly 4, use plotly.io.to_html:

import plotly

# Returns a `<div>` and `<script>`
plotly.io.to_html(figure, include_plotlyjs=False, full_html=False)

# Returns a full standalone HTML
plotly.io.to_html(figure)

Reference: https://plotly.com/python-api-reference/generated/plotly.io.to_html.html


问:
Get accurate array of dates from sheet
I have a Google sheet with thousands of lines, each starting with a date. So:

```<code>2019-01-30
2019-01-30
2019-02-19
2019-03-06
2019-03-06
...
</code>```

I need to get that column into a javascript array and then perform additional functions thereon. I know there is some issue with date indexing such that Google 2019-01-30 translates to javascript 2019-01-29 and a logger on the code confirms this.

How can I get that entire column into the Google Apps Script javascript (using dataSheet.getRange().getValues()) and have that be accurate to what is on the sheet? The only way I know is to individually go through each element of the array and add 1. That feels like a bad way to get around it.

Alternatively, am I better off just leaving it as-is and, when I need to output a date from the javascript to the sheet, add 1 at that point?

答:
Get dates in a flat array</p>

```<code>function getColumnOne() {
  const startrow=2;
  const ss=SpreadsheetApp.getActive();
  const sh=ss.getActiveSheet();
  const rg=sh.getRange(startrow,1,sh.getLastRow()-startrow+1,1);
  var dateA=rg.getValues().map(function(r,i){return r[0];});
  return dateA;//returns a flat array
}
</code>```

Title: Get accurate array of dates from sheet

Body:
I have a Google sheet with thousands of lines, each starting with a date. So:

2019-01-30
2019-01-30
2019-02-19
2019-03-06
2019-03-06
...

I need to get that column into a javascript array and then perform additional functions thereon. I know there is some issue with date indexing such that Google 2019-01-30 translates to javascript 2019-01-29 and a logger on the code confirms this.

How can I get that entire column into the Google Apps Script javascript (using dataSheet.getRange().getValues()) and have that be accurate to what is on the sheet? The only way I know is to individually go through each element of the array and add 1. That feels like a bad way to get around it.

Alternatively, am I better off just leaving it as-is and, when I need to output a date from the javascript to the sheet, add 1 at that point?

Body:
Get dates in a flat array

function getColumnOne() {
  const startrow=2;
  const ss=SpreadsheetApp.getActive();
  const sh=ss.getActiveSheet();
  const rg=sh.getRange(startrow,1,sh.getLastRow()-startrow+1,1);
  var dateA=rg.getValues().map(function(r,i){return r[0];});
  return dateA;//returns a flat array
}


问:
React proxy localhost not working, why?? MacOS Catalina
I have a problem with merging front-end and back-end in React framework. I had opened 3 terminals with: 1. Client side, 2. Database side and 3rd is with started mongodb ( sudo mongod --dbpath /System/Volumes/Data/data/db instead of mongod because of Catalina update ). I can't change localhost:3000 to localhost:8000 don't know why. Any suggestions?

Here are the codes from client and server:

Client:

```<code>const name = match.params.name;
const article = articleContent.find(article => article.name === name);

const [articleInfo, setArticleInfo] = useState({ upvotes: 0, comments: [] });

useEffect(() => {
    const fetchData = async () => {
        const result = await fetch(`/api/article/${name}`);
        const body = await result.json();
        console.log(body);
        setArticleInfo(body);
    }
    fetchData();
}, [name]);
</code>```

package.json:

```<code>"proxy": "http://localhost:8000/",
</code>```

Server:

```<code>    app.post('/api/articles/:name/upvote', async (req, res) => {

    withDB(async (db) => {
        const articleName = req.params.name;

        const articleInfo = await db.collection('articles').findOne({ name: articleName });
        await db.collection('articles').updateOne({ name: articleName }, {
            '$set': {
                upvotes: articleInfo.upvotes + 1,
            },
        });
        const updatedArticleInfo = await db.collection('articles').findOne({ name: articleName });

        res.status(200).json(updatedArticleInfo);
    }, res);
});

app.post('/api/articles/:name/add-comment', (req, res) => {
    const { username, text } = req.body;
    const articleName = req.params.name;

    withDB(async (db) => {
        const articleInfo = await db.collection('articles').findOne({ name: articleName });
        await db.collection('articles').updateOne({ name: articleName }, {
            '$set': {
                comments: articleInfo.comments.concat({ username, text }),
            },
        });
        const updatedArticleInfo = await db.collection('articles').findOne({ name: articleName });

        res.status(200).json(updatedArticleInfo);
    }, res);
});

app.listen(8000, () => console.log('Listening on port 8000'));
</code>```

Client starts on basic command: npm start, Server start with command: npx nodemon --exec npx babel-node src/server.js

Using program Postman, server work correct getting upvotes +1 each time on app.post function, also adding comments etc.

答:
if you are going to use

```<code>proxy": "http://localhost:8000/"
</code>```

as your proxy then at Node your route should not start with / because that would become http://localhost:8000//api/articles/:name/upvote (notice the extra /)

so it should be

```<code>app.post('api/articles/:name/upvote', async (req, res) => {
</code>```

and to change the default PORT number try adding a port to the start script in package.json file

```<code>"scripts": {
   "start": "PORT=3000 react-scripts start",
 }
</code>```

Body:
I have a problem with merging front-end and back-end in React framework. I had opened 3 terminals with: 1. Client side, 2. Database side and 3rd is with started mongodb ( sudo mongod --dbpath /System/Volumes/Data/data/db instead of mongod because of Catalina update ). I can't change localhost:3000 to localhost:8000 don't know why. Any suggestions?

Here are the codes from client and server:

Client:

const name = match.params.name;
const article = articleContent.find(article => article.name === name);

const [articleInfo, setArticleInfo] = useState({ upvotes: 0, comments: [] });

useEffect(() => {
    const fetchData = async () => {
        const result = await fetch(`/api/article/${name}`);
        const body = await result.json();
        console.log(body);
        setArticleInfo(body);
    }
    fetchData();
}, [name]);

package.json:

"proxy": "http://localhost:8000/",

Server:

    app.post('/api/articles/:name/upvote', async (req, res) => {

    withDB(async (db) => {
        const articleName = req.params.name;

        const articleInfo = await db.collection('articles').findOne({ name: articleName });
        await db.collection('articles').updateOne({ name: articleName }, {
            '$set': {
                upvotes: articleInfo.upvotes + 1,
            },
        });
        const updatedArticleInfo = await db.collection('articles').findOne({ name: articleName });

        res.status(200).json(updatedArticleInfo);
    }, res);
});

app.post('/api/articles/:name/add-comment', (req, res) => {
    const { username, text } = req.body;
    const articleName = req.params.name;

    withDB(async (db) => {
        const articleInfo = await db.collection('articles').findOne({ name: articleName });
        await db.collection('articles').updateOne({ name: articleName }, {
            '$set': {
                comments: articleInfo.comments.concat({ username, text }),
            },
        });
        const updatedArticleInfo = await db.collection('articles').findOne({ name: articleName });

        res.status(200).json(updatedArticleInfo);
    }, res);
});

app.listen(8000, () => console.log('Listening on port 8000'));

Client starts on basic command: npm start, Server start with command: npx nodemon --exec npx babel-node src/server.js

Using program Postman, server work correct getting upvotes +1 each time on app.post function, also adding comments etc.

Body:
if you are going to use

proxy": "http://localhost:8000/"

as your proxy then at Node your route should not start with / because that would become http://localhost:8000//api/articles/:name/upvote (notice the extra /)

so it should be

app.post('api/articles/:name/upvote', async (req, res) => {

and to change the default PORT number try adding a port to the start script in package.json file

"scripts": {
   "start": "PORT=3000 react-scripts start",
 }


问:
Does fuzzy logic really improve simple machine learning algorithms?
I'm reading about fuzzy logic and I just don't see how it would possibly improve machine learning algorithms in most instances (which it seems to be applied to relatively often).

Take for example, k nearest neighbors.  If you have a bunch a bunch of attributes like color: [red,blue,green,orange], temperature: [real number], shape: [round, square, triangle], you can't really fuzzify any of these except for the real numbered attribute (please correct me if I'm wrong), and I don't see how this can improve anything more than bucketing things together.

How can machine fuzzy logic be used to improve machine learning?  The toy examples you'll find on most websites don't seem to be all that applicable, most of the time.

答:
In my view, fuzzy logic is not a practically viable approach to anything unless you are building a purpose build fuzzified controller or some rule based structure like for compliance/policies. Although, fuzzy implies dealing with everything between and including 0 and 1. It, however, I find is a bit flawed when you approach more complicated problems where you need to apply fuzzy logic aspects in 3 dimensional spaces. You can still approach multivariate without having to look at fuzzy logic. Unfortunately, for me having studied fuzzy logic I found myself disagreeing with the principles approached in fuzzy sets in large dimensional spaces it seems infeasible, unpractical, and not very logically sound. The natural language base that you would be applying in your fuzzy set solution will also be very adhoc what exactly is [very,few, many] this is all what you define in your application.
Alot, of machine learning aspects you will find that you don't even have to go so far as to build natural language underpinnings into your model. In fact, you will find you can achieve even better results without having to apply fuzzy logic into any aspect of your model. </p>


问:
How do I transform a pandas groupby with a condition on the transformation?
I have a dataframe containing session and bid data where there are three columns (of interest): user_id, event and date.

user_id is just an ID to identify a user

event is either bid or session

date is a datetime object

Now what I want to do is add a column to my dataframe that is the date of the first bid. I have tried several ways of getting this to work but the issue is that it is of course very common that the user generated a session before they made a bid.

I have tried in several ways to get a filter to work but it does not seem to work like I think it should. From the documentation it says "Return a copy of a DataFrame excluding elements from groups that do not satisfy the boolean criterion specified by func." which sounds like what I want, ignore the events in the group that are session and not bid.

```<code>df['first bid date'] = df.groupby('user_id').filter(lambda x: x['event'] == 'bid')['date'].transform('min')
</code>```

When this did not work I tried to instead have the transform take a custom function, like this:

```<code>def custom_transform(group):
    return group[group['event'] == 'bid']['date'].min()

df['first bid date'] = df.groupby('user_id').['date'].transform(custom_transform)
</code>```

But this does not work because the transform cannot access both the date and the event at the same time, seemingly no matter what I groupby.

Finally I tried to group by both the user_id and the event like this

```<code>df['first bid date'] = df.groupby(['user_id', 'event'])['date'].transform('min')

</code>```

which kind of works but then I am left with having to change all of the first sessions to the first bid since there is now a first session and a first bid.

Any input to make this oneliner work? Seems like a combination of groupby, filter and transform should do the trick but I just can't crack it.

Thanks!

答:
Here is some sample code with a dataframe to match the problem.

```<code>from io import StringIO

csv = StringIO("""index,uid,event,date
0,1,"bid",'2010-01-01'
1,1,"bid",'2013-01-01'
2,1,"session",'2009-01-01'
3,2,"session",'2010-01-01'
4,2,"bid",'2015-01-01'
5,2,"bid",'2017-01-01'""")

df = pd.read_csv(csv, index_col='index').reset_index(drop=True)
</code>```

This alternate approach uses the merge function.

```<code>df.merge(df[df['event']=='bid'].groupby('uid')['date'].min(),
on='uid', suffixes=('','_first_bid'))
</code>```

Which prints:

```<code>    uid  event    date        date_first_bid
0   1    bid      2010-01-01  2010-01-01
1   1    bid      2013-01-01  2010-01-01
2   1    session  2009-01-01  2010-01-01
3   2    session  2010-01-01  2015-01-01
4   2    bid      2015-01-01  2015-01-01
5   2    bid      2017-01-01  2015-01-01
</code>```

Body:
I have a dataframe containing session and bid data where there are three columns (of interest): user_id, event and date.

user_id is just an ID to identify a user

event is either bid or session

date is a datetime object

Now what I want to do is add a column to my dataframe that is the date of the first bid. I have tried several ways of getting this to work but the issue is that it is of course very common that the user generated a session before they made a bid.

I have tried in several ways to get a filter to work but it does not seem to work like I think it should. From the documentation it says "Return a copy of a DataFrame excluding elements from groups that do not satisfy the boolean criterion specified by func." which sounds like what I want, ignore the events in the group that are session and not bid.

df['first bid date'] = df.groupby('user_id').filter(lambda x: x['event'] == 'bid')['date'].transform('min')

When this did not work I tried to instead have the transform take a custom function, like this:

def custom_transform(group):
    return group[group['event'] == 'bid']['date'].min()

df['first bid date'] = df.groupby('user_id').['date'].transform(custom_transform)

But this does not work because the transform cannot access both the date and the event at the same time, seemingly no matter what I groupby.

Finally I tried to group by both the user_id and the event like this

df['first bid date'] = df.groupby(['user_id', 'event'])['date'].transform('min')

which kind of works but then I am left with having to change all of the first sessions to the first bid since there is now a first session and a first bid.

Any input to make this oneliner work? Seems like a combination of groupby, filter and transform should do the trick but I just can't crack it.

Thanks!

Body:
Here is some sample code with a dataframe to match the problem.

from io import StringIO

csv = StringIO("""index,uid,event,date
0,1,"bid",'2010-01-01'
1,1,"bid",'2013-01-01'
2,1,"session",'2009-01-01'
3,2,"session",'2010-01-01'
4,2,"bid",'2015-01-01'
5,2,"bid",'2017-01-01'""")

df = pd.read_csv(csv, index_col='index').reset_index(drop=True)

This alternate approach uses the merge function.

df.merge(df[df['event']=='bid'].groupby('uid')['date'].min(),
on='uid', suffixes=('','_first_bid'))

Which prints:

    uid  event    date        date_first_bid
0   1    bid      2010-01-01  2010-01-01
1   1    bid      2013-01-01  2010-01-01
2   1    session  2009-01-01  2010-01-01
3   2    session  2010-01-01  2015-01-01
4   2    bid      2015-01-01  2015-01-01
5   2    bid      2017-01-01  2015-01-01