问:
How to use Reflection in linq queries ?RSS
I'm looking for a way to use reflection in my linq queries to increase code reusability. for example, i want to change this method :

```<code>private Orders GetObjectGraph(MyDbContext dbContext, int orderID)
{
    return dbContext.Orders.Include(o => o.OrderDetails).AsNoTracking().FirstOrDefault(o => o.OrderID == orderID);
}
</code>```

To something like this :

```<code>private object GetObjectGraph(MyDbContext dbContext, string masterEntityName, string detailsEntityName, string masterFieldName, object masterFieldValue)
{
    return dbContext[masterEntityName].Include(o => o[detailsEntityName]).AsNoTracking().FirstOrDefault(o => o.[masterFieldName] == masterFieldValue);
}
</code>```

Can anybody help me how to accomplish this task ?

Thanks in advance

答:
You can try something like this (if you are not getting strings from somewhere outside in runtime, if you do than this solution can be adapted to build corresponding Expression Trees from strings):

```<code>private T GetObjectGraph<T, TDetails, TField>(
    MyDbContext dbContext,
    Expression<Func<T, TDetails>> details,
    Expression<Func<T, TField>> field,
    TField value) where T: class
{
    var p = field.Parameters[0];
    var eq = Expression.Equal(field.Body, Expression.Constant(value));
    var expr = Expression.Lambda<Func<T, bool>>(eq, p);
    return dbContext
        .Set<T>()
        .Include(details)
        .AsNoTracking()
        .FirstOrDefault(expr);
}
</code>```

And usage:

```<code>GetObjectGraph(dbContext, (Order o) => o.OrderDetails, o => o.OrderID, orderID)
</code>```

If you don't need to parse strings and so on this could be simplified to:

```<code>public static class Ext
{
    public static T GetObjectGraph<T, TDetails>(
        this DbSet<T> set,
        Expression<Func<T, TDetails>> details,
        Expression<Func<T, bool>> filter) where T : class
    {

        return set
            .Include(details)
            .AsNoTracking()
            .FirstOrDefault(filter);
    }
}
</code>```

And usage:

```<code>dbContext.Orders(o => o.OrderDetails, o => o.OrderID == orderID);
</code>```

And for more insight how to handle strings you can look at this question.

Body:
I'm looking for a way to use reflection in my linq queries to increase code reusability. for example, i want to change this method :

private Orders GetObjectGraph(MyDbContext dbContext, int orderID)
{
    return dbContext.Orders.Include(o => o.OrderDetails).AsNoTracking().FirstOrDefault(o => o.OrderID == orderID);
}

To something like this :

private object GetObjectGraph(MyDbContext dbContext, string masterEntityName, string detailsEntityName, string masterFieldName, object masterFieldValue)
{
    return dbContext[masterEntityName].Include(o => o[detailsEntityName]).AsNoTracking().FirstOrDefault(o => o.[masterFieldName] == masterFieldValue);
}

Can anybody help me how to accomplish this task ?

Thanks in advance

Body:
You can try something like this (if you are not getting strings from somewhere outside in runtime, if you do than this solution can be adapted to build corresponding Expression Trees from strings):

private T GetObjectGraph<T, TDetails, TField>(
    MyDbContext dbContext,
    Expression<Func<T, TDetails>> details,
    Expression<Func<T, TField>> field,
    TField value) where T: class
{
    var p = field.Parameters[0];
    var eq = Expression.Equal(field.Body, Expression.Constant(value));
    var expr = Expression.Lambda<Func<T, bool>>(eq, p);
    return dbContext
        .Set<T>()
        .Include(details)
        .AsNoTracking()
        .FirstOrDefault(expr);
}

And usage:

GetObjectGraph(dbContext, (Order o) => o.OrderDetails, o => o.OrderID, orderID)

If you don't need to parse strings and so on this could be simplified to:

public static class Ext
{
    public static T GetObjectGraph<T, TDetails>(
        this DbSet<T> set,
        Expression<Func<T, TDetails>> details,
        Expression<Func<T, bool>> filter) where T : class
    {

        return set
            .Include(details)
            .AsNoTracking()
            .FirstOrDefault(filter);
    }
}

And usage:

dbContext.Orders(o => o.OrderDetails, o => o.OrderID == orderID);

And for more insight how to handle strings you can look at this question.


来源: stackexchange

问:
Rails edit form not showing nested item
I got a form that have a nested link. The problem that the link field is empty on edit.
Here is my form:

```<code><h1>Editing kategori</h1>
<%= simple_form_for(@konkurrancer, :url => {:action => 'update', :id => @konkurrancer.id }) do |f| %>
    <%= f.simple_fields_for :link_attributes do |d| %>
    <%= d.input :link, :label => 'Tracking url', :style => 'width:500;' %>
    <% end %>
    <%= f.button :submit, :value => 'Edit konkurrence' %>
<% end %>
<%= link_to 'Show', admin_konkurrancer_path %> |
<%= link_to 'Back', admin_konkurrancer_path %>
</code>```

My konkurrencer model:

```<code>has_one :link
</code>```

My link model:

```<code>class Link < ActiveRecord::Base
belongs_to :konkurrancer
accepts_nested_attributes_for :konkurrancer
end
</code>```

My konkurrancer edit action:

```<code>  def edit
    @konkurrancer = Konkurrancer.find(params[:id])
    @konkurrancer.link_attributes.build
  end
</code>```

答:
1) Remove from your Link model

```<code>accepts_nested_attributes_for :konkurrancer
</code>```

and add to your Konkurrancer model

```<code>accepts_nested_attributes_for :link
</code>```

2) In controller edit action remove

```<code>@konkurrancer.link_attributes.build
</code>```

and in controller new action add

```<code>@konkurrances.build_link
</code>```

3) In the view file replace

```<code><%= f.simple_fields_for :link_attributes do |d| %>
</code>```

with

```<code><%= f.simple_fields_for :link do |d| %>
</code>```

ContentLicense: CC BY-SA 3.0

Title: Rails edit form not showing nested item

Body:
I got a form that have a nested link. The problem that the link field is empty on edit.
Here is my form:

Editing kategori

<%= simple_form_for(@konkurrancer, :url => {:action => 'update', :id => @konkurrancer.id }) do |f| %>
    <%= f.simple_fields_for :link_attributes do |d| %>
    <%= d.input :link, :label => 'Tracking url', :style => 'width:500;' %>
    <% end %>
    <%= f.button :submit, :value => 'Edit konkurrence' %>
<% end %>
<%= link_to 'Show', admin_konkurrancer_path %> |
<%= link_to 'Back', admin_konkurrancer_path %>

My konkurrencer model:

has_one :link

My link model:

class Link < ActiveRecord::Base
belongs_to :konkurrancer
accepts_nested_attributes_for :konkurrancer
end

My konkurrancer edit action:

  def edit
    @konkurrancer = Konkurrancer.find(params[:id])
    @konkurrancer.link_attributes.build
  end

Body:
1) Remove from your Link model

accepts_nested_attributes_for :konkurrancer

and add to your Konkurrancer model

accepts_nested_attributes_for :link

2) In controller edit action remove

@konkurrancer.link_attributes.build

and in controller new action add

@konkurrances.build_link

3) In the view file replace

<%= f.simple_fields_for :link_attributes do |d| %>

with

<%= f.simple_fields_for :link do |d| %>


问:
Python function to convert one or more columns
My goal is that specified columns in a dataframe get converted to numeric even if they have commas in them. In other words:

```<code>cols = ["x"]
df = pd.DataFrame({"x": ["1,000", "2,000"], "y": ["430","3,000"]})
df = data.float_convert(df, cols)
</code>```

produces a df with this value:

```<code>pd.DataFrame({"x": ["1000", "2000"], "y": ["430","3,000"]})
</code>```

Here's my function:

```<code>def float_convert(df, cols):
    return (df.loc[:,cols].apply(lambda x: x.str.replace(',', "").astype(float)))
</code>```

I can't understand why my code is not doing what I expect, and dont know if there's a much simpler way of doing this.

答:
You forget assign it back </p>

```<code>def float_convert(df, cols):
       df.loc[:,cols]=df.loc[:,cols].apply(lambda x: x.str.replace(',', "").astype(float))
float_convert(df, cols)
df
      x      y
0  1000    430
1  2000  3,000
</code>```

ContentLicense: CC BY-SA 4.0

Body:
My goal is that specified columns in a dataframe get converted to numeric even if they have commas in them. In other words:

cols = ["x"]
df = pd.DataFrame({"x": ["1,000", "2,000"], "y": ["430","3,000"]})
df = data.float_convert(df, cols)

produces a df with this value:

pd.DataFrame({"x": ["1000", "2000"], "y": ["430","3,000"]})

Here's my function:

def float_convert(df, cols):
    return (df.loc[:,cols].apply(lambda x: x.str.replace(',', "").astype(float)))

I can't understand why my code is not doing what I expect, and dont know if there's a much simpler way of doing this.

Body:
You forget assign it back

def float_convert(df, cols):
       df.loc[:,cols]=df.loc[:,cols].apply(lambda x: x.str.replace(',', "").astype(float))
float_convert(df, cols)
df
      x      y
0  1000    430
1  2000  3,000


问:
Fix grammtical or spelling errors?
I want to test this method in a junit and one more.</p>

答: I think you want a new instance of Temperature, which should look like this: Temperature temperature = new Temperature();. You can use this to set the internal fahrenheit value of 30 temperature.setFahrenheit(30); and get the celcius value by double celsius = temperature.toCelsius();

Title: Fix grammtical or spelling errors?


问:
bootstrap 4 - placing one table under another and centering
I want to have my tables centered horizontally and I expect them to be displayed one under another. Using some bootstrap 4 classes I've managed to have the tables displayed very unevenly or to have one missing. That is why I am looking for help, and I'm delivering the code, where the two tables exists in one row. </p>

```<code><div class="mt-3 d-flex justify-content-center">
        <div class="text-center p-2">
        <table class="table table-dark table-striped w-auto">
        <thead>
            <tr class="bg-primary">
            <th>Przystanek</th>
            <th>(A)</th>
            <th>(A)</th>
            <th>(A)</th>
            <th>(A)</th>
            </tr>
        </thead>
        <tbody>
            <tr>
            <th scope="row">Lidzbark Warmiński</th>
            <td>08:00</td>
            <td>12:00</td>
            <td>15:00</td>
            <td>19:00</td>
            </tr>
            <tr>
            <th scope="row">Kraszewo</th>
            <td>08:20</td>
            <td>12:20</td>
            <td>15:20</td>
            <td>19:20</td>
            </tr>
            <tr>
            <th scope="row">Dobre Miasto</th>
            <td>08:30</td>
            <td>12:30</td>
            <td>15:30</td>
            <td>19:30</td>
            </tr>
            <tr>
            <th scope="row">Olsztyn PKP</th>
            <td>09:00</td>
            <td>13:00</td>
            <td>16:00</td>
            <td>20:00</td>
            </tr>
        </tbody>
        </table>
        </div>

        <div class="text-center p-2">
        <table class="table table-dark table-striped w-auto ">
        <thead>
            <tr class="bg-primary">
            <th>Przystanek</th>
            <th>(A)</th>
            <th>(A)</th>
            <th>(A)</th>
            <th>(A)</th>
            </tr>
        </thead>
        <tbody>
            <tr>
            <th scope="row">Olsztyn PKP</th>
            <td>09:00</td>
            <td>13:00</td>
            <td>17:00</td>
            <td>21:00</td>
            </tr>
            <tr>
            <th scope="row">Dobre Miasto</th>
            <td>09:30</td>
            <td>13:30</td>
            <td>17:30</td>
            <td>21:30</td>
            </tr>
            <tr>
            <th scope="row">Kraszewo</th>
            <td>09:50</td>
            <td>13:50</td>
            <td>17:50</td>
            <td>21:50</td>
            </tr>
            <tr>
            <th scope="row">Lidzbark Warmiński</th>
            <td>10:00</td>
            <td>14:00</td>
            <td>18:00</td>
            <td>22:00</td>
            </tr>
        </tbody>
        </table>
        </div>
    </div>
</code>```

答:
You just need set flex direction to column instead rows (that is by default), and then align items. In bootstrap it will be simply flex-column and align-items-center.

Docs: https://getbootstrap.com/docs/4.4/utilities/flex/

Also this div
 is not needed. Just set text-center on table.

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet"/>

            Przystanek
            (A)
            (A)
            (A)
            (A)

            Lidzbark Warmiński
            08:00
            12:00
            15:00
            19:00

            Kraszewo
            08:20
            12:20
            15:20
            19:20

            Dobre Miasto
            08:30
            12:30
            15:30
            19:30

            Olsztyn PKP
            09:00
            13:00
            16:00
            20:00

            Przystanek
            (A)
            (A)
            (A)
            (A)

            Olsztyn PKP
            09:00
            13:00
            17:00
            21:00

            Dobre Miasto
            09:30
            13:30
            17:30
            21:30

            Kraszewo
            09:50
            13:50
            17:50
            21:50

            Lidzbark Warmiński
            10:00
            14:00
            18:00
            22:00

```

Body:
I want to have my tables centered horizontally and I expect them to be displayed one under another. Using some bootstrap 4 classes I've managed to have the tables displayed very unevenly or to have one missing. That is why I am looking for help, and I'm delivering the code, where the two tables exists in one row.

            Przystanek
            (A)
            (A)
            (A)
            (A)

            Lidzbark Warmiński
            08:00
            12:00
            15:00
            19:00

            Kraszewo
            08:20
            12:20
            15:20
            19:20

            Dobre Miasto
            08:30
            12:30
            15:30
            19:30

            Olsztyn PKP
            09:00
            13:00
            16:00
            20:00

            Przystanek
            (A)
            (A)
            (A)
            (A)

            Olsztyn PKP
            09:00
            13:00
            17:00
            21:00

            Dobre Miasto
            09:30
            13:30
            17:30
            21:30

            Kraszewo
            09:50
            13:50
            17:50
            21:50

            Lidzbark Warmiński
            10:00
            14:00
            18:00
            22:00

Body:
You just need set flex direction to column instead rows (that is by default), and then align items. In bootstrap it will be simply flex-column and align-items-center.

Docs: https://getbootstrap.com/docs/4.4/utilities/flex/

Also this div <div class="text-center p-2"> is not needed. Just set text-center on table.

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet"/>

<div class="mt-3 d-flex align-items-center flex-column">
    <table class="table table-dark table-striped w-auto text-center m-2">
        <thead>
            <tr class="bg-primary">
            <th>Przystanek</th>
            <th>(A)</th>
            <th>(A)</th>
            <th>(A)</th>
            <th>(A)</th>
            </tr>
        </thead>
        <tbody>
            <tr>
            <th scope="row">Lidzbark Warmiński</th>
            <td>08:00</td>
            <td>12:00</td>
            <td>15:00</td>
            <td>19:00</td>
            </tr>
            <tr>
            <th scope="row">Kraszewo</th>
            <td>08:20</td>
            <td>12:20</td>
            <td>15:20</td>
            <td>19:20</td>
            </tr>
            <tr>
            <th scope="row">Dobre Miasto</th>
            <td>08:30</td>
            <td>12:30</td>
            <td>15:30</td>
            <td>19:30</td>
            </tr>
            <tr>
            <th scope="row">Olsztyn PKP</th>
            <td>09:00</td>
            <td>13:00</td>
            <td>16:00</td>
            <td>20:00</td>
            </tr>
        </tbody>
        </table>

    <table class="table table-dark table-striped w-auto text-center m-2">
        <thead>
            <tr class="bg-primary">
            <th>Przystanek</th>
            <th>(A)</th>
            <th>(A)</th>
            <th>(A)</th>
            <th>(A)</th>
            </tr>
        </thead>
        <tbody>
            <tr>
            <th scope="row">Olsztyn PKP</th>
            <td>09:00</td>
            <td>13:00</td>
            <td>17:00</td>
            <td>21:00</td>
            </tr>
            <tr>
            <th scope="row">Dobre Miasto</th>
            <td>09:30</td>
            <td>13:30</td>
            <td>17:30</td>
            <td>21:30</td>
            </tr>
            <tr>
            <th scope="row">Kraszewo</th>
            <td>09:50</td>
            <td>13:50</td>
            <td>17:50</td>
            <td>21:50</td>
            </tr>
            <tr>
            <th scope="row">Lidzbark Warmiński</th>
            <td>10:00</td>
            <td>14:00</td>
            <td>18:00</td>
            <td>22:00</td>
            </tr>
        </tbody>
    </table>
</div>


问:
SQL or Spring JDBC return object of objects
Is it possible for postgres-sql or Spring JDBC to return data with the following shape:

```<code>    {
      id: 1
      profit: 200
      sales_rep: {
        name: 'bob',
        age: 9,
        gender: male
    }
</code>```

where name, age, and gender are inside the key 'sales_rep' before it reaches the repository layer? Or do I have to retrieve flat data and then put it into the shape I want in repository layer using java.

Please assume we are using two tables 'earnings' and 'sales_rep' with foreign key being 'sales_rep_id' for the sake of argument.

答:
In Postgres SQL, you can do this easily with json functions:

```<code>select jsonb_build_object(
    'id',        e.id,
    'profit',    e.profit
    'sales_rep', jsonb_build_object(
        'name',   sr.name,
        'age',    sr.age,
        'gender', sr.gender
    )
) js
from earnings e
inner join sales_rep sr on sr.sales_rep_id = e.sales_rep_id
</code>```

This gives you a resultset with one row per earning and a single colum, that contains a jsonb payload with the structure that you asked for.

Body:
Is it possible for postgres-sql or Spring JDBC to return data with the following shape:

    {
      id: 1
      profit: 200
      sales_rep: {
        name: 'bob',
        age: 9,
        gender: male
    }

where name, age, and gender are inside the key 'sales_rep' before it reaches the repository layer? Or do I have to retrieve flat data and then put it into the shape I want in repository layer using java.

Please assume we are using two tables 'earnings' and 'sales_rep' with foreign key being 'sales_rep_id' for the sake of argument.

Body:
In Postgres SQL, you can do this easily with json functions:

select jsonb_build_object(
    'id',        e.id,
    'profit',    e.profit
    'sales_rep', jsonb_build_object(
        'name',   sr.name,
        'age',    sr.age,
        'gender', sr.gender
    )
) js
from earnings e
inner join sales_rep sr on sr.sales_rep_id = e.sales_rep_id

This gives you a resultset with one row per earning and a single colum, that contains a jsonb payload with the structure that you asked for.


问:
SSL certificate issue GoDaddy domain , Heroku Server hosting , Cloudflare SSL
I have bought my domain name www.thoughtgrub.com from goDaddy.
However I am hosting it on Heroku.
I needed an SSL certificate so I set that up using cloudflare.

When I check whether SSL is installed using https://www.digicert.com/help/
It says certificate installed correctly.

However web browser shows www.thoughtgrub.com as unsecure.
also https://thoughtgrub.com --> throws Site cannot be reached error or

shortener.secureserver.net/error_404

What's going wrong?
IS there any other method to achieve https certification?

答: you need to go to heroku settings and click on add SSl certificate. </p>


问:
Am I using file_get_contents properly?
Lately, I was messing around with HTML and PHP (which I just started to learn).
I found out, that I can use file_get_contents to fetch the contents of a text file.
So I copied the contents of my HTML file in a plain PHP file and just replaced the text, which was written in the HTML with

```<code>  <?PHP
    $name = file_get_contents('this.txt');
    echo $name;
  ?>
</code>```

I wondered If I could still use the links I which where embedded in the text. I could.

```<code><a href="https://optifine.net/downloads" target="_blank">Optifine</a>
</code>```

This is in the .txt file and works.
But now I don't know if this is the "right" way of doing it.
Obviously it works, but does it always work or is there a better way?

edit/extension:

file_get_contens:

expection: gets the pure contents form a file without prosessing e.g. links etc.

reality: fetches the text from the txt file and handles it as a html file thus prossessingthe links thus showing them properly

include:

expection: gets filecontents and prosesses file according to its extension.

reality: gets contents from textfile and prosesses it as an html file thus showing the links properly.

WHY

答:
Yes, you can use file_get_contents to fetch text.

Better way for fetching external text/code would be to use include as you can also use .html, .php...

```<code><?php
  include 'externalfile.html';
?>
</code>```

You can also use require, which is almost same thing except:

The include and require statements are identical, except upon failure:

require will produce a fatal error (E_COMPILE_ERROR) and stop the script

include will only produce a warning (E_WARNING) and the script will continue

W3schools reference for include

Title: Am I using file_get_contents properly?

Body:
Lately, I was messing around with HTML and PHP (which I just started to learn).
I found out, that I can use file_get_contents to fetch the contents of a text file.
So I copied the contents of my HTML file in a plain PHP file and just replaced the text, which was written in the HTML with

  <?PHP
    $name = file_get_contents('this.txt');
    echo $name;
  ?>

I wondered If I could still use the links I which where embedded in the text. I could.

Optifine

This is in the .txt file and works.
But now I don't know if this is the "right" way of doing it.
Obviously it works, but does it always work or is there a better way?

edit/extension:

file_get_contens:

expection: gets the pure contents form a file without prosessing e.g. links etc.

reality: fetches the text from the txt file and handles it as a html file thus prossessingthe links thus showing them properly

include:

expection: gets filecontents and prosesses file according to its extension.

reality: gets contents from textfile and prosesses it as an html file thus showing the links properly.

WHY

Body:
Yes, you can use file_get_contents to fetch text.

Better way for fetching external text/code would be to use include as you can also use .html, .php...

<?php
  include 'externalfile.html';
?>

You can also use require, which is almost same thing except:

The include and require statements are identical, except upon failure:

require will produce a fatal error (E_COMPILE_ERROR) and stop the script

include will only produce a warning (E_WARNING) and the script will continue

W3schools reference for include


问:
how to make websites for iphone
i have a website which i want my users to access from their iphones as well. Would i need to make separate webpages for mobiles or is there a template provided in Xcode that lets developers make web applications for iphone?

if i am making the website just my altering the webpages then i am limited by the functionality of the browser safari. But if i am going for Xcode based support for web applications i would be able to use the rich Foundation and UIKit framework.

what is a better option?

thank you in advance.

答:
Check for the browser's user agent using PHP and then redirect the user to a mobile version of your website. You can use the iphone simulator or a browser that can change the user agent (like safari) to test your website. Don't forget to make the UI much cleaner than on your regular website, it should to follow the design philosophy that Apple implemented on the iphone.

```<code>$userAgent = $_SERVER['HTTP_USER_AGENT'];
</code>```

iPad user agent:

```<code>Mozilla/5.0 (iPad; U; CPU OS 3_2_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B500 Safari/531.21.10
</code>```

iPhone user agent:

```<code>Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_1 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Version/4.0.5 Mobile/8B117 Safari/6531.22.7
</code>```

iPod user agent:

```<code>Mozilla/5.0 (iPod; U; CPU iPhone OS 4_1 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Version/4.0.5 Mobile/8B117 Safari/6531.22.7
</code>```

Title: how to make websites for iphone

Body:
Check for the browser's user agent using PHP and then redirect the user to a mobile version of your website. You can use the iphone simulator or a browser that can change the user agent (like safari) to test your website. Don't forget to make the UI much cleaner than on your regular website, it should to follow the design philosophy that Apple implemented on the iphone.

$userAgent = $_SERVER['HTTP_USER_AGENT'];

iPad user agent:

Mozilla/5.0 (iPad; U; CPU OS 3_2_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B500 Safari/531.21.10

iPhone user agent:

Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_1 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Version/4.0.5 Mobile/8B117 Safari/6531.22.7

iPod user agent:

Mozilla/5.0 (iPod; U; CPU iPhone OS 4_1 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Version/4.0.5 Mobile/8B117 Safari/6531.22.7


问:
How to generate a unique list of 3 character prefixes
How to make the top list to the below output in python 3:

```<code>['abc', 'def', 'ghi']

['adg', 'adh', 'adi', 'aeg', 'aeh', 'aei', 'afg', 'afh', 'afi', 'bdg', 'bdh', 'bdi', 'beg', 'beh', 'bei', 'bfg', 'bfh', 'bfi', 'cdg', 'cdh', 'cdi', 'ceg', 'ceh', 'cei', 'cfg', 'cfh', 'cfi']
</code>```

If possible, can this be solved using a for loop?

答:
You are looking for itertools.product:

```<code>from itertools import product

lst = ['abc', 'def', 'ghi']

print( [''.join(c) for c in product(*lst)] )
</code>```

Prints:

```<code>['adg', 'adh', 'adi', 'aeg', 'aeh', 'aei', 'afg', 'afh', 'afi', 'bdg', 'bdh', 'bdi', 'beg', 'beh', 'bei', 'bfg', 'bfh', 'bfi', 'cdg', 'cdh', 'cdi', 'ceg', 'ceh', 'cei', 'cfg', 'cfh', 'cfi']
</code>```

Body:
How to make the top list to the below output in python 3:

['abc', 'def', 'ghi']

['adg', 'adh', 'adi', 'aeg', 'aeh', 'aei', 'afg', 'afh', 'afi', 'bdg', 'bdh', 'bdi', 'beg', 'beh', 'bei', 'bfg', 'bfh', 'bfi', 'cdg', 'cdh', 'cdi', 'ceg', 'ceh', 'cei', 'cfg', 'cfh', 'cfi']

If possible, can this be solved using a for loop?

Body:
You are looking for itertools.product:

from itertools import product

lst = ['abc', 'def', 'ghi']

print( [''.join(c) for c in product(*lst)] )

Prints:

['adg', 'adh', 'adi', 'aeg', 'aeh', 'aei', 'afg', 'afh', 'afi', 'bdg', 'bdh', 'bdi', 'beg', 'beh', 'bei', 'bfg', 'bfh', 'bfi', 'cdg', 'cdh', 'cdi', 'ceg', 'ceh', 'cei', 'cfg', 'cfh', 'cfi']


问:
Flutter own AppBar needs context with navigation
I made via a tutorial a own app bar with a gradient color. But now can I not navigate with the buttons to my settings view. The button needs a context. Can you help me how I fix this issue please? Thanks!</p>

```<code>class MyAppBar extends AppBar {
  MyAppBar({Key key, Widget title})
  : super(
      key: key,
      title: title,
      centerTitle: true,
      flexibleSpace: Container(
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topLeft,
            end: Alignment.bottomRight,
            colors: <Color>[
          Color.fromRGBO(255, 120, 84, 1),
          Color.fromRGBO(236, 10, 131, 1)
        ])
      )),
      actions: <Widget>[
      new IconButton(
        icon: new Icon(Icons.notifications),
        onPressed: ()=> print("tap"),
      ),
      new IconButton(
        icon: new Icon(Icons.settings),
        onPressed: () => Navigator.pushReplacementNamed(context, Settings.id),
      )
  ]);
}
</code>```

答:
You need to extend a StatelessWidget to get your BuildContext and then implement PreferredSizeWidget because the AppBar itself implements it.

```<code>class MyAppBar extends StatelessWidget implements PreferredSizeWidget {
final String screenTitle;

MyAppBar({@required this.screenTitle});

@override
Widget build(BuildContext context) {
  return AppBar(
    title: Text(screenTitle),
    actions: // Whatever you need
  );
}

@override
Size get preferredSize => Size.fromHeight(kToolbarHeight);
}
</code>```

You also need to override get preferredSize and specify a height. In this example, I used a constant already specified by Flutter that is 56.0 for the toolbar component of the AppBar.

Body:
I made via a tutorial a own app bar with a gradient color. But now can I not navigate with the buttons to my settings view. The button needs a context. Can you help me how I fix this issue please? Thanks!

class MyAppBar extends AppBar {
  MyAppBar({Key key, Widget title})
  : super(
      key: key,
      title: title,
      centerTitle: true,
      flexibleSpace: Container(
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topLeft,
            end: Alignment.bottomRight,
            colors: <Color>[
          Color.fromRGBO(255, 120, 84, 1),
          Color.fromRGBO(236, 10, 131, 1)
        ])
      )),
      actions: <Widget>[
      new IconButton(
        icon: new Icon(Icons.notifications),
        onPressed: ()=> print("tap"),
      ),
      new IconButton(
        icon: new Icon(Icons.settings),
        onPressed: () => Navigator.pushReplacementNamed(context, Settings.id),
      )
  ]);
}

Body:
You need to extend a StatelessWidget to get your BuildContext and then implement PreferredSizeWidget because the AppBar itself implements it.

class MyAppBar extends StatelessWidget implements PreferredSizeWidget {
final String screenTitle;

MyAppBar({@required this.screenTitle});

@override
Widget build(BuildContext context) {
  return AppBar(
    title: Text(screenTitle),
    actions: // Whatever you need
  );
}

@override
Size get preferredSize => Size.fromHeight(kToolbarHeight);
}

You also need to override get preferredSize and specify a height. In this example, I used a constant already specified by Flutter that is 56.0 for the toolbar component of the AppBar.


问:
STM32L4 - SPI2 clocking issue
I am currently working on the STM32L476RG Nucleo board and I am trying to communicate with the SPI2 bus.

It seems that I am sending data with the MOSI pin but I don't have anything on the SCK pin.

Here are my initialisation code and sending data code:

In the main.c:

/Function that initializes the SPI/

```<code>void MX_SPI2_Init(void)
{
  hspi2.Instance = SPI2;
  hspi2.Init.Mode = SPI_MODE_MASTER;
  hspi2.Init.Direction = SPI_DIRECTION_2LINES;
  hspi2.Init.DataSize = SPI_DATASIZE_8BIT;
  hspi2.Init.CLKPolarity = SPI_POLARITY_LOW;
  hspi2.Init.CLKPhase = SPI_PHASE_1EDGE;
  hspi2.Init.NSS = SPI_NSS_SOFT;
  hspi2.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_16;
  hspi2.Init.FirstBit = SPI_FIRSTBIT_MSB;
  hspi2.Init.TIMode = SPI_TIMODE_DISABLED;
  hspi2.Init.CRCCalculation = SPI_CRCCALCULATION_DISABLED;
  hspi2.Init.CRCPolynomial = 7;
  hspi2.Init.CRCLength = SPI_CRC_LENGTH_DATASIZE;
  hspi2.Init.NSSPMode = SPI_NSS_PULSE_DISABLED;
  HAL_SPI_Init(&hspi2);
}
</code>```

/Function that sends data via SPI to the slave/

```<code>void ADAS1000_SetRegisterValue(unsigned char regAddress,
                               unsigned long regVal)
{

    unsigned char writeCmd[4] = {0, 0, 0, 0};

    writeCmd[0] = 0x80 + regAddress;    // Write bit and register address.
    writeCmd[1] = (unsigned char)((regVal & 0xFF0000) >> 16);
    writeCmd[2] = (unsigned char)((regVal & 0x00FF00) >> 8);
    writeCmd[3] = (unsigned char)((regVal & 0x0000FF) >> 0);

    HAL_SPI_Transmit(&hspi2, &(writeCmd[0]), (uint16_t) sizeof(writeCmd[0]), 50);
    HAL_Delay(500);
    HAL_SPI_Transmit(&hspi2, &(writeCmd[1]), (uint16_t) sizeof(writeCmd[1]), 50);
    HAL_Delay(500);
    HAL_SPI_Transmit(&hspi2, &(writeCmd[2]), (uint16_t) sizeof(writeCmd[2]), 50);
    HAL_Delay(500);
    HAL_SPI_Transmit(&hspi2, &(writeCmd[3]), (uint16_t) sizeof(writeCmd[3]), 50);
    HAL_Delay(500);
}
</code>```

In the hal_msp.c :

```<code>void HAL_SPI_MspInit(SPI_HandleTypeDef* hspi)
{

  GPIO_InitTypeDef GPIO_InitStruct;
  if(hspi->Instance==SPI2)
  {
    /* Peripheral clock enable */
    __SPI2_CLK_ENABLE();

    /**SPI2 GPIO Configuration
    PC2     ------> SPI2_MISO
    PC3     ------> SPI2_MOSI
    PB10     ------> SPI2_SCK
    PB12     ------> SPI2_NSS
    */
    GPIO_InitStruct.Pin = GPIO_PIN_2|GPIO_PIN_3;
    GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
    GPIO_InitStruct.Pull = GPIO_NOPULL;
    GPIO_InitStruct.Speed = GPIO_SPEED_MEDIUM;
    GPIO_InitStruct.Alternate = GPIO_AF5_SPI2;
    HAL_GPIO_Init(GPIOC, &GPIO_InitStruct);

    GPIO_InitStruct.Pin = GPIO_PIN_10|GPIO_PIN_12;
    GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
    GPIO_InitStruct.Pull = GPIO_NOPULL;
    GPIO_InitStruct.Speed = GPIO_SPEED_MEDIUM;
    GPIO_InitStruct.Alternate = GPIO_AF5_SPI2;
    HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
  }
</code>```

If you have any ideas or advice, thanks for helping!

EDIT

```<code>void MX_GPIO_Init(void)
{
   /* GPIO Ports Clock Enable */
   __GPIOC_CLK_ENABLE();
   __GPIOA_CLK_ENABLE();
   __GPIOB_CLK_ENABLE();
}
</code>```

答:
This might be the problem:

```<code>// [...]
hspi2.Init.NSS = SPI_NSS_SOFT;
// [...]
</code>```

Without checking the definition of your HAL macros, I believe that this configures the SPI not to drive NSS - but to have this done by software. This means that you are responsible to assert the NSS pin manually before putting data into the SPI peripheral.

This in turn may cause the SPI slave side not to respond, which may appear like the SCK signals weren't reaching the slave at all.

Title: STM32L4 - SPI2 clocking issue

Body:
I am currently working on the STM32L476RG Nucleo board and I am trying to communicate with the SPI2 bus.

It seems that I am sending data with the MOSI pin but I don't have anything on the SCK pin.

Here are my initialisation code and sending data code:

In the main.c:

/Function that initializes the SPI/

void MX_SPI2_Init(void)
{
  hspi2.Instance = SPI2;
  hspi2.Init.Mode = SPI_MODE_MASTER;
  hspi2.Init.Direction = SPI_DIRECTION_2LINES;
  hspi2.Init.DataSize = SPI_DATASIZE_8BIT;
  hspi2.Init.CLKPolarity = SPI_POLARITY_LOW;
  hspi2.Init.CLKPhase = SPI_PHASE_1EDGE;
  hspi2.Init.NSS = SPI_NSS_SOFT;
  hspi2.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_16;
  hspi2.Init.FirstBit = SPI_FIRSTBIT_MSB;
  hspi2.Init.TIMode = SPI_TIMODE_DISABLED;
  hspi2.Init.CRCCalculation = SPI_CRCCALCULATION_DISABLED;
  hspi2.Init.CRCPolynomial = 7;
  hspi2.Init.CRCLength = SPI_CRC_LENGTH_DATASIZE;
  hspi2.Init.NSSPMode = SPI_NSS_PULSE_DISABLED;
  HAL_SPI_Init(&hspi2);
}

/Function that sends data via SPI to the slave/

void ADAS1000_SetRegisterValue(unsigned char regAddress,
                               unsigned long regVal)
{

    unsigned char writeCmd[4] = {0, 0, 0, 0};

    writeCmd[0] = 0x80 + regAddress;    // Write bit and register address.
    writeCmd[1] = (unsigned char)((regVal & 0xFF0000) >> 16);
    writeCmd[2] = (unsigned char)((regVal & 0x00FF00) >> 8);
    writeCmd[3] = (unsigned char)((regVal & 0x0000FF) >> 0);

    HAL_SPI_Transmit(&hspi2, &(writeCmd[0]), (uint16_t) sizeof(writeCmd[0]), 50);
    HAL_Delay(500);
    HAL_SPI_Transmit(&hspi2, &(writeCmd[1]), (uint16_t) sizeof(writeCmd[1]), 50);
    HAL_Delay(500);
    HAL_SPI_Transmit(&hspi2, &(writeCmd[2]), (uint16_t) sizeof(writeCmd[2]), 50);
    HAL_Delay(500);
    HAL_SPI_Transmit(&hspi2, &(writeCmd[3]), (uint16_t) sizeof(writeCmd[3]), 50);
    HAL_Delay(500);
}

In the hal_msp.c :

void HAL_SPI_MspInit(SPI_HandleTypeDef* hspi)
{

  GPIO_InitTypeDef GPIO_InitStruct;
  if(hspi->Instance==SPI2)
  {
    /* Peripheral clock enable */
    __SPI2_CLK_ENABLE();

    /**SPI2 GPIO Configuration
    PC2     ------> SPI2_MISO
    PC3     ------> SPI2_MOSI
    PB10     ------> SPI2_SCK
    PB12     ------> SPI2_NSS
    */
    GPIO_InitStruct.Pin = GPIO_PIN_2|GPIO_PIN_3;
    GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
    GPIO_InitStruct.Pull = GPIO_NOPULL;
    GPIO_InitStruct.Speed = GPIO_SPEED_MEDIUM;
    GPIO_InitStruct.Alternate = GPIO_AF5_SPI2;
    HAL_GPIO_Init(GPIOC, &GPIO_InitStruct);

    GPIO_InitStruct.Pin = GPIO_PIN_10|GPIO_PIN_12;
    GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
    GPIO_InitStruct.Pull = GPIO_NOPULL;
    GPIO_InitStruct.Speed = GPIO_SPEED_MEDIUM;
    GPIO_InitStruct.Alternate = GPIO_AF5_SPI2;
    HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
  }

If you have any ideas or advice, thanks for helping!

EDIT

void MX_GPIO_Init(void)
{
   /* GPIO Ports Clock Enable */
   __GPIOC_CLK_ENABLE();
   __GPIOA_CLK_ENABLE();
   __GPIOB_CLK_ENABLE();
}

Body:
This might be the problem:

// [...]
hspi2.Init.NSS = SPI_NSS_SOFT;
// [...]

Without checking the definition of your HAL macros, I believe that this configures the SPI not to drive NSS - but to have this done by software. This means that you are responsible to assert the NSS pin manually before putting data into the SPI peripheral.

This in turn may cause the SPI slave side not to respond, which may appear like the SCK signals weren't reaching the slave at all.


问:
Why does this function need 'this' to be binded to it?
I am following a React tutorial and I noticed that I have a function that looks like this:

```<code>  onDeleteClick = (id, dispatch) => {
    console.log(id);
    // this is a function which is a part of the global state
    dispatch({ type: "DELETE_CONTACT", payload: id });
  };
</code>```

and in my form I have this:

```<code><i onClick={this.onDeleteClick.bind( this, this.props.id, dispatch)} className="fas fa-times" style={{ cursor: "pointer", float: "right", color: "red" }}></i>
</code>```

So, my question is why do I need to bind 'this' to onDeleteClick because I don't use state or any other class methods inside of onDeleteClick that would require 'this'. But, when I remove it, I get the error Uncaught TypeError: dispatch is not a function.

I see why 'this.props.id' and 'dispatch' need to be binded, but not sure why dispatch is no longer a function when I remove 'this' from this  tag.

Here is the full class:

```<code>import React, { Component } from "react";
import PropTypes from "prop-types";
import { Consumer } from "../../context";

class Contact extends Component {
  state = {
    showContactInfo: false,
    num: 1, // this is useless. just for testing things
  };

  // uses arrow function because otherwise we couldn't use 'this'
  onShowClick = (e) => {
    var newNum = this.state.num;
    newNum = newNum + 1;
    this.setState({
      showContactInfo: !this.state.showContactInfo,
      num: newNum,
    });
  };

  onDeleteClick = (id, dispatch) => {
    console.log(id);
    // this is a function which is a part of the global state
    dispatch({ type: "DELETE_CONTACT", payload: id });
  };

  render() {
    //pull boolean out of this.state
    const { showContactInfo } = this.state;
    return (
      <Consumer>
        {(value) => {
          const { dispatch } = value;
          return (
            <div className="card card-body mb-3">
              <h4>
                {this.props.name}
                <i
                  onClick={this.onShowClick}
                  className="fas fa-sort-down"
                  style={{ cursor: "pointer" }}
                ></i>
                <i
                  onClick={this.onDeleteClick.bind(
                    this,
                    this.props.id,
                    dispatch
                  )}
                  className="fas fa-times"
                  style={{ cursor: "pointer", float: "right", color: "red" }}
                ></i>
              </h4>
              {showContactInfo ? (
                <ul className="list-group">
                  <li className="list-group-item">Email: {this.props.email}</li>
                  <li className="list-group-item">Phone: {this.props.phone}</li>
                </ul>
              ) : null}
            </div>
          );
        }}
      </Consumer>
    );
  }
}

Contact.propTypes = {
  name: PropTypes.string.isRequired,
  email: PropTypes.string.isRequired,
  phone: PropTypes.string.isRequired,
};

export default Contact;
</code>```

答:
But, when I remove it, I get the error Uncaught TypeError: dispatch is not a function

What did you change it to when you removed it? I'm guessing this:

```<code>this.onDeleteClick.bind(this.props.id, dispatch)
</code>```

If so, that's telling .bind that you want this to equal this.props.id, and the 0th argument (id) to be dispatch. The 1st argument (dispatch) will not be bound to anything.

If you like, you could set this equal to null or undefined:

```<code>this.onDeleteClick.bind(null, this.props.id, dispatch)
</code>```

But this doesn't really gain you anything, and if you ever modify onDeleteClick to use this you may need to fix the binding anyway. So you might as well bind this to begin with.

Body:
I am following a React tutorial and I noticed that I have a function that looks like this:

  onDeleteClick = (id, dispatch) => {
    console.log(id);
    // this is a function which is a part of the global state
    dispatch({ type: "DELETE_CONTACT", payload: id });
  };

and in my form I have this:

So, my question is why do I need to bind 'this' to onDeleteClick because I don't use state or any other class methods inside of onDeleteClick that would require 'this'. But, when I remove it, I get the error Uncaught TypeError: dispatch is not a function.

I see why 'this.props.id' and 'dispatch' need to be binded, but not sure why dispatch is no longer a function when I remove 'this' from this  tag.

Here is the full class:

import React, { Component } from "react";
import PropTypes from "prop-types";
import { Consumer } from "../../context";

class Contact extends Component {
  state = {
    showContactInfo: false,
    num: 1, // this is useless. just for testing things
  };

  // uses arrow function because otherwise we couldn't use 'this'
  onShowClick = (e) => {
    var newNum = this.state.num;
    newNum = newNum + 1;
    this.setState({
      showContactInfo: !this.state.showContactInfo,
      num: newNum,
    });
  };

  onDeleteClick = (id, dispatch) => {
    console.log(id);
    // this is a function which is a part of the global state
    dispatch({ type: "DELETE_CONTACT", payload: id });
  };

  render() {
    //pull boolean out of this.state
    const { showContactInfo } = this.state;
    return (
      <Consumer>
        {(value) => {
          const { dispatch } = value;
          return (

                {this.props.name}

              {showContactInfo ? (

Email: {this.props.email}

Phone: {this.props.phone}

              ) : null}

          );
        }}
      </Consumer>
    );
  }
}

Contact.propTypes = {
  name: PropTypes.string.isRequired,
  email: PropTypes.string.isRequired,
  phone: PropTypes.string.isRequired,
};

export default Contact;

Body:
But, when I remove it, I get the error Uncaught TypeError: dispatch is not a function

What did you change it to when you removed it? I'm guessing this:

this.onDeleteClick.bind(this.props.id, dispatch)

If so, that's telling .bind that you want this to equal this.props.id, and the 0th argument (id) to be dispatch. The 1st argument (dispatch) will not be bound to anything.

If you like, you could set this equal to null or undefined:

this.onDeleteClick.bind(null, this.props.id, dispatch)

But this doesn't really gain you anything, and if you ever modify onDeleteClick to use this you may need to fix the binding anyway. So you might as well bind this to begin with.


问:
Node + Docker Compose: Development and production setup
I'm looking for a solution to have both a development and a production environment in my project using docker, docker-compose and nodejs.

How do I approach this?

Basically what I want is a command to start my docker production environment, and a command to start my development environment (which could use nodemon for example).

Here is my Dockerfile

```<code>FROM node:13-alpine

RUN mkdir /app

WORKDIR /app

COPY . /app

RUN npm install

RUN npm run build

EXPOSE 1234

CMD ["npm", "run", "prod"] # <--- Have a possibility to run something like "npm run dev" here instead
</code>```

docker-compose.yml

```<code>version: "3"
services:
    findus:
        build: .
        ports:
            - "1234:1234"
        links:
            - mongo
        container_name: myapp
    mongo:
        image: mongo
        restart: always
        ports:
            - "4444:4444"
</code>```

package.json

```<code>// ...
    "scripts": {
        "build": "tsc",
        "dev": "nodemon source/index.ts",
        "prod": "node build/index.js"
    },
// ...
</code>```

答:
One way to do it is to create two "targets" on your Dockerfile like this:

Dockerfile:

```<code>FROM node:13-alpine As development

RUN mkdir /app

WORKDIR /app

COPY package*.json ./

RUN npm install

COPY . .

RUN npm run build

FROM node:13-alpine as production

ARG NODE_ENV=production
ENV NODE_ENV=${NODE_ENV}

WORKDIR /app

COPY package*.json ./

RUN npm install --only=production

COPY . .

COPY --from=development /app/dist ./dist

CMD ["node", "dist/index.js"]
</code>```

And them on your docker-compose run only the Development version:

```<code>version: '3.7'

services:
  main:
    container_name: main
    build:
      context: .
      target: development
    command: npm run dev
...
</code>```

So on your dev environment, you can run:

docker-compose up

and them in prod you can run docker directly with

docker run --target production

I'm assuming that when you run "npm run build" you are generating a dist/production folder so it's better to run node there instead of running straight at index.js on your root folder.

Body:
I'm looking for a solution to have both a development and a production environment in my project using docker, docker-compose and nodejs.

How do I approach this?

Basically what I want is a command to start my docker production environment, and a command to start my development environment (which could use nodemon for example).

Here is my Dockerfile

FROM node:13-alpine

RUN mkdir /app

WORKDIR /app

COPY . /app

RUN npm install

RUN npm run build

EXPOSE 1234

CMD ["npm", "run", "prod"] # <--- Have a possibility to run something like "npm run dev" here instead

docker-compose.yml

version: "3"
services:
    findus:
        build: .
        ports:
            - "1234:1234"
        links:
            - mongo
        container_name: myapp
    mongo:
        image: mongo
        restart: always
        ports:
            - "4444:4444"

package.json

// ...
    "scripts": {
        "build": "tsc",
        "dev": "nodemon source/index.ts",
        "prod": "node build/index.js"
    },
// ...

Body:
One way to do it is to create two "targets" on your Dockerfile like this:

Dockerfile:

FROM node:13-alpine As development

RUN mkdir /app

WORKDIR /app

COPY package*.json ./

RUN npm install

COPY . .

RUN npm run build

FROM node:13-alpine as production

ARG NODE_ENV=production
ENV NODE_ENV=${NODE_ENV}

WORKDIR /app

COPY package*.json ./

RUN npm install --only=production

COPY . .

COPY --from=development /app/dist ./dist

CMD ["node", "dist/index.js"]

And them on your docker-compose run only the Development version:

version: '3.7'

services:
  main:
    container_name: main
    build:
      context: .
      target: development
    command: npm run dev
...

So on your dev environment, you can run:

docker-compose up

and them in prod you can run docker directly with

docker run --target production

I'm assuming that when you run "npm run build" you are generating a dist/production folder so it's better to run node there instead of running straight at index.js on your root folder.


问:
React Router conditional routing component flashing/flickering
I'm trying to render some components only if the user is signed in. Whether the user is signed in is determined by current user object stored in a redux store. The problem is that the main App component, which contains the routes, does not receive the current user object to its' props instantly before its' first render call. Consequently, it redirects to Login page. After a second or two, the main App component finally receives the object into its' props and redirects where it should have in the first place.

I've tried to move the condition into the render method of the actual component, but still that component does not receive user object as props from redux store before its' first render, resulting in that same 'flash' of login page.

```<code>class App extends React.Component {
    constructor() {
        super();
    }

    unsubscribeFromAuth = null;

    async componentDidMount(): void {
        this.unsubscribeFromAuth = await auth.onAuthStateChanged(async userAuth => {
            if (userAuth) {
                await this.props.setCurrentUser(userAuth);
            }
        })
    }

    componentWillUnmount(): void {
        this.unsubscribeFromAuth();
    }

    render() {
        return (
            <div>
                <Navbar />
                <BrowserRouter history={history}>
                    <div>
                    <Switch>
                        <Route exact={true} path={'/register'} render={() => this.props.currentUser
                                                                            ? <Profile/>
                                                                            : <Register/>}/>
                        <Route exact={true} path={'/profile'} render={() => this.props.currentUser
                            ? <Profile/>
                            : <Login/>}/>
                        <Route exact={true} path={'/login'} render={() => this.props.currentUser
                                                                        ? <Events/>
                                                                        : <Login/>}/>
                        <Route exact={true} path={'/events'} render={() => this.props.currentUser
                                                                         ? <Events/> : <Login/>}/>
                        <Route exact={true} path={'/my_events'} render={() => this.props.currentUser
                                                                            ? <MyEvents/> : <Login/>}/>
                        <Route exact={true} path={'/new_event'} render={() => this.props.currentUser
                                                                            ? <NewEvent/> : <Login/>}/>
                        <Route exact={true} path={'/edit_event'} render={() => this.props.currentUser
                                                                        ? <EventEdit/>
                                                                        : <Login/>}/>
                        <Route exact={true} path={'/apply-to-event'} render={() => this.props.currentUser
                                                                                ? <ApplyToEvent/>
                                                                                : <Login/>}/>
                        <Route path={'/'} render={() => this.props.currentUser
                            ? <Events/>
                            : <Login/>}/>
                    </Switch>
                    </div>
                </BrowserRouter>
            </div>
        );
    }
}

const mapStateToProps = ({ user }) => ({
    currentUser: user.currentUser
});

const mapDispatchToProps = (dispatch) => ({
    setCurrentUser: async user => await dispatch(setCurrentUser(user))
});

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(App);
</code>```

I would like to find a way how to render the component without the flashing/flickering of the Login component.

答:
If i understood your code correctly, it appears me that problem is not router code but logic of redux auth state.

First of all; componentDidMount always work after first render. So you can never achieve what you want in componentDidMount. You will always miss first render. It will remember the auth state and won't need to fetch to server to know it.

If you wanna know auth info during first render, you should use localStorage or asyncStorage( forReact Native). So that you would know by the first render.

If you insist to not use localStorage; you might show some loading screen until you update the auth state. So react router won't have chance to route to login page and return back.

Body:
I'm trying to render some components only if the user is signed in. Whether the user is signed in is determined by current user object stored in a redux store. The problem is that the main App component, which contains the routes, does not receive the current user object to its' props instantly before its' first render call. Consequently, it redirects to Login page. After a second or two, the main App component finally receives the object into its' props and redirects where it should have in the first place.

I've tried to move the condition into the render method of the actual component, but still that component does not receive user object as props from redux store before its' first render, resulting in that same 'flash' of login page.

class App extends React.Component {
    constructor() {
        super();
    }

    unsubscribeFromAuth = null;

    async componentDidMount(): void {
        this.unsubscribeFromAuth = await auth.onAuthStateChanged(async userAuth => {
            if (userAuth) {
                await this.props.setCurrentUser(userAuth);
            }
        })
    }

    componentWillUnmount(): void {
        this.unsubscribeFromAuth();
    }

    render() {
        return (

                <Navbar />
                <BrowserRouter history={history}>

                    <Switch>
                        <Route exact={true} path={'/register'} render={() => this.props.currentUser
                                                                            ? <Profile/>
                                                                            : <Register/>}/>
                        <Route exact={true} path={'/profile'} render={() => this.props.currentUser
                            ? <Profile/>
                            : <Login/>}/>
                        <Route exact={true} path={'/login'} render={() => this.props.currentUser
                                                                        ? <Events/>
                                                                        : <Login/>}/>
                        <Route exact={true} path={'/events'} render={() => this.props.currentUser
                                                                         ? <Events/> : <Login/>}/>
                        <Route exact={true} path={'/my_events'} render={() => this.props.currentUser
                                                                            ? <MyEvents/> : <Login/>}/>
                        <Route exact={true} path={'/new_event'} render={() => this.props.currentUser
                                                                            ? <NewEvent/> : <Login/>}/>
                        <Route exact={true} path={'/edit_event'} render={() => this.props.currentUser
                                                                        ? <EventEdit/>
                                                                        : <Login/>}/>
                        <Route exact={true} path={'/apply-to-event'} render={() => this.props.currentUser
                                                                                ? <ApplyToEvent/>
                                                                                : <Login/>}/>
                        <Route path={'/'} render={() => this.props.currentUser
                            ? <Events/>
                            : <Login/>}/>
                    </Switch>

                </BrowserRouter>

        );
    }
}

const mapStateToProps = ({ user }) => ({
    currentUser: user.currentUser
});

const mapDispatchToProps = (dispatch) => ({
    setCurrentUser: async user => await dispatch(setCurrentUser(user))
});

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(App);

I would like to find a way how to render the component without the flashing/flickering of the Login component.


问:
how to show a loading page for some n seconds
I want to show some loading content for some seconds then I want to show the first page, loading page content some thing lik</p>

```<code><div class="well-bgs">Loading..</div>
</code>```

答:
Ok, I'll guess...

```<code>    $.mobile.pageLoading();

//when it's loaded
    $.mobile.pageLoading( true );
</code>```

http://jquerymobile.com/demos/1.0a4.1/#docs/api/methods.html

Body:
I want to show some loading content for some seconds then I want to show the first page, loading page content some thing lik

Loading..

Body:
Ok, I'll guess...

    $.mobile.pageLoading();

//when it's loaded
    $.mobile.pageLoading( true );

http://jquerymobile.com/demos/1.0a4.1/#docs/api/methods.html


答:
What you want is the product of each list values[0] * values[1] * values[2]

```<code>from itertools import product
values = ['abc', 'def', 'ghi']
result = list(map("".join, product(*values)))
</code>```

CODE DEMO

Title: How to generate a unique list of 3 character prefixes

Body:
What you want is the product of each list values[0] * values[1] * values[2]

from itertools import product
values = ['abc', 'def', 'ghi']
result = list(map("".join, product(*values)))

CODE DEMO


问:
Method to display monthly compounding values?
I'm new to Object Orientated Programming and I need to come up with a way to display values for each month which are compounded by a specific interest rate. I was originally thinking of a list and having each value in the list compounded by the previous value but I have no idea how to actually implement this.

The user at the moment can specify their initial investment and get their final value at the end of the period using the following formula:

```<code>double initialInvestmentReturn = Math.Pow(1 + ((InterestRate / 100) / 12), 12 * numberOfYears + (numberOfMonths)) * initialInvestment;
</code>```

The user should then be able to specify a constant monthly investment to be compounded monthly and tallied up at the end. To find the monthly return on just one month, this is the formula I have used:

```<code>double monthlyInterestReturn = Math.Pow(1 + ((InterestRate / 100) / 12), 1) * monthlyInvestment;
</code>```

And this is the method I'm attempting to use currently:

```<code>ArrayList monthlyValues = new ArrayList();
            int counter = 0;

            while (0 == 0)
            {
                monthlyValues.Add(monthlyInterestReturn);

                if (monthlyValues.Count == numberOfMonths + (numberOfYears * 12))
                {
                    break;
                }

            }

            foreach (double d in monthlyValues)
            {
                counter++;
                double var = monthlyInvestment * counter;
                double result = Math.Pow(1 + ((InterestRate / 100) / 12), counter) * var;

                rtfTestBox.Text += result.ToString("#.##") + Environment.NewLine;

            }
</code>```

Since the only applicable data structure I've been taught fully is Array/ArrayList (which I'm told is obsolete by SO users) I've tried to find a way to set the next value in the AL to the compounded value of the previous index value but to no avail. The output I'm getting is below which as you can see isn't quite correct.

```<code>//100 invested per month for 3 years 0 months at 12% annual interest:
    101
    204.02
    309.09
    416.24
    525.51
    636.91
    750.49
    866.29
    984.32
    1104.62
    1227.24
    1352.19
    1479.52
    1609.26
    1741.45
    1876.13
    2013.32
    2153.07
    2295.41
    2440.38
    2588.02
    2738.37
    2891.47
    3047.36
    3206.08
    3367.67
    3532.16
    3699.61
    3870.06
    4043.55
    4220.11
    4399.81
    4582.68
    4768.76
    4958.11
    5150.77
</code>```

The project is a .NET C# application in visual studio.

Any help would be greatly appreciated and I'd be more than happy to provide more detail if necessary.

Thanks in advance!

答:
As you mentions, ArrayList is obsolete. The goto datastructure in c# is List<T>. When we talk about money the recommended type is decimal this avoids some rounding issues with the other floating point types.

For this case we can use something called iterator block for even more convenience:

```<code>    public static IEnumerable<decimal> CompoundIntrest(decimal initialAmount, decimal yearlyIntrestRatePercent, decimal monthlyInvestmentRate)
    {
        var montlyIntrest = 1 + yearlyIntrestRatePercent / (1200);
        var currentAmount = initialAmount;
        while (true)
        {
            yield return currentAmount;
            currentAmount = currentAmount * montlyIntrest + monthlyInvestmentRate;
        }
    }
</code>```

Called like

```<code>        var amounts = CompoundIntrest(100, 12, 100).Take(36);
        foreach(var a in amounts)
        {
            Console.WriteLine(a.ToString("N1"));
        }
</code>```

Note the Take(36), this determines how many months to take values from, preventing an infinite loop. There is also use the ToList method to convert it to an actual list.

Body:
I'm new to Object Orientated Programming and I need to come up with a way to display values for each month which are compounded by a specific interest rate. I was originally thinking of a list and having each value in the list compounded by the previous value but I have no idea how to actually implement this.

The user at the moment can specify their initial investment and get their final value at the end of the period using the following formula:

double initialInvestmentReturn = Math.Pow(1 + ((InterestRate / 100) / 12), 12 * numberOfYears + (numberOfMonths)) * initialInvestment;

The user should then be able to specify a constant monthly investment to be compounded monthly and tallied up at the end. To find the monthly return on just one month, this is the formula I have used:

double monthlyInterestReturn = Math.Pow(1 + ((InterestRate / 100) / 12), 1) * monthlyInvestment;

And this is the method I'm attempting to use currently:

ArrayList monthlyValues = new ArrayList();
            int counter = 0;

            while (0 == 0)
            {
                monthlyValues.Add(monthlyInterestReturn);

                if (monthlyValues.Count == numberOfMonths + (numberOfYears * 12))
                {
                    break;
                }

            }

            foreach (double d in monthlyValues)
            {
                counter++;
                double var = monthlyInvestment * counter;
                double result = Math.Pow(1 + ((InterestRate / 100) / 12), counter) * var;

                rtfTestBox.Text += result.ToString("#.##") + Environment.NewLine;

            }

Since the only applicable data structure I've been taught fully is Array/ArrayList (which I'm told is obsolete by SO users) I've tried to find a way to set the next value in the AL to the compounded value of the previous index value but to no avail. The output I'm getting is below which as you can see isn't quite correct.

//100 invested per month for 3 years 0 months at 12% annual interest:
    101
    204.02
    309.09
    416.24
    525.51
    636.91
    750.49
    866.29
    984.32
    1104.62
    1227.24
    1352.19
    1479.52
    1609.26
    1741.45
    1876.13
    2013.32
    2153.07
    2295.41
    2440.38
    2588.02
    2738.37
    2891.47
    3047.36
    3206.08
    3367.67
    3532.16
    3699.61
    3870.06
    4043.55
    4220.11
    4399.81
    4582.68
    4768.76
    4958.11
    5150.77

The project is a .NET C# application in visual studio.

Any help would be greatly appreciated and I'd be more than happy to provide more detail if necessary.

Thanks in advance!

Body:
As you mentions, ArrayList is obsolete. The goto datastructure in c# is List<T>. When we talk about money the recommended type is decimal this avoids some rounding issues with the other floating point types.

For this case we can use something called iterator block for even more convenience:

    public static IEnumerable<decimal> CompoundIntrest(decimal initialAmount, decimal yearlyIntrestRatePercent, decimal monthlyInvestmentRate)
    {
        var montlyIntrest = 1 + yearlyIntrestRatePercent / (1200);
        var currentAmount = initialAmount;
        while (true)
        {
            yield return currentAmount;
            currentAmount = currentAmount * montlyIntrest + monthlyInvestmentRate;
        }
    }

Called like

        var amounts = CompoundIntrest(100, 12, 100).Take(36);
        foreach(var a in amounts)
        {
            Console.WriteLine(a.ToString("N1"));
        }

Note the Take(36), this determines how many months to take values from, preventing an infinite loop. There is also use the ToList method to convert it to an actual list.


问:
Lotusscript MIME Email
I modified a code that I found to send MIME HTML mails with attachments.
It works when the mail is open in gmail, but in Apple Mail or Lotus Notes there isn't any attachment in the body.
The plaintext part does not arrive either, but what interests me are the attachments.

Here is my code:

```<code>    Set MailDoc     = New NotesDocument( mailbox )
    session.convertMIME = False
    Dim body As NotesMIMEEntity
    Dim mimeHeader As NotesMIMEHeader
    Dim mimeEntity As NotesMIMEEntity
    Dim stream As NotesStream
</code>```

Set body = mailDoc.CreateMIMEEntity

```<code>    Set mimeHeader = body.CreateHeader({MIME-Version})
    Call mimeHeader.SetHeaderVal("1.0")
    Set mimeHeader = body.CreateHeader("Content-Type")
    Call mimeHeader.SetHeaderValAndParams({multipart/alternative;boundary="=NextPart_="})

    ' create another MIME part for the attachment. (repeat as needed)
    If (docEval.HasItem("$File")) Then
        Dim AttachmentsField As NotesRichTextItem
        Set AttachmentsField = docEval.GetFirstItem( "fc_adjunto" )
        If IsArray(AttachmentsField.EmbeddedObjects) Then ' Isarray validates for attachments ignoring embedded text
            ForAll att In AttachmentsField.EmbeddedObjects
                If att.Type = EMBED_ATTACHMENT Then
                    Call errorLog.LogAction("Inicio attch: " + att.Name())
                    Set mimeEntity = body.CreateChildEntity( )
                    Set mimeHeader = mimeEntity.CreateHeader("Content-Disposition")
                    aliasFilename = CStr(att.Name())
                    Call mimeHeader.SetHeaderValAndParams(|attachment; filename=| & aliasFilename)
                    Set stream = session.CreateStream
                    attachFilename = AttachToFile(session, docEval, CStr(att.Name()))  'Call o.ExtractFile(Attachfoldername & "\" & o.Name())
                    Call errorLog.LogAction("Inicio attch name: " + attachFilename)
                    stream.Open attachFileName, "binary"
                    Call mimeEntity.SetContentFromBytes(stream, "application/octet-stream", ENC_IDENTITY_BINARY)
                    mimeEntity.EncodeContent(ENC_BASE64)
                    Kill attachFilename
                End If
            End ForAll
        End If
    End If

    'Send the plain text part first (this never work for me!!)
    Set mimeEntity = body.createChildEntity()
    Set stream = session.createStream()
    Call WritePlainText(stream)
    Call mimeEntity.setContentFromText(stream, {text/plain;charset="iso-8859-1"}, ENC_IDENTITY_8BIT)

    'Send the HTML part.
    Call stream.Truncate()

    'Send the HTML part.
    Set mimeEntity = body.createChildEntity()
    Call WriteHTML(stream, elHtml)
    Call mimeEntity.setContentFromText(stream, {text/html;charset="iso-8859-1"},ENC_IDENTITY_8BIT)
    'Close the stream and Send it
    Call stream.Truncate()
    Call stream.Close()

    Call maildoc.Closemimeentities(True)

    Call MailDoc.ReplaceItemValue("EncryptOnSend"   , True )
    Call MailDoc.ReplaceItemValue("PostedDate"      , Now )
    Call MailDoc.ReplaceItemValue("From"            , Remitente )
    Call MailDoc.ReplaceItemValue("SendFrom"        , Remitente )
    Call MailDoc.ReplaceItemValue("Principal"       , Remitente )
    Call MailDoc.ReplaceItemValue( "SendTo"         , sendTo )
    Call MailDoc.ReplaceItemValue( "CopyTo"         , copyTo )
    Call MailDoc.ReplaceItemValue( "BlindCopyTo"    , bccTo )
    Call MailDoc.ReplaceItemValue( "Subject"        , Subject )
    Call MailDoc.save( True , False ) 'Send it
    session.convertMIME = True
</code>```

Any idea what could I miss?
Thanks

答:
It looks to me like you are using only a multipart/alternative section. I don't see a multipart/mixed section. I believe that you need to have a nested structure like this:

```<code> multipart/mixed
   application/octet-stream
   application/octet-stream (etc...)
   multipart/alternative
     text/plain
     text/HTML
</code>```

Send yourself a hand-crafted email that looks the way that you want it to, and verify the MIME headers in the received message to be sure I've got this right ('View - Show - Page Source' in the Notes client or 'Show Original' in gmail), but I'm looking at several messages with attachments in my own inbox, and they've all got this structure.

Title: Lotusscript MIME Email

Body:
I modified a code that I found to send MIME HTML mails with attachments.
It works when the mail is open in gmail, but in Apple Mail or Lotus Notes there isn't any attachment in the body.
The plaintext part does not arrive either, but what interests me are the attachments.

Here is my code:

    Set MailDoc     = New NotesDocument( mailbox )
    session.convertMIME = False
    Dim body As NotesMIMEEntity
    Dim mimeHeader As NotesMIMEHeader
    Dim mimeEntity As NotesMIMEEntity
    Dim stream As NotesStream

Set body = mailDoc.CreateMIMEEntity

    Set mimeHeader = body.CreateHeader({MIME-Version})
    Call mimeHeader.SetHeaderVal("1.0")
    Set mimeHeader = body.CreateHeader("Content-Type")
    Call mimeHeader.SetHeaderValAndParams({multipart/alternative;boundary="=NextPart_="})

    ' create another MIME part for the attachment. (repeat as needed)
    If (docEval.HasItem("$File")) Then
        Dim AttachmentsField As NotesRichTextItem
        Set AttachmentsField = docEval.GetFirstItem( "fc_adjunto" )
        If IsArray(AttachmentsField.EmbeddedObjects) Then ' Isarray validates for attachments ignoring embedded text
            ForAll att In AttachmentsField.EmbeddedObjects
                If att.Type = EMBED_ATTACHMENT Then
                    Call errorLog.LogAction("Inicio attch: " + att.Name())
                    Set mimeEntity = body.CreateChildEntity( )
                    Set mimeHeader = mimeEntity.CreateHeader("Content-Disposition")
                    aliasFilename = CStr(att.Name())
                    Call mimeHeader.SetHeaderValAndParams(|attachment; filename=| & aliasFilename)
                    Set stream = session.CreateStream
                    attachFilename = AttachToFile(session, docEval, CStr(att.Name()))  'Call o.ExtractFile(Attachfoldername & "\" & o.Name())
                    Call errorLog.LogAction("Inicio attch name: " + attachFilename)
                    stream.Open attachFileName, "binary"
                    Call mimeEntity.SetContentFromBytes(stream, "application/octet-stream", ENC_IDENTITY_BINARY)
                    mimeEntity.EncodeContent(ENC_BASE64)
                    Kill attachFilename
                End If
            End ForAll
        End If
    End If

    'Send the plain text part first (this never work for me!!)
    Set mimeEntity = body.createChildEntity()
    Set stream = session.createStream()
    Call WritePlainText(stream)
    Call mimeEntity.setContentFromText(stream, {text/plain;charset="iso-8859-1"}, ENC_IDENTITY_8BIT)

    'Send the HTML part.
    Call stream.Truncate()

    'Send the HTML part.
    Set mimeEntity = body.createChildEntity()
    Call WriteHTML(stream, elHtml)
    Call mimeEntity.setContentFromText(stream, {text/html;charset="iso-8859-1"},ENC_IDENTITY_8BIT)
    'Close the stream and Send it
    Call stream.Truncate()
    Call stream.Close()

    Call maildoc.Closemimeentities(True)

    Call MailDoc.ReplaceItemValue("EncryptOnSend"   , True )
    Call MailDoc.ReplaceItemValue("PostedDate"      , Now )
    Call MailDoc.ReplaceItemValue("From"            , Remitente )
    Call MailDoc.ReplaceItemValue("SendFrom"        , Remitente )
    Call MailDoc.ReplaceItemValue("Principal"       , Remitente )
    Call MailDoc.ReplaceItemValue( "SendTo"         , sendTo )
    Call MailDoc.ReplaceItemValue( "CopyTo"         , copyTo )
    Call MailDoc.ReplaceItemValue( "BlindCopyTo"    , bccTo )
    Call MailDoc.ReplaceItemValue( "Subject"        , Subject )
    Call MailDoc.save( True , False ) 'Send it
    session.convertMIME = True

Any idea what could I miss?
Thanks

Body:
It looks to me like you are using only a multipart/alternative section. I don't see a multipart/mixed section. I believe that you need to have a nested structure like this:

 multipart/mixed
   application/octet-stream
   application/octet-stream (etc...)
   multipart/alternative
     text/plain
     text/HTML

Send yourself a hand-crafted email that looks the way that you want it to, and verify the MIME headers in the received message to be sure I've got this right ('View - Show - Page Source' in the Notes client or 'Show Original' in gmail), but I'm looking at several messages with attachments in my own inbox, and they've all got this structure.


问:
divide the number by the sum
The user enters a number (c) and a number of decompositions (N).the program must decompose the number into a sum of numbers equal to the number of decompositions, but the difference between these numbers must not be greater than 1

for example:

```<code>c = 28 n = 3
print 9,9,10

c = 30 n = 3
print 10,10,10

c = 24 n = 7
print 3,3,3,3,4,4,4
</code>```

have no idea which algorithm implements this

答:
The number plus one needs to be taken c modulo n times. The number itself needs to be taken n minus c modulo n times.

If you write c as c = n * q + r with r smaller than n, you can rewrite it as follows:

```<code>c = n * q + r
c = (n - r + r) * q + r
c = (n - r) * q + r * q + r
c = (n - r) * q + r * (q + 1)
</code>```

In code, using a list to represent the result:

```<code>def split_in_parts(c, n):
    r = c % n
    return [c // n] * (n - r) + [c // n + 1] * r

c = 28
n = 3
print(split_in_parts(c, n))
</code>```

Title: divide the number by the sum

Body:
The user enters a number (c) and a number of decompositions (N).the program must decompose the number into a sum of numbers equal to the number of decompositions, but the difference between these numbers must not be greater than 1

for example:

c = 28 n = 3
print 9,9,10

c = 30 n = 3
print 10,10,10

c = 24 n = 7
print 3,3,3,3,4,4,4

have no idea which algorithm implements this

Body:
The number plus one needs to be taken c modulo n times. The number itself needs to be taken n minus c modulo n times.

If you write c as c = n * q + r with r smaller than n, you can rewrite it as follows:

c = n * q + r
c = (n - r + r) * q + r
c = (n - r) * q + r * q + r
c = (n - r) * q + r * (q + 1)

In code, using a list to represent the result:

def split_in_parts(c, n):
    r = c % n
    return [c // n] * (n - r) + [c // n + 1] * r

c = 28
n = 3
print(split_in_parts(c, n))


问:
How to pull integer from mySQL database and display in HTML document
I am trying to write a website that can display information from a mySQL database using PHP.

I have set up the database connection, I believe it is doing the query but it is not displaying the query. It stops displaying data after the first variable is echoed in the code.

I attempted the query directly in mySQL and it gave me the response I wanted.

Here is the code for the HTML document:

EDIT: The value I am trying to display is an integer.

```<code><!DOCTYPE html>
<html>
    <head>
        <!-- Start Link Stylesheet -->
        <link rel="stylesheet" type="text/css" href="style.css" />
        <!-- End Link Stylesheet-->

        <!-- Start Meta Tags -->
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta charset="utf-8">
        <meta author="Cole K. Motuliak">
        <!-- End Meta Tags -->

        <title>sumstats - view stats</title>
    </head>

    <body>
        <header>
            <h1 class="center" id="bigger">JHS IT Summer Statistics Viewpage</h1>
        </header>
            <h1 class="center">Welcome</h1>
            <div class="center">
                <?php
                include 'view_stats.php';
                ?>

        </div>

        <footer>
            <p class="center">© 2020 Cole K. Motuliak | <a href="mailto:cmotuliak3@gmail.com">cmotuliak3@gmail.com</a></p>
        </footer>
    </body>

</html>
</code>```

Here is the PHP code

```<code><?php
                $servername = "localhost:3306"; // Define Server Domain Name / TCP port
                $username = "sumstats_viewonly"; // Define username
                $password = "*****"; // Define password, PASSWORD CHANGED FROM SCRIPT
                $dbname = "sumstats_db"; // Define database name

                // Create connection
                $conn = new mysqli($servername, $username, $password, $dbname);
                // Check connection
                if ($conn->connect_error) {
                    die("Connection failed: " . $conn->connect_error);
                }
                $imaged_query = "SELECT imaged FROM sumstats_table";
                $tagged_query = "SELECT tagged FROM sumstats_table";
                $unboxed_query = "SELECT unboxed FROM sumstats_table";
                $imaged_int = $conn->query($imaged_query);
                $tagged_int = $conn->query($tagged_query);
                $unboxed_int = $conn->query($unboxed_query);
                echo "<p >Imaged Count:", $imaged_int, "EndTest</p>";
                echo "<p >Tagged Count:", $tagged_int, "EndTest</p>";
                echo "<p >Unboxed Count:", $unboxed_int, "EndTest</p>";
                $conn->close();

                ?>
</code>```

If anybody could assist and tell me what I am doing wrong, please let me know. Thanks!

答:
You need to fetch the data from the result resource. Since these are all simply columns in the same table, you can also fetch them all in a single query, as follows:</p>

```<code>$just_one_query = "SELECT imaged, tagged, unboxed FROM sumstats_table";
$result = $conn->query($just_one_query);
$counts = $result->fetch_assoc(); // Here the magic.

echo "<p >Imaged Count:", $counts['imaged'], "EndTest</p>";
echo "<p >Tagged Count:", $counts['tagged'], "EndTest</p>";
echo "<p >Unboxed Count:", $counts['unboxed'], "EndTest</p>";
</code>```

Body:
I am trying to write a website that can display information from a mySQL database using PHP.

I have set up the database connection, I believe it is doing the query but it is not displaying the query. It stops displaying data after the first variable is echoed in the code.

I attempted the query directly in mySQL and it gave me the response I wanted.

Here is the code for the HTML document:

EDIT: The value I am trying to display is an integer.

<!DOCTYPE html>

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

        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta charset="utf-8">
        <meta author="Cole K. Motuliak">

        <title>sumstats - view stats</title>

JHS IT Summer Statistics Viewpage

Welcome

                <?php
                include 'view_stats.php';
                ?>

© 2020 Cole K. Motuliak | cmotuliak3@gmail.com

Here is the PHP code

<?php
                $servername = "localhost:3306"; // Define Server Domain Name / TCP port
                $username = "sumstats_viewonly"; // Define username
                $password = "*****"; // Define password, PASSWORD CHANGED FROM SCRIPT
                $dbname = "sumstats_db"; // Define database name

                // Create connection
                $conn = new mysqli($servername, $username, $password, $dbname);
                // Check connection
                if ($conn->connect_error) {
                    die("Connection failed: " . $conn->connect_error);
                }
                $imaged_query = "SELECT imaged FROM sumstats_table";
                $tagged_query = "SELECT tagged FROM sumstats_table";
                $unboxed_query = "SELECT unboxed FROM sumstats_table";
                $imaged_int = $conn->query($imaged_query);
                $tagged_int = $conn->query($tagged_query);
                $unboxed_int = $conn->query($unboxed_query);
                echo "
Imaged Count:", $imaged_int, "EndTest
";
                echo "
Tagged Count:", $tagged_int, "EndTest
";
                echo "
Unboxed Count:", $unboxed_int, "EndTest
";
                $conn->close();

                ?>

If anybody could assist and tell me what I am doing wrong, please let me know. Thanks!

Body:
You need to fetch the data from the result resource. Since these are all simply columns in the same table, you can also fetch them all in a single query, as follows:

$just_one_query = "SELECT imaged, tagged, unboxed FROM sumstats_table";
$result = $conn->query($just_one_query);
$counts = $result->fetch_assoc(); // Here the magic.

echo "<p >Imaged Count:", $counts['imaged'], "EndTest</p>";
echo "<p >Tagged Count:", $counts['tagged'], "EndTest</p>";
echo "<p >Unboxed Count:", $counts['unboxed'], "EndTest</p>";


问:
How to properly call service methods from interceptor in angular
I am trying to build an error interceptor in my angular app. I imported the auth service into it through the constructor. But I am getting an error when I call a method from it that it does not exist. This is the interceptor.

```<code>
 import {Injectable } from '@angular/core';
 import {
    HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpErrorResponse
} from '@angular/common/http';
import { AuthService } from '../auth/auth.service';

import {Observable, throwError} from 'rxjs';
import { catchError } from 'rxjs/operators';
import { Router } from '@angular/router';

@Injectable()
export class ErrorInterceptor implements HttpInterceptor{

    constructor(
        private authService: AuthService,
    ){

    }
     intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>{

        return next.handle(req).pipe(
            catchError(this.handleError)
        );
    }

    private handleError(error: HttpErrorResponse) {
        if(error.status === 401){
            this.authService.logout();
        }
        return throwError(error);
    }
}

</code>```

And this is my auth-service.

```<code>import { Injectable } from '@angular/core';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
import {HttpClient, HttpErrorResponse} from '@angular/common/http';

@Injectable({
    providedIn: 'root'
})
export class AuthService {
    url = 'http://localhost:3000/users/login'
    isLoggedIn = false;
    constructor(private http: HttpClient) { }
    redirectUrl: string;

    login(credentials): Observable<any> {
        return this.http.post<any>(this.url, credentials).pipe(catchError(err => {
            return throwError(err);
        }));
    }

    logout(): void {
        localStorage.removeItem('token');
        this.isLoggedIn = false;
    }

    getAuthToken(): string{
        return localStorage.getItem('token');
    }
}
</code>```

After I try to run it, I get TypeError: Cannot read property 'logout' of undefined

答:
You need to use arrow function notation to denote the class using this keyword in callbacks. Try the following

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>{
  return next.handle(req).pipe(
    catchError((error) => this.handleError(error))    // <-- use arrow function here
  );
}
```

Body:
I am trying to build an error interceptor in my angular app. I imported the auth service into it through the constructor. But I am getting an error when I call a method from it that it does not exist. This is the interceptor.

 import {Injectable } from '@angular/core';
 import {
    HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpErrorResponse
} from '@angular/common/http';
import { AuthService } from '../auth/auth.service';

import {Observable, throwError} from 'rxjs';
import { catchError } from 'rxjs/operators';
import { Router } from '@angular/router';

@Injectable()
export class ErrorInterceptor implements HttpInterceptor{

    constructor(
        private authService: AuthService,
    ){

    }
     intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>{

        return next.handle(req).pipe(
            catchError(this.handleError)
        );
    }

    private handleError(error: HttpErrorResponse) {
        if(error.status === 401){
            this.authService.logout();
        }
        return throwError(error);
    }
}

And this is my auth-service.

import { Injectable } from '@angular/core';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
import {HttpClient, HttpErrorResponse} from '@angular/common/http';

@Injectable({
    providedIn: 'root'
})
export class AuthService {
    url = 'http://localhost:3000/users/login'
    isLoggedIn = false;
    constructor(private http: HttpClient) { }
    redirectUrl: string;

    login(credentials): Observable<any> {
        return this.http.post<any>(this.url, credentials).pipe(catchError(err => {
            return throwError(err);
        }));
    }

    logout(): void {
        localStorage.removeItem('token');
        this.isLoggedIn = false;
    }

    getAuthToken(): string{
        return localStorage.getItem('token');
    }
}

After I try to run it, I get TypeError: Cannot read property 'logout' of undefined


问:
Change TextMate live webpreview to use Chrome's Webkit
Currently Textmate uses Safari's Webkit to render the hmlt outputs for both commands and the live webpreview window.

Unfortunately for one specific project I am working with specific javascript API supported only be Firefox's gecko or Chrome's Webkit, it seems Safari still not supporting it.

Perhaps there's a way to globally change Safari for Chromium or Webkit Nightly?

答:
A support member of TextMate kindly answered my email asking for it by mentioning this url which definitely points to the right solution. I really didn't think it could be done so seamlessly and now I am very happy that it is possible.

Basically there are few steps to follow:

```<code>$ cd /Applications/TextMate.app/Contents/MacOS/
$ mv TextMate _TextMate
$ vim TextMate
</code>```

new TextMate file contains (note that you might want to change the path for the new  webkit framework to fit the one you like)

```<code>#!/bin/bash
env DYLD_FRAMEWORK_PATH=/Applications/WebKit.app/Contents/Frameworks/10.6/WEBKIT_UNSET_DYLD_FRAMEWORK_PATH=YES /Applications/TextMate.app/Contents/MacOS/_TextMate
</code>```

after saving the newly created file:

```<code>$ chmod a+x TextMate
</code>```

Close/Run TextMate :)

Or obvious if you just want to do this for each session you can simply use the bash command right away from terminal like this:

```<code>$ env DYLD_FRAMEWORK_PATH=/Applications/WebKit.app/Contents/Frameworks/10.6/ WEBKIT_UNSET_DYLD_FRAMEWORK_PATH=YES /Applications/TextMate.app/Contents/MacOS/TextMate
</code>```

This is really cool...one thing I've noticed after that is that my themes are no longer being displayed, have no clue about it but I will try to check the cause.

Body:
A support member of TextMate kindly answered my email asking for it by mentioning this url which definitely points to the right solution. I really didn't think it could be done so seamlessly and now I am very happy that it is possible.

Basically there are few steps to follow:

$ cd /Applications/TextMate.app/Contents/MacOS/
$ mv TextMate _TextMate
$ vim TextMate

new TextMate file contains (note that you might want to change the path for the new  webkit framework to fit the one you like)

#!/bin/bash
env DYLD_FRAMEWORK_PATH=/Applications/WebKit.app/Contents/Frameworks/10.6/WEBKIT_UNSET_DYLD_FRAMEWORK_PATH=YES /Applications/TextMate.app/Contents/MacOS/_TextMate

after saving the newly created file:

$ chmod a+x TextMate

Close/Run TextMate :)

Or obvious if you just want to do this for each session you can simply use the bash command right away from terminal like this:

$ env DYLD_FRAMEWORK_PATH=/Applications/WebKit.app/Contents/Frameworks/10.6/ WEBKIT_UNSET_DYLD_FRAMEWORK_PATH=YES /Applications/TextMate.app/Contents/MacOS/TextMate

This is really cool...one thing I've noticed after that is that my themes are no longer being displayed, have no clue about it but I will try to check the cause.