问:
hierarchical linear regression error in python
```<code>    with pm.Model() as hierarchical_model:
        # Hyperpriors for group nodes
        mu_a = pm.Normal('mu_a', mu=0., sigma=100)
        sigma_a = pm.HalfNormal('sigma_a', 5.)
        mu_b = pm.Normal('mu_b', mu=0., sigma=100)
        sigma_b = pm.HalfNormal('sigma_b', 5.)
        mu_c = pm.Normal('mu_c', mu=0., sigma=100)
        sigma_c = pm.HalfNormal('sigma_c', 5.)
        mu_d = pm.Normal('mu_d', mu=0., sigma=100)
        sigma_d = pm.HalfNormal('sigma_d', 5.)
        mu_e = pm.Normal('mu_e', mu=0., sigma=100)
        sigma_e = pm.HalfNormal('sigma_e', 5.)
        mu_f = pm.Normal('mu_f', mu=0., sigma=100)
        sigma_f = pm.HalfNormal('sigma_f', 5.)

        # Intercept for each county, distributed around group mean mu_a
        # Above we just set mu and sd to a fixed value while here we
        # plug in a common group distribution for all a and b (which are
        # vectors of length n_counties).
        a = pm.Normal('a', mu=mu_a, sigma=sigma_a, shape=n_school)
        # Intercept for each county, distributed around group mean mu_a
        b = pm.Normal('b', mu=mu_b, sigma=sigma_b, shape=n_school)
        c = pm.Normal('c', mu=mu_c, sigma=sigma_c, shape=n_school)
        d = pm.Normal('d', mu=mu_d, sigma=sigma_d, shape=n_school)
        e = pm.Normal('e', mu=mu_e, sigma=sigma_e, shape=n_school)
        f = pm.Normal('f', mu=mu_f, sigma=sigma_f, shape=n_school)

        # Model error
        eps = pm.HalfCauchy('eps', 5.)

        test_score_est = a[school_idx] + b[school_idx]*df.student_ses.values+ c[school_idx]*df.student_iq.values+ d[school_idx]*df.school_avrg._ses.values+ e[school_idx]*df.school_avrg._iq.values+ f[school_idx]*df.student_gender_0.values

        # Data likelihood
        test_like = pm.Normal('test_like', mu=test_score_est,
                               sigma=eps, observed=df.test_score)
</code>```

I get the following error

```<code>OUTPUT: IndexError: index 211 is out of bounds for size 211
</code>```

**Hi. I get this error for hierarchical regreson. n_school = 211 why am i getting an error like this? I will be grateful if you could help me. Thanks to everyone in advance.

below I provide information on how to calculate n_school and school_idx.**

```<code>school_idx=df.school_id.values
n_school=len(df.school_id.unique())
OUTPUT= n_school=211
</code>```

答: Python is 0-indexed, you have 211 elements in a list like data structure, the contents will be in indices [0,1,2,..,210] you have a size mismatch somewhere most likely based on this.

Body:
    with pm.Model() as hierarchical_model:
        # Hyperpriors for group nodes
        mu_a = pm.Normal('mu_a', mu=0., sigma=100)
        sigma_a = pm.HalfNormal('sigma_a', 5.)
        mu_b = pm.Normal('mu_b', mu=0., sigma=100)
        sigma_b = pm.HalfNormal('sigma_b', 5.)
        mu_c = pm.Normal('mu_c', mu=0., sigma=100)
        sigma_c = pm.HalfNormal('sigma_c', 5.)
        mu_d = pm.Normal('mu_d', mu=0., sigma=100)
        sigma_d = pm.HalfNormal('sigma_d', 5.)
        mu_e = pm.Normal('mu_e', mu=0., sigma=100)
        sigma_e = pm.HalfNormal('sigma_e', 5.)
        mu_f = pm.Normal('mu_f', mu=0., sigma=100)
        sigma_f = pm.HalfNormal('sigma_f', 5.)

        # Intercept for each county, distributed around group mean mu_a
        # Above we just set mu and sd to a fixed value while here we
        # plug in a common group distribution for all a and b (which are
        # vectors of length n_counties).
        a = pm.Normal('a', mu=mu_a, sigma=sigma_a, shape=n_school)
        # Intercept for each county, distributed around group mean mu_a
        b = pm.Normal('b', mu=mu_b, sigma=sigma_b, shape=n_school)
        c = pm.Normal('c', mu=mu_c, sigma=sigma_c, shape=n_school)
        d = pm.Normal('d', mu=mu_d, sigma=sigma_d, shape=n_school)
        e = pm.Normal('e', mu=mu_e, sigma=sigma_e, shape=n_school)
        f = pm.Normal('f', mu=mu_f, sigma=sigma_f, shape=n_school)

        # Model error
        eps = pm.HalfCauchy('eps', 5.)

        test_score_est = a[school_idx] + b[school_idx]*df.student_ses.values+ c[school_idx]*df.student_iq.values+ d[school_idx]*df.school_avrg._ses.values+ e[school_idx]*df.school_avrg._iq.values+ f[school_idx]*df.student_gender_0.values

        # Data likelihood
        test_like = pm.Normal('test_like', mu=test_score_est,
                               sigma=eps, observed=df.test_score)

I get the following error

OUTPUT: IndexError: index 211 is out of bounds for size 211

**Hi. I get this error for hierarchical regreson. n_school = 211 why am i getting an error like this? I will be grateful if you could help me. Thanks to everyone in advance.

below I provide information on how to calculate n_school and school_idx.**

school_idx=df.school_id.values
n_school=len(df.school_id.unique())
OUTPUT= n_school=211


来源: stackexchange

问:
How do I create an SNS subscription filter involving two attributes using the AWS CDK in Python?
I am setting up our AWS infrastructure using CDK in Python.  I want to subscribe an sqs queue to an SNS topic using a filter when the id is in a range and the type is one of two types.  The filter should look like this:

{
  "id": [{"numeric": [">", 0, "<", 100]}],
  "type": ["foo", "bar"]
}

This is what I have:

class MyStack(core.Stack):
    def init(self, scope: core.Construct, id: str, **kwargs) -> None:
        super().init(scope, id,  **kwargs)

```<code>    queue = sqs.Queue(self, "MyQueue")
    snsTopic = sns.Topic(self, "MyTopic", display_name="My Topic")

    idMapping = {"id":  sns.SubscriptionFilter(conditions=[{"numeric": [">", 0, "<", 100] } ])}
    typeMapping = {"type" : sns.SubscriptionFilter(conditions=["foo", "bar"])}

    sub = subs.SqsSubscription(queue, filter_policy = idMapping)
    snsTopic.add_subscription(sub)
</code>```

It seems to work if I set the filter_policy to either idMapping or typeMapping, but how do I do the AND of the two?

答:
just give one dict containing both keys

mapping = {"id": ...,"type" :...)}

ContentLicense: CC BY-SA 4.0

Body:
I am setting up our AWS infrastructure using CDK in Python.  I want to subscribe an sqs queue to an SNS topic using a filter when the id is in a range and the type is one of two types.  The filter should look like this:

{
  "id": [{"numeric": [">", 0, "<", 100]}],
  "type": ["foo", "bar"]
}

This is what I have:

class MyStack(core.Stack):
    def init(self, scope: core.Construct, id: str, **kwargs) -> None:
        super().init(scope, id,  **kwargs)

    queue = sqs.Queue(self, "MyQueue")
    snsTopic = sns.Topic(self, "MyTopic", display_name="My Topic")

    idMapping = {"id":  sns.SubscriptionFilter(conditions=[{"numeric": [">", 0, "<", 100] } ])}
    typeMapping = {"type" : sns.SubscriptionFilter(conditions=["foo", "bar"])}

    sub = subs.SqsSubscription(queue, filter_policy = idMapping)
    snsTopic.add_subscription(sub)

It seems to work if I set the filter_policy to either idMapping or typeMapping, but how do I do the AND of the two?


问:
Is there any data structure that has no duplicates but can have elements added to it while being iterated over?
I know a set has no duplicates but the issue is that I can't add elements to it while iterating over it using an iterator or for each loop. Is there any other way? Thank you.</p>

答:
The ConcurrentHashMap class can be used for this.  For example:

```<code>Set<T> set = Collections.newSetFromMap(new ConcurrentHashMap<T, Boolean>());
</code>```

(You can replace <T, Boolean> with <> and let the compiler infer the types.  I wrote it as above for illustrative purposes.)

The Collections::newSetFromMap javadoc says:

Returns a set backed by the specified map. The resulting set displays the same ordering, concurrency, and performance characteristics as the backing map. In essence, this factory method provides a Set implementation corresponding to any Map implementation.

Since ConcurrentHashMap allows simultaneous iteration and updates, so does the Set produced as above.  The catch is that an iteration may not see the effect of additions or removals made while iterating.

The concurrency properties of iteration can be inferred from the javadoc for ConcurrentHashMap.

Is there any other way.

It depends on your requirements, but there are potentially ways to avoid the problem.  For example, you could:

copy the set before iterating it, OR

add the new element to another new set and add the existing elements to the new set to the new set after ... or while ... iterating.

However, these these are unlikely to work without a concurrency bottleneck (e.g. 1.) or a differences in behavior (e.g. 2.)

Body:
The ConcurrentHashMap class can be used for this.  For example:

Set<T> set = Collections.newSetFromMap(new ConcurrentHashMap<T, Boolean>());

(You can replace <T, Boolean> with <> and let the compiler infer the types.  I wrote it as above for illustrative purposes.)

The Collections::newSetFromMap javadoc says:

Returns a set backed by the specified map. The resulting set displays the same ordering, concurrency, and performance characteristics as the backing map. In essence, this factory method provides a Set implementation corresponding to any Map implementation.

Since ConcurrentHashMap allows simultaneous iteration and updates, so does the Set produced as above.  The catch is that an iteration may not see the effect of additions or removals made while iterating.

The concurrency properties of iteration can be inferred from the javadoc for ConcurrentHashMap.

Is there any other way.

It depends on your requirements, but there are potentially ways to avoid the problem.  For example, you could:

copy the set before iterating it, OR

add the new element to another new set and add the existing elements to the new set to the new set after ... or while ... iterating.

However, these these are unlikely to work without a concurrency bottleneck (e.g. 1.) or a differences in behavior (e.g. 2.)


问:
@GetMapping is not getting imported
Image for clarification
I am new to Spring MVC and I am doing this project on maven. I was trying to import @GetMapping but it did not get imported. What could be the issue? Could someone please help me?</p>

```<code><!-- Spring dependencies --!>
        <!-- Spring IOC -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>5.2.3.RELEASE</version>
        </dependency>

        <!-- Spring container -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.3.RELEASE</version>
        </dependency>

        <!-- Spring JDBC -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.2.3.RELEASE</version>
        </dependency>

        <!-- Spring MVC -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>5.2.3.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.2.3.RELEASE</version>
        </dependency>
</code>```

答:
You need to describe import org.springframework.web.bind.annotation.GetMapping;, like this.

Eclipse quick fix function is useful.

Title: @GetMapping is not getting imported

Body:
Image for clarification
I am new to Spring MVC and I am doing this project on maven. I was trying to import @GetMapping but it did not get imported. What could be the issue? Could someone please help me?

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>5.2.3.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.3.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.2.3.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>5.2.3.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.2.3.RELEASE</version>
        </dependency>


问:
is it possible to get Oracle SQL Developer to escape output when exporting as inserts?
Is it possible, and if so, how, to tell Oracle SQL Developer to escape single quotes whenn exporting a table to inserts? It seems like an obvious thing to want to do, escape the character being used to quote fields when it occurs within the field, but I cannot find the option to do it.

Update: version 2.1.1.64, export method is. Context menu>export data>insert...

答:
I just tried it using SQL Developer 3.0.04, and it appears that the single quotes in data are escaped by default:

```<code>--------------------------------------------------------
--  File created - Wednesday-June-01-2011
--------------------------------------------------------
--------------------------------------------------------
--  DDL for Table T3
--------------------------------------------------------

  CREATE TABLE "THEUSER"."T3"
   ("C1" VARCHAR2(20 BYTE),
    "C2" VARCHAR2(20 BYTE)
   ) SEGMENT CREATION IMMEDIATE
     PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255 NOCOMPRESS LOGGING
     STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
     PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1
     BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
  TABLESPACE "USERS" ;
REM INSERTING into THEUSER.T3
Insert into THEUSER.T3 (C1,C2) values ('C1','C''2');
</code>```

I just had one row in the table, consisting of the values C1 and C'2.

ContentLicense: CC BY-SA 3.0

Body:
I just tried it using SQL Developer 3.0.04, and it appears that the single quotes in data are escaped by default:

--------------------------------------------------------
--  File created - Wednesday-June-01-2011
--------------------------------------------------------
--------------------------------------------------------
--  DDL for Table T3
--------------------------------------------------------

  CREATE TABLE "THEUSER"."T3"
   ("C1" VARCHAR2(20 BYTE),
    "C2" VARCHAR2(20 BYTE)
   ) SEGMENT CREATION IMMEDIATE
     PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255 NOCOMPRESS LOGGING
     STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
     PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1
     BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
  TABLESPACE "USERS" ;
REM INSERTING into THEUSER.T3
Insert into THEUSER.T3 (C1,C2) values ('C1','C''2');

I just had one row in the table, consisting of the values C1 and C'2.


问:
How do you get a flex grid to scale with page size instead of wrapping using css
5.30.20 EDIT: Works on stackoverflows code snippet viewer but not on chrome or any html hosting. Here's the hosted file:

https://unholytool.htmlpasta.com/

wondering what's going on.

Here's an image to show what I'm talking about

https://i.stack.imgur.com/ggQcF.png

So I'm new to CSS and I'm not finding a lot of luck on google.

I have a media query set up that works great for mobile, however I can't seem to get it to display correctly on different monitor sizes.

On very wide screens it works well and displays four columns and the left sidebar.

However as the screen shrinks it displays a wonky view of three images on one row and one image on the next row

This is my current display with the answer below

body {
  font-family: 'Montserrat';
  font-size: 18px;
}

.body {
  margin-left: 5%;
  margin-right: 5%;
}

.logo {
  display: block;
  margin-left: auto;
  margin-right: auto;
  width: 400px height:90px max-width: 30%;
}

.hero {
  display: block;
  margin-left: auto;
  margin-right: auto;
  max-width: 100%;
}

.leftsidebar {
  display: none;
}

.row {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  justify-content: center;
}

.column {
  margin-left: 1%;
  margin-right: 1%;
}

@media screen and (min-width: 1050px) {
  .row {
    display: flex;
    flex-wrap: nowrap;
    align-items: center;
    justify-content: center;
  }
  .column {
    flex: 1 1 auto;
  }

.container {
  display: grid;
}

.leftsidebar {
  grid-column: 1;
  display: inherit;
}

.products {
  grid-column: 2;
}

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!doctype html>
<html>

<head>
  <meta charset="utf-8">
  <title>Our Catalog</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="https://fonts.googleapis.com/css?family=Montserrat" rel='stylesheet'>
  <style>

  </style>
</head>

<body class="body">
  <div>
    <img class="logo" src="logoimg.jpeg">

  </div>
  <hr class="divider">
  <div>
    <picture>
      <source media="(max-width: 799px)" class="hero" srcset="heroimg1.jpeg, heroimg2.jpeg">
      <img class="hero" src="heroimg1.jpeg">
    </picture>
  </div>

  <hr class="divider">
  <div class="container">
    <div class="leftsidebar">
      <img src="img.jpeg" />
    </div>
    <div class="products">
      <div class="row">
        <div class="column">
          <img src="img.jpeg" />
          <h1> product</h1>
          <p>$100</p>
        </div>
        <div class="column">
          <img src="img.jpeg" />
          <h1> product</h1>
          <p>$100</p>
        </div>
        <div class="column">
          <img src="img.jpeg" />
          <h1> product</h1>
          <p>$100</p>
        </div>
        <div class="column">
          <img src="img.jpeg" />
          <h1> product</h1>
          <p>$100</p>
        </div>
      </div>
      <div class="row">
        <div class="column">
          <img src="img.jpeg" />
          <h1>product</h1>
          <p>$100</p>
        </div>
        <div class="column">
          <img src="img.jpeg" />
          <h1> product</h1>
          <p>$100</p>
        </div>
        <div class="column">
          <img src="img.jpeg" />
          <h1> product</h1>
          <p>$100</p>
        </div>
        <div class="column">
          <img src="img.jpeg" />
          <h1> product</h1>
          <p>$100</p>
        </div>
      </div>
      <div class="row">
        <div class="column">
          <img src="img.jpeg" />
          <h1> product</h1>
          <p>$100</p>
        </div>
        <div class="column">
          <img src="img.jpeg" />
          <h1> product</h1>
          <p>$100</p>
        </div>
        <div class="column">
          <img src="img.jpeg" />
          <h1> product</h1>
          <p>$100</p>
        </div>
        <div class="column">
          <img src="img.jpeg" />
          <h1> product</h1>
          <p>$100</p>
        </div>
      </div>
      <div class="row">
        <div class="column">
          <img src="img.jpeg" />
          <h1> product</h1>
          <p>$100</p>
        </div>
        <div class="column">
          <img src="img.jpeg" />
          <h1> product</h1>
          <p>$100</p>
        </div>
        <div class="column">
          <img src="img.jpeg" />
          <h1> product</h1>
          <p>$100</p>
        </div>
        <div class="column">
          <img src="img.jpeg" />
          <h1> product</h1>
          <p>$100</p>
        </div>
      </div>
    </div>
  </div>
  <hr class="divider">
  <br>
  <h3>Return Policy | Shipping Policy | Privacy Policy | About Us | Our Cause</h3>
  <br>
  <hr class="divider">

</body>

</html></code>```

I've tried a lot of stuff, including using both flex-shrink and flex-grow properties on all elements,

messing with height and width attributes setting them between auto and a %.

and setting a % with the flex property

Any ideas? I'm trying to keep javascript to a minimum so CSS only.

答:
I have configured your flexbox CSS and it should work as per your requirement. I have also added
 for every

.row {
  display: flex;
  flex-wrap: nowrap;
  align-items: center;
  justify-content: center;
}

.column {
  flex: 1 1 auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="row">
  <div class="column">
    <img src="image.jpeg" />
    <h1> text</h1>
    <p>text</p>
  </div>
  <div class="column">
    <img src="image.jpeg" />
    <h1> text</h1>
    <p>text</p>
  </div>
  <div class="column">
    <img src="image.jpeg" />
    <h1>text</h1>
    <p>text</p>
  </div>
  <div class="column">
    <img src="image.jpeg" />
    <h1>text</h1>
    <p>text</p>
  </div></code>```

Body:
5.30.20 EDIT: Works on stackoverflows code snippet viewer but not on chrome or any html hosting. Here's the hosted file:

https://unholytool.htmlpasta.com/

wondering what's going on.

Here's an image to show what I'm talking about

https://i.stack.imgur.com/ggQcF.png

So I'm new to CSS and I'm not finding a lot of luck on google.

I have a media query set up that works great for mobile, however I can't seem to get it to display correctly on different monitor sizes.

On very wide screens it works well and displays four columns and the left sidebar.

However as the screen shrinks it displays a wonky view of three images on one row and one image on the next row

This is my current display with the answer below

body {
  font-family: 'Montserrat';
  font-size: 18px;
}

.body {
  margin-left: 5%;
  margin-right: 5%;
}

.logo {
  display: block;
  margin-left: auto;
  margin-right: auto;
  width: 400px height:90px max-width: 30%;
}

.hero {
  display: block;
  margin-left: auto;
  margin-right: auto;
  max-width: 100%;
}

.leftsidebar {
  display: none;
}

.row {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  justify-content: center;
}

.column {
  margin-left: 1%;
  margin-right: 1%;
}

@media screen and (min-width: 1050px) {
  .row {
    display: flex;
    flex-wrap: nowrap;
    align-items: center;
    justify-content: center;
  }
  .column {
    flex: 1 1 auto;
  }

.container {
  display: grid;
}

.leftsidebar {
  grid-column: 1;
  display: inherit;
}

.products {
  grid-column: 2;
}

}

<!doctype html>

  <meta charset="utf-8">
  <title>Our Catalog</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="https://fonts.googleapis.com/css?family=Montserrat" rel='stylesheet'>

    <picture>
      <source media="(max-width: 799px)" class="hero" srcset="heroimg1.jpeg, heroimg2.jpeg">

    </picture>

 product

$100

 product

$100

 product

$100

 product

$100

product

$100

 product

$100

 product

$100

 product

$100

 product

$100

 product

$100

 product

$100

 product

$100

 product

$100

 product

$100

 product

$100

 product

$100

Return Policy | Shipping Policy | Privacy Policy | About Us | Our Cause

I've tried a lot of stuff, including using both flex-shrink and flex-grow properties on all elements,

messing with height and width attributes setting them between auto and a %.

and setting a % with the flex property

Any ideas? I'm trying to keep javascript to a minimum so CSS only.

Body:
I have configured your flexbox CSS and it should work as per your requirement. I have also added </div> for every <div class="column">

.row {
  display: flex;
  flex-wrap: nowrap;
  align-items: center;
  justify-content: center;
}

.column {
  flex: 1 1 auto;
}

<div class="row">
  <div class="column">
    <img src="image.jpeg" />
    <h1> text</h1>
    <p>text</p>
  </div>
  <div class="column">
    <img src="image.jpeg" />
    <h1> text</h1>
    <p>text</p>
  </div>
  <div class="column">
    <img src="image.jpeg" />
    <h1>text</h1>
    <p>text</p>
  </div>
  <div class="column">
    <img src="image.jpeg" />
    <h1>text</h1>
    <p>text</p>
  </div>


问:
what is the scope of this variable in c++?
If i define a function like this

```<code>std::string& returnstring(std::istringstream &ist)
{
    std::string temp;
    std::getline(ist,temp);
    return temp;
}
</code>```

and if i use this temp which is passed by reference to another function like this

```<code>void displaystring(std::string &temp)
{
    std::cout<<temp;
}
</code>```

would the string temp still be in scope when i pass it by reference to displaystring function?

答: this is the reference variable which refers to the current class object which has called it. it has scope only inside the class and the same as the lifetime of the object which called it.

Body:
If i define a function like this

std::string& returnstring(std::istringstream &ist)
{
    std::string temp;
    std::getline(ist,temp);
    return temp;
}

and if i use this temp which is passed by reference to another function like this

void displaystring(std::string &temp)
{
    std::cout<<temp;
}

would the string temp still be in scope when i pass it by reference to displaystring function?


问:
Enemies won't go visible after health reaches 0 - how to fix?
In my main loop I add health for the enemy. If I keep hitting the enemy and the health drops to 0, the enemy should disappear (enemys1.visible = False).

I ran the visible variable on my enemy class but for some reason the enemy wont go invisible and still shows up when its health reaches 0.

Here is a video of the problem in my game.

for bullet in bullets:
  if bullet.rect.colliderect(enemys1.hitbox):
    bullets.pop(bullets.index(bullet))
    if enemys1.health > 0:
      enemys1.health -= 1
    else:
      enemys1.visible = False # if my health reaches 0 the enemy should disappear but it doesnt
      print('hit')
```

<p>my enemy class:</p>

```class enemys:
    def __init__(self,x,y,height,width,end):
        self.x = x
        self.y =y
        self.esright = [pygame.image.load("esright1.png"),
        pygame.image.load("esright1.png"),
        pygame.image.load("esright2.png"),
        pygame.image.load("esright3.png"),
        pygame.image.load("esright4.png"),
        pygame.image.load("esright5.png"),
        pygame.image.load("esright6.png"),
        pygame.image.load("esright7.png"),
        pygame.image.load("esright8.png"),
        pygame.image.load("esright9.png"),
        pygame.image.load("esright10.png"),
        pygame.image.load("esright11.png"),
        pygame.image.load("esright12.png"),
        pygame.image.load("esright13.png"),
        pygame.image.load("esright14.png"),
        pygame.image.load("esright15.png"),
        pygame.image.load("esright16.png"),
        pygame.image.load("esright17.png"),
                          ]
        self.esleft = [pygame.image.load("esleft1.png"),
        pygame.image.load("esleft1.png"),
        pygame.image.load("esleft2.png"),
        pygame.image.load("esleft3.png"),
        pygame.image.load("esleft4.png"),
        pygame.image.load("esleft5.png"),
        pygame.image.load("esleft6.png"),
        pygame.image.load("esleft7.png"),
        pygame.image.load("esleft8.png"),
        pygame.image.load("esleft9.png"),
        pygame.image.load("esleft10.png"),
        pygame.image.load("esleft11.png"),
        pygame.image.load("esleft12.png"),
        pygame.image.load("esleft13.png"),
        pygame.image.load("esleft14.png"),
        pygame.image.load("esleft15.png"),
        pygame.image.load("esleft16.png"),
        pygame.image.load("esleft17.png"),
                          ]
        self.esright = [pygame.transform.scale(image,(image.get_width()//3,image.get_height()//3)) for image in self.esright]
        self.esleft = [pygame.transform.scale(image,(image.get_width()//3,image.get_height()//3)) for image in self.esleft]
        self.height = height
        self.width = width
        self.anim_index = 0
        self.distance = 80
        self.speed = 8
        self.vel = 3
        self.path = [x,end]
        self.Walking_index = 0
        self.hitbox = (self.x + 17, self.y + 2, 31, 57)
        self.rect = pygame.Rect(x,y,height,width)
        # enemys health
        self.health = 10
        self.visible = True

    # this makes the enemy move right and left
    def draw(self,window):
        self.move()
        if self.Walking_index + 1 >= 33:
            self.Walking_index = 0
        if self.vel > 0:
            window.blit(self.esright[self.Walking_index//3], (self.x,self.y))
            self.Walking_index += 1
        else:
            window.blit(self.esleft[self.Walking_index//3], (self.x,self.y))
            self.Walking_index += 1

# this moves the enemy left and right
    def move(self):
        if self.visible:
            if self.vel > 0:
               if self.x + self.vel < self.path[1]:
                   self.x += self.vel
               else:
                   self.vel = self.vel * -1
                   self.Walking_index = 0
            else:
               if self.x - self.vel >  self.path[0]:
                   self.x += self.vel
               else:
                   self.vel = self.vel * -1
                   self.Walking_index = 0
                # the hit box for the enemy the health
            pygame.draw.rect(window, (255,0,0), (self.hitbox[0], self.hitbox[1] - 20, 70, 10)) # NEW
            pygame.draw.rect(window, (0,255,0), (self.hitbox[0], self.hitbox[1] - 20, 70 - (5 * (10 - self.health)), 10))
            self.hitbox = (self.x + 47, self.y + 31, 50, 72)

# THIS PART MAKES  the enemy not scroll with the player
    def scroll(self,sx, sy):
        self.x += sx
        self.y += sy
        self.path[0] += sx
        self.path[1] += sx
```

答:
```<code>    for bullet in bullets: # never mind I fixed it
    if bullet.rect.colliderect(enemys1.hitbox):
        bullets.pop(bullets.index(bullet))
        if enemys1.health > 0:
            enemys1.health -= 1
        else:
            for one in range(len(enemying)-1,-1,-1):
                    del enemying[one]
</code>```

Body:
In my main loop I add health for the enemy. If I keep hitting the enemy and the health drops to 0, the enemy should disappear (enemys1.visible = False).

I ran the visible variable on my enemy class but for some reason the enemy wont go invisible and still shows up when its health reaches 0.

Here is a video of the problem in my game.

for bullet in bullets:
  if bullet.rect.colliderect(enemys1.hitbox):
    bullets.pop(bullets.index(bullet))
    if enemys1.health > 0:
      enemys1.health -= 1
    else:
      enemys1.visible = False # if my health reaches 0 the enemy should disappear but it doesnt
      print('hit')

my enemy class:

class enemys:
    def __init__(self,x,y,height,width,end):
        self.x = x
        self.y =y
        self.esright = [pygame.image.load("esright1.png"),
        pygame.image.load("esright1.png"),
        pygame.image.load("esright2.png"),
        pygame.image.load("esright3.png"),
        pygame.image.load("esright4.png"),
        pygame.image.load("esright5.png"),
        pygame.image.load("esright6.png"),
        pygame.image.load("esright7.png"),
        pygame.image.load("esright8.png"),
        pygame.image.load("esright9.png"),
        pygame.image.load("esright10.png"),
        pygame.image.load("esright11.png"),
        pygame.image.load("esright12.png"),
        pygame.image.load("esright13.png"),
        pygame.image.load("esright14.png"),
        pygame.image.load("esright15.png"),
        pygame.image.load("esright16.png"),
        pygame.image.load("esright17.png"),
                          ]
        self.esleft = [pygame.image.load("esleft1.png"),
        pygame.image.load("esleft1.png"),
        pygame.image.load("esleft2.png"),
        pygame.image.load("esleft3.png"),
        pygame.image.load("esleft4.png"),
        pygame.image.load("esleft5.png"),
        pygame.image.load("esleft6.png"),
        pygame.image.load("esleft7.png"),
        pygame.image.load("esleft8.png"),
        pygame.image.load("esleft9.png"),
        pygame.image.load("esleft10.png"),
        pygame.image.load("esleft11.png"),
        pygame.image.load("esleft12.png"),
        pygame.image.load("esleft13.png"),
        pygame.image.load("esleft14.png"),
        pygame.image.load("esleft15.png"),
        pygame.image.load("esleft16.png"),
        pygame.image.load("esleft17.png"),
                          ]
        self.esright = [pygame.transform.scale(image,(image.get_width()//3,image.get_height()//3)) for image in self.esright]
        self.esleft = [pygame.transform.scale(image,(image.get_width()//3,image.get_height()//3)) for image in self.esleft]
        self.height = height
        self.width = width
        self.anim_index = 0
        self.distance = 80
        self.speed = 8
        self.vel = 3
        self.path = [x,end]
        self.Walking_index = 0
        self.hitbox = (self.x + 17, self.y + 2, 31, 57)
        self.rect = pygame.Rect(x,y,height,width)
        # enemys health
        self.health = 10
        self.visible = True

    # this makes the enemy move right and left
    def draw(self,window):
        self.move()
        if self.Walking_index + 1 >= 33:
            self.Walking_index = 0
        if self.vel > 0:
            window.blit(self.esright[self.Walking_index//3], (self.x,self.y))
            self.Walking_index += 1
        else:
            window.blit(self.esleft[self.Walking_index//3], (self.x,self.y))
            self.Walking_index += 1

# this moves the enemy left and right
    def move(self):
        if self.visible:
            if self.vel > 0:
               if self.x + self.vel < self.path[1]:
                   self.x += self.vel
               else:
                   self.vel = self.vel * -1
                   self.Walking_index = 0
            else:
               if self.x - self.vel >  self.path[0]:
                   self.x += self.vel
               else:
                   self.vel = self.vel * -1
                   self.Walking_index = 0
                # the hit box for the enemy the health
            pygame.draw.rect(window, (255,0,0), (self.hitbox[0], self.hitbox[1] - 20, 70, 10)) # NEW
            pygame.draw.rect(window, (0,255,0), (self.hitbox[0], self.hitbox[1] - 20, 70 - (5 * (10 - self.health)), 10))
            self.hitbox = (self.x + 47, self.y + 31, 50, 72)

# THIS PART MAKES  the enemy not scroll with the player
    def scroll(self,sx, sy):
        self.x += sx
        self.y += sy
        self.path[0] += sx
        self.path[1] += sx


问:
.html files showing up as "listing directory" when opening live server
I am opening up a new file in a new folder in vscode. When I open up the new .html file in live server, it opens it up as a "listing directory." When I create a new file in an old folder it works perfectly fine. I tried creating different folders and they all open up as "listing directory." I even opened up the instructors file of the lesson in vscode and it gives me the same "listing directory" tab. Please help! Thank you!</p>

答:
1) First option is obviously setting the main html file named as index.html but as you mentioned it didn't work right!

well the file you are trying to open has also need to be opened in vs code too!

As you can see in the above screenshot it is not rendering the work.html

You must have to open the file in vscode editor also

Then you can simply press F1 and write open with live server


问:
Not able to get response with @Controller, while @RestController works fine
I am trying to map the URL /function/hash in my project to a specific HTML page html/hashcode.html. This is a spring boot project without using thymeleaf.

This is my code:

// package ...;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class FunctionController {
    @RequestMapping("/function/hash")
    public String hashPage(Model m) {
        return "html/hashcode.html";
    }
}
```

<p>The above code returns a 404 when I try to access <code>localhost:8080/function/hash</code>.</p>

<p>I also tried</p>

<pre class="lang-java prettyprint-override"><code>@Controller
@RequestMapping("/function")
public class FunctionController {
    @RequestMapping("/hash")
    public String hashPage(Model m) {
        return "html/hashcode.html";
    }
}
</code>```

which also yields a 404 when I go to localhost:8080/function/hash.

Directly using @RequestMapping("/hash") to map the page to /hash works, in case you wonder if the return value of the function is incorrect.

I also find that using multiple layer url like @RequestMapping("/api/test") is working in @RestController classes, but somehow it doesn't work in this @Controller class above.

答:
use path in request mapping.

Ex:

@RequestMapping(path="/hash")

Body:
I am trying to map the URL /function/hash in my project to a specific HTML page html/hashcode.html. This is a spring boot project without using thymeleaf.

This is my code:

// package ...;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class FunctionController {
    @RequestMapping("/function/hash")
    public String hashPage(Model m) {
        return "html/hashcode.html";
    }
}

The above code returns a 404 when I try to access localhost:8080/function/hash.

I also tried

@Controller
@RequestMapping("/function")
public class FunctionController {
    @RequestMapping("/hash")
    public String hashPage(Model m) {
        return "html/hashcode.html";
    }
}

which also yields a 404 when I go to localhost:8080/function/hash.

Directly using @RequestMapping("/hash") to map the page to /hash works, in case you wonder if the return value of the function is incorrect.

I also find that using multiple layer url like @RequestMapping("/api/test") is working in @RestController classes, but somehow it doesn't work in this @Controller class above.


问:
I am not allowed to run a python executable on other pcs
I was doing a game in tkinter, then I make it executable with PyInstaller and sent it to my friends so they can run it and tell me how it feels.
It seems that they could download the file, but can't open it because windows forbade them telling that it's not secure and not letting them choose to assume the risk or something.
They tried to run as administrator and still nothing changed.

What should I do or what I should add to my code so that windows can open it without problem and why windows opens other executable files without saying that(current error that my executable gets)?

答:
compress it as a .zip file and then it will most probably work

or install NSIS and create a windows installer for it.


问:
Using a signal to interrupt the main thread
I'm making a server/client TCP concurrent program in C. Everytime a client connects, the main thread of the server creates a new thread, to handle that client. After that, the main thread goes back to accept(), and stays stuck until another client connects.

However, I want the client to be able to close the server. For that, I assume I have to use signals. How can I approach this. I'm very new to signals. I don't know how to send a signal to a specific thread, or how I can use them here.

I want the client to write '..' and close the server.

Any ideas?

Thanks

答:
Though I understood your question, what puzzles me is, where do you use such a server ?. In any case, I hope you will make a good use of this server.

```<code>#include <signal.h>
#include <sys/socket.h>
#include <pthread.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>

void sigfunc(int signo)
{
    _exit(0); // safe to call in signal handler since it is async-signal-safe func
}

struct client_data {
    int clifd;
    pthread_t ptid;
};

void* client_func(void* _cli_data)
{
    struct client_data* cli_data = (struct client_data*) _cli_data;

    char buf[100];

    for( ; ; ) {
        int rd_status = read(cli_data->clifd, buf, sizeof(buf) - 1);

        if (rd_status <= 0)
            break;

        buf[rd_status] = '\0';
        printf("%s", buf);
        fflush(stdout);
    }

    close(cli_data->clifd);

    pthread_kill(cli_data->ptid, SIGRTMIN);
    return NULL;
}

int main()
{
    /* Setup a Listening server */

    struct sockaddr_in servaddr;
    memset(&servaddr, 0, sizeof(struct sockaddr_in));

    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    servaddr.sin_port = htons(8008);

    int sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

    if (bind(sockfd, (struct sockaddr*) &servaddr, sizeof(struct sockaddr_in)) != 0)
        exit(1);

    listen(sockfd, 5);

    /* Setup signal handler, use SIGRTMIN as sync signal */

    struct sigaction act;
    sigemptyset(&act.sa_mask);
    act.sa_flags = 0;

#ifdef SA_INTERRUPT
    act.sa_flags |= SA_INTERRUPT;
#endif

    act.sa_handler = sigfunc;

    sigaction(SIGRTMIN, &act, NULL);

    /* Loop and listen for connections */

    int addr_len;

    for ( ; ; ) {
        struct client_data cli_data;

        cli_data.ptid = pthread_self();
        addr_len = sizeof(struct sockaddr_in);
        cli_data.clifd = accept(sockfd, (struct sockaddr*) &servaddr, &addr_len);

        if (cli_data.clifd < 0)
            continue;

        pthread_t tid;
        pthread_create(&tid, NULL, client_func, &cli_data);
    }
}
</code>```

Terminal Session:

Server

```<code>$ gcc SO.c -lpthread
$ ./a.out
Hi to the server
Bye to the server
$
</code>```

Client

```<code>$ netstat -l | grep 8008
tcp        0      0 0.0.0.0:8008            0.0.0.0:*               LISTEN
$ nc 127.0.0.1 8008
Hi to the server
Bye to the server
^C
$
</code>```

The code is commented, and you can go through it. As @MartinJames said, you don't need to take a pain of terminating threads where it is absolutely unnecessary, you are better off relying on OS routines. Since we are handling the signals in an asynchronous way, only a few functions can be called in signal handler (async-signal-safe functions); _exit() is one among them.

Body:
Though I understood your question, what puzzles me is, where do you use such a server ?. In any case, I hope you will make a good use of this server.

#include <signal.h>
#include <sys/socket.h>
#include <pthread.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>

void sigfunc(int signo)
{
    _exit(0); // safe to call in signal handler since it is async-signal-safe func
}

struct client_data {
    int clifd;
    pthread_t ptid;
};

void* client_func(void* _cli_data)
{
    struct client_data* cli_data = (struct client_data*) _cli_data;

    char buf[100];

    for( ; ; ) {
        int rd_status = read(cli_data->clifd, buf, sizeof(buf) - 1);

        if (rd_status <= 0)
            break;

        buf[rd_status] = '\0';
        printf("%s", buf);
        fflush(stdout);
    }

    close(cli_data->clifd);

    pthread_kill(cli_data->ptid, SIGRTMIN);
    return NULL;
}

int main()
{
    /* Setup a Listening server */

    struct sockaddr_in servaddr;
    memset(&servaddr, 0, sizeof(struct sockaddr_in));

    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    servaddr.sin_port = htons(8008);

    int sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

    if (bind(sockfd, (struct sockaddr*) &servaddr, sizeof(struct sockaddr_in)) != 0)
        exit(1);

    listen(sockfd, 5);

    /* Setup signal handler, use SIGRTMIN as sync signal */

    struct sigaction act;
    sigemptyset(&act.sa_mask);
    act.sa_flags = 0;

#ifdef SA_INTERRUPT
    act.sa_flags |= SA_INTERRUPT;
#endif

    act.sa_handler = sigfunc;

    sigaction(SIGRTMIN, &act, NULL);

    /* Loop and listen for connections */

    int addr_len;

    for ( ; ; ) {
        struct client_data cli_data;

        cli_data.ptid = pthread_self();
        addr_len = sizeof(struct sockaddr_in);
        cli_data.clifd = accept(sockfd, (struct sockaddr*) &servaddr, &addr_len);

        if (cli_data.clifd < 0)
            continue;

        pthread_t tid;
        pthread_create(&tid, NULL, client_func, &cli_data);
    }
}

Terminal Session:

Server

$ gcc SO.c -lpthread
$ ./a.out
Hi to the server
Bye to the server
$

Client

$ netstat -l | grep 8008
tcp        0      0 0.0.0.0:8008            0.0.0.0:*               LISTEN
$ nc 127.0.0.1 8008
Hi to the server
Bye to the server
^C
$

The code is commented, and you can go through it. As @MartinJames said, you don't need to take a pain of terminating threads where it is absolutely unnecessary, you are better off relying on OS routines. Since we are handling the signals in an asynchronous way, only a few functions can be called in signal handler (async-signal-safe functions); _exit() is one among them.


问:
Why character in StringBuild does not change?
The character must be entered from the console to change to lowercase letters on this line. But it displays the same word and the symbol does not change.</p>

```<code>public class Task {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder(requestString());
        char symbol = requestSymbol().charAt(0);
        int count = 0;

        for (int i = 0; i < sb.length(); i++) {
            if (sb.charAt(i) == symbol) {
                sb.setCharAt(i, sb.charAt(Character.toUpperCase(i)));
                count++;
            }
        }
        System.out.println("Number of entries: " + count);
        System.out.println("Converted string: " + sb);
    }

    static String requestString() {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter string:");
        return scanner.nextLine();
    }

    static String requestSymbol() {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter the symbol:");
        return scanner.next();
    }
}
</code>```

答:
It seems to be a problem with the line:

sb.setCharAt(i, sb.charAt(Character.toUpperCase(i)));
```

<p>It should be:</p>

<pre class="lang-java prettyprint-override"><code>sb.setCharAt(i, Character.toUpperCase(symbol));
</code>```

Body:
The character must be entered from the console to change to lowercase letters on this line. But it displays the same word and the symbol does not change.

public class Task {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder(requestString());
        char symbol = requestSymbol().charAt(0);
        int count = 0;

        for (int i = 0; i < sb.length(); i++) {
            if (sb.charAt(i) == symbol) {
                sb.setCharAt(i, sb.charAt(Character.toUpperCase(i)));
                count++;
            }
        }
        System.out.println("Number of entries: " + count);
        System.out.println("Converted string: " + sb);
    }

    static String requestString() {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter string:");
        return scanner.nextLine();
    }

    static String requestSymbol() {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter the symbol:");
        return scanner.next();
    }
}

Body:
It seems to be a problem with the line:

sb.setCharAt(i, sb.charAt(Character.toUpperCase(i)));

It should be:

sb.setCharAt(i, Character.toUpperCase(symbol));


问:
Why is IronPython faster than the Official Python Interpreter
According to this:

http://www.codeplex.com/IronPython/Wiki/View.aspx?title=IP20VsCPy25Perf&referringTitle=IronPython%20Performance

IronPython (Python for .Net) is faster than regular Python (cPython) on the same machine.  Why is this?  I would think compiled C code would always be faster than the equivalent CLI bytecode.

答: I'm not sure exactly how you're drawing the conclusion that IronPython is faster than CPython.  The link that you post seems to indicate that they're good at different things (like exceptions as has been pointed out).</p>

OwnerDisplayName: DrFredEdison

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Jason Baker


问:
Potentially long loop and declaring variables inside
I've recently written a dynamic program that calculates the similarity (modified edit distance) between two sequences of DNA strands (can be lengthy).

My code is like (not actual code since its an assignment):

```<code>while(!file.eof){
   string line;
   int sizeY, sizeX;

   //get first strand
   getline(db, line)

   //second strand
   getline(db, line)

   double ** ary = new double[sizeY];
   //loop to initialize array

   for(i to sizeY)
   {
      for(i to sizex)
      {
            pair<string,string> p,d;
            p.first = "A";
            p.second = "T";
            d.first = "G";
            d.second = "C";
            //do some comparisons
      }
   }
}
</code>```

The code above will take approximately 40 minutes to complete on a file with ~2400 lines.
If I move the pair p,d and assignments outside the nested for-loop and run the exact same file, it will complete in about ~1 minute.

I've read in other threads that the performance is pretty much the same. I've also compiled it with -O2.

Why is the code above so much slower?

答:
Consider the various allocations/deallocations that have to happen on each and every iteration of the inner loop.

Allocate a pair object on the stack

Allocate four empty strings, each probably a 1 byte allocation on the heap

Four string assignments which may require 4 heap deallocations and new allocations

Destruction of the strings involving 4 heap deallocations

Destruction of the pair object

Ignoring the stack allocations (which should be relatively cheap) that is a total of 8 heap allocations and another 8 deallocations (or a best case of 4/4). If this is a debug build there may be additional overhead in checking each heap operation.

If your sizeX/sizeY constants are 2400 then you're doing a total of of 92 million heap operations. If you're lucky each of those operations will take around the same time since you're allocating the same sized object each loop. If you're unlucky then some heap operations may take significantly longer to accomplish due to heap fragmentation.

The obvious solution, as you've found, is to put the variable definition and assignment outside the loop. You only need to reassign the pair values if they are being overwritten within the loop at some point.

Body:
I've recently written a dynamic program that calculates the similarity (modified edit distance) between two sequences of DNA strands (can be lengthy).

My code is like (not actual code since its an assignment):

while(!file.eof){
   string line;
   int sizeY, sizeX;

   //get first strand
   getline(db, line)

   //second strand
   getline(db, line)

   double ** ary = new double[sizeY];
   //loop to initialize array

   for(i to sizeY)
   {
      for(i to sizex)
      {
            pair<string,string> p,d;
            p.first = "A";
            p.second = "T";
            d.first = "G";
            d.second = "C";
            //do some comparisons
      }
   }
}

The code above will take approximately 40 minutes to complete on a file with ~2400 lines.
If I move the pair p,d and assignments outside the nested for-loop and run the exact same file, it will complete in about ~1 minute.

I've read in other threads that the performance is pretty much the same. I've also compiled it with -O2.

Why is the code above so much slower?


问:
How do you save links with g++/C++?
I am writing some OpenGL code, and my links to libraries in /usr/lib is getting quite unwieldly:

```<code>g++ Application.cpp -lglfw -lGL -lGLEW
</code>```

I don't want to hunt around/can't remember the exact names of the libraries EVERY TIME i want to complile something, so in my project folder I have a file called linkingsNeeded.txt. That file contains that command and nothing else. Is there a way to save the list of linkings so I can just type

```<code>g++ Application.cpp
</code>```

And not have to deal with manually linking? Say, in the #include section of the CPP file?

答:
Learn to use some build automation tool such as GNU make or ninja.

You'll then edit your Makefile (with make); this could be inspirational and just build your program by typing make. Most source code editors (like GNU emacs) or IDEs can be easily configured to run make with a single keypress.

Of course you want to invoke GCC as g++ -Wall -Wextra -g since you want all warnings and debug info (for the GDB debugger).

Read also How to debug small programs and more about C++, perhaps even the n3337 quasi C++11 standard.

Title: How do you save links with g++/C++?

Body:
I am writing some OpenGL code, and my links to libraries in /usr/lib is getting quite unwieldly:

g++ Application.cpp -lglfw -lGL -lGLEW

I don't want to hunt around/can't remember the exact names of the libraries EVERY TIME i want to complile something, so in my project folder I have a file called linkingsNeeded.txt. That file contains that command and nothing else. Is there a way to save the list of linkings so I can just type

g++ Application.cpp

And not have to deal with manually linking? Say, in the #include section of the CPP file?


问:
Cumulative count on date data from datetime format
I have a table looks like:

```<code>ID entry_time
abc123 2020-05-29 10:29:18.000
def456 2020-05-30 13:12:43.000
...
</code>```

I want to do cumulative count by date, so I did:

select entry_time, count (*) OVER (ORDER BY entry_time) as TOTAL_NUM from my_table;

It is okay, but it will count based on datetime format. I would like to count only on date (i.e. by day, don't care about time).

How would I do that?

Many thanks,

答:
You can use convert or cast entry_time to Date</p>

```<code>select entry_time, count (*) OVER (ORDER BY Convert(date,entry_time)) as TOTAL_NUM from my_table;

OR

select entry_time, count (*) OVER (ORDER BY Cast(entry_timeas as date)) as TOTAL_NUM from my_table;
</code>```

Body:
I have a table looks like:

ID entry_time
abc123 2020-05-29 10:29:18.000
def456 2020-05-30 13:12:43.000
...

I want to do cumulative count by date, so I did:

select entry_time, count (*) OVER (ORDER BY entry_time) as TOTAL_NUM from my_table;

It is okay, but it will count based on datetime format. I would like to count only on date (i.e. by day, don't care about time).

How would I do that?

Many thanks,

Body:
You can use convert or cast entry_time to Date

select entry_time, count (*) OVER (ORDER BY Convert(date,entry_time)) as TOTAL_NUM from my_table;

OR

select entry_time, count (*) OVER (ORDER BY Cast(entry_timeas as date)) as TOTAL_NUM from my_table;


问:
Get last 4 digits of card from PaymentIntent object in Stripe PHP
Is it possible to get the last 4 digits of a card from the PaymentIntent object (not same as Charges API) using Stripe PHP SDK?</p>

答:
You can get from Charge object included in PaymentIntent.

```<code>PaymentIntent->charges->data
</code>```

https://stripe.com/docs/api/charges/object

Body:
You can get from Charge object included in PaymentIntent.

PaymentIntent->charges->data

https://stripe.com/docs/api/charges/object


问:
How to upload a large file on Google drive using Python?
I am trying to upload a large file on google drive but I am getting a warning that my app is not verified by google.I am using pydrive.Give me a solution using pydrive or using another way.</p>

答:
use the google cloud platform

have not used it much but pretty sure it works


问:
Python3 newbie needing advice
Hey everyone I am brand new to coding and back end computing in general. I have been at it about 3 weeks and thought I would take a crack at writing my first app. Most of my app is working just fine but I cannot figure out how to get the system to accept the new input and apply it to my functions after loop() runs. help please!</p>

```<code>from os import sys

def say_bye():
    print("GoodBye!")
    sys.exit()

def loop():
    print()
    print("Would you like to enter another value?")
    choice2 = input('y/n: ')
    if choice2 == 'y':
        print()
        amount = float(input("enter another price: "))
        rate = float(input("tax rate: "))
        print()
        return in_page(), tot_with_tax_exit(), print(tot_with_tax()), loop()
    else:
        return say_bye()

def tot_with_tax():
    tax = (amount * rate)
    total = ("Your total after tax is", tax + amount)
    return total

def tot_with_tax_exit():
    if amount == int(0):
        print('would you like to exit')
        choice = input('y/n?: ')
        if choice == 'y':
            print()
            return say_bye()
        else:
            return tot_with_tax()

def in_page():
    print()
    print("Welcome to the tax tool!")
    print()
    print("Please enter your total price, and tax rate.")

in_page()
amount = float(input("enter price: "))
tot_with_tax_exit()
rate = float(input("tax rate: "))
print(tot_with_tax())
loop()
</code>```

答:
You have to pass the values to the function to_with_tax()  here is the code with the changes that make it work. </p>

```<code>from os import sys

def say_bye():
    print("GoodBye!")
    sys.exit()

def loop():
    print()
    print("Would you like to enter another value?")
    choice2 = input('y/n: ')
    if choice2 == 'y':
        print()
        amount = float(input("enter another price: "))
        rate = float(input("tax rate: "))
        print()
        return in_page(), tot_with_tax_exit(), print(tot_with_tax(amount, rate)), loop()
    else:
        return say_bye()

def tot_with_tax(amount, rate):
    tax = (amount * rate)
    total = ("Your total after tax is", tax + amount)
    return total

def tot_with_tax_exit():
    if amount == int(0):
        print('would you like to exit')
        choice = input('y/n?: ')
        if choice == 'y':
            print()
            return say_bye()
        else:
            return tot_with_tax()

def in_page():
    print()
    print("Welcome to the tax tool!")
    print()
    print("Please enter your total price, and tax rate.")

in_page()
amount = float(input("enter price: "))
tot_with_tax_exit()
rate = float(input("tax rate: "))
print(tot_with_tax(amount, rate))
loop()
</code>```

Title: Python3 newbie needing advice

Body:
Hey everyone I am brand new to coding and back end computing in general. I have been at it about 3 weeks and thought I would take a crack at writing my first app. Most of my app is working just fine but I cannot figure out how to get the system to accept the new input and apply it to my functions after loop() runs. help please!

from os import sys

def say_bye():
    print("GoodBye!")
    sys.exit()

def loop():
    print()
    print("Would you like to enter another value?")
    choice2 = input('y/n: ')
    if choice2 == 'y':
        print()
        amount = float(input("enter another price: "))
        rate = float(input("tax rate: "))
        print()
        return in_page(), tot_with_tax_exit(), print(tot_with_tax()), loop()
    else:
        return say_bye()

def tot_with_tax():
    tax = (amount * rate)
    total = ("Your total after tax is", tax + amount)
    return total

def tot_with_tax_exit():
    if amount == int(0):
        print('would you like to exit')
        choice = input('y/n?: ')
        if choice == 'y':
            print()
            return say_bye()
        else:
            return tot_with_tax()

def in_page():
    print()
    print("Welcome to the tax tool!")
    print()
    print("Please enter your total price, and tax rate.")

in_page()
amount = float(input("enter price: "))
tot_with_tax_exit()
rate = float(input("tax rate: "))
print(tot_with_tax())
loop()

Body:
You have to pass the values to the function to_with_tax()  here is the code with the changes that make it work.

from os import sys

def say_bye():
    print("GoodBye!")
    sys.exit()

def loop():
    print()
    print("Would you like to enter another value?")
    choice2 = input('y/n: ')
    if choice2 == 'y':
        print()
        amount = float(input("enter another price: "))
        rate = float(input("tax rate: "))
        print()
        return in_page(), tot_with_tax_exit(), print(tot_with_tax(amount, rate)), loop()
    else:
        return say_bye()

def tot_with_tax(amount, rate):
    tax = (amount * rate)
    total = ("Your total after tax is", tax + amount)
    return total

def tot_with_tax_exit():
    if amount == int(0):
        print('would you like to exit')
        choice = input('y/n?: ')
        if choice == 'y':
            print()
            return say_bye()
        else:
            return tot_with_tax()

def in_page():
    print()
    print("Welcome to the tax tool!")
    print()
    print("Please enter your total price, and tax rate.")

in_page()
amount = float(input("enter price: "))
tot_with_tax_exit()
rate = float(input("tax rate: "))
print(tot_with_tax(amount, rate))
loop()


问:
MongoDB Mongoose How to delete an object from an array
```<code>var UserSchema = new mongoose.Schema({
   //Irrelevant code
   profile:
   {
    requests: [{ sender: String, id: String,  hasSelected: Boolean, value: Boolean}]
   }
});
</code>```

That object is to keep track of friend request, I want it to get completely deleted from the requests array once it has been accepted or declined. I have tried a whole bunch of stuff but nothing is deleting it. Currently have this code:

```<code>User.updateOne({ id: user.id },
              { "$pull": { "profile": { "requests": { "id": targetId } } }  },
              { "multi": true },
              function(err,status) {
                if(err){console.log("Could not delete the friend request");}
                else{
                  console.log("Sucessfully deleted friend request from: " + user.name);}
               }
              );
</code>```

It always says it was deleted on the log, but when I check on mongoDB the request is still there.

答:
try $elemMatch to remove the specific object.</p>

```<code> User.updateOne(
 { id: user.id },
 { $pull: { "profile.requests": { $elemMatch: { id: targetId } } } },
 { multi: true },
 function (err, status) {
 if (err) {
  console.log("Could not delete the friend request");
  } else {
  console.log("Sucessfully deleted friend request from: " + user.name);
 }
 }
 );
</code>```

Body:
var UserSchema = new mongoose.Schema({
   //Irrelevant code
   profile:
   {
    requests: [{ sender: String, id: String,  hasSelected: Boolean, value: Boolean}]
   }
});

That object is to keep track of friend request, I want it to get completely deleted from the requests array once it has been accepted or declined. I have tried a whole bunch of stuff but nothing is deleting it. Currently have this code:

User.updateOne({ id: user.id },
              { "$pull": { "profile": { "requests": { "id": targetId } } }  },
              { "multi": true },
              function(err,status) {
                if(err){console.log("Could not delete the friend request");}
                else{
                  console.log("Sucessfully deleted friend request from: " + user.name);}
               }
              );

It always says it was deleted on the log, but when I check on mongoDB the request is still there.

Body:
try $elemMatch to remove the specific object.

 User.updateOne(
 { id: user.id },
 { $pull: { "profile.requests": { $elemMatch: { id: targetId } } } },
 { multi: true },
 function (err, status) {
 if (err) {
  console.log("Could not delete the friend request");
  } else {
  console.log("Sucessfully deleted friend request from: " + user.name);
 }
 }
 );


答:
I'm guessing your problem was that after the initial tot_with_tax() gets calculated, it would continue to return the same value regardless of new inputs. At least that is what I noticed when I ran your code. Check out where I commented "HERE". I just modified tot_with_tax() to take two variables tot_with_tax(amount, rate). Now you're passing in the new amount and rate to the function each time you want a new calculation.

```<code>from os import sys

def say_bye():
    print("GoodBye!")
    sys.exit()

def loop():
    print()
    print("Would you like to enter another value?")
    choice2 = input('y/n: ')
    if choice2 == 'y':
        print()
        amount = float(input("enter another price: "))
        rate = float(input("tax rate: "))
        print()
        return in_page(), tot_with_tax_exit(), print(tot_with_tax(amount, rate)), loop() # <--- HERE
    else:
        return say_bye()

def tot_with_tax(amount, rate): # <---- HERE
    tax = (amount * rate)
    total = ("Your total after tax is", tax + amount)
    return total

def tot_with_tax_exit():
    if amount == int(0):
        print('would you like to exit')
        choice = input('y/n?: ')
        if choice == 'y':
            print()
            return say_bye()
        else:
            return tot_with_tax()

def in_page():
    print()
    print("Welcome to the tax tool!")
    print()
    print("Please enter your total price, and tax rate.")

in_page()
amount = float(input("enter price: "))
tot_with_tax_exit()
rate = float(input("tax rate: "))
print(tot_with_tax(amount, rate)) # <--- HERE
loop()
</code>```

Hope this helps.

Title: Python3 newbie needing advice

Body:
I'm guessing your problem was that after the initial tot_with_tax() gets calculated, it would continue to return the same value regardless of new inputs. At least that is what I noticed when I ran your code. Check out where I commented "HERE". I just modified tot_with_tax() to take two variables tot_with_tax(amount, rate). Now you're passing in the new amount and rate to the function each time you want a new calculation.

from os import sys

def say_bye():
    print("GoodBye!")
    sys.exit()

def loop():
    print()
    print("Would you like to enter another value?")
    choice2 = input('y/n: ')
    if choice2 == 'y':
        print()
        amount = float(input("enter another price: "))
        rate = float(input("tax rate: "))
        print()
        return in_page(), tot_with_tax_exit(), print(tot_with_tax(amount, rate)), loop() # <--- HERE
    else:
        return say_bye()

def tot_with_tax(amount, rate): # <---- HERE
    tax = (amount * rate)
    total = ("Your total after tax is", tax + amount)
    return total

def tot_with_tax_exit():
    if amount == int(0):
        print('would you like to exit')
        choice = input('y/n?: ')
        if choice == 'y':
            print()
            return say_bye()
        else:
            return tot_with_tax()

def in_page():
    print()
    print("Welcome to the tax tool!")
    print()
    print("Please enter your total price, and tax rate.")

in_page()
amount = float(input("enter price: "))
tot_with_tax_exit()
rate = float(input("tax rate: "))
print(tot_with_tax(amount, rate)) # <--- HERE
loop()

Hope this helps.


问:
Get target branch ref in Github Actions for PR that is [not] from a fork
I'm trying to test a PR handling action on Github.

For that I'm creating a PR in my own repo and trying to use ${{ github.base_ref }}, but it is empty.
This help page says that GITHUB_BASE_REF is only available for PRs from forks.

Is there a way to get the target branch for a PR event, regardless of whether it is from a forked PR or not? Or a way to address the latter case specifically.

P.S. What I'm really trying to do is to get a list of changed files in the PR. What I have works for pushes but not for PRs:

```<code>git diff-tree --no-commit-id --name-only -r ${{ github.event.before }} ${{ github.sha }}
</code>```

答:
This should work regardless of whether it's raised from a fork or not.

```<code>${{ github.event.pull_request.base.ref }}
</code>```

By the way, you can add a step in your workflow to dump the github context object to see all available properties.

```<code>      - name: Dump GitHub context
        env:
          GITHUB_CONTEXT: ${{ toJson(github) }}
        run: echo "$GITHUB_CONTEXT"
</code>```

Body:
I'm trying to test a PR handling action on Github.

For that I'm creating a PR in my own repo and trying to use ${{ github.base_ref }}, but it is empty.
This help page says that GITHUB_BASE_REF is only available for PRs from forks.

Is there a way to get the target branch for a PR event, regardless of whether it is from a forked PR or not? Or a way to address the latter case specifically.

P.S. What I'm really trying to do is to get a list of changed files in the PR. What I have works for pushes but not for PRs:

git diff-tree --no-commit-id --name-only -r ${{ github.event.before }} ${{ github.sha }}

Body:
This should work regardless of whether it's raised from a fork or not.

${{ github.event.pull_request.base.ref }}

By the way, you can add a step in your workflow to dump the github context object to see all available properties.

      - name: Dump GitHub context
        env:
          GITHUB_CONTEXT: ${{ toJson(github) }}
        run: echo "$GITHUB_CONTEXT"


问:
String to Date Conversion in Python
In the following piece of code:

```<code>df['Year']=pd.DatetimeIndex(df['Date']).year
df['Month']=pd.DatetimeIndex(df['Date']).month
df['Day']=pd.DatetimeIndex(df['Date']).day
df['MM_DD_str']=df['Month'].astype(str).str.zfill(2)+'-'+df['Day'].astype(str).str.zfill(2)
</code>```

Since I want only MM-DD i did this way and it is a string now. But later on the program I want them in the date format. Especially I need month in order to plot a graph. Can i extract a date by extracting month from it.

Edited:

I want to plot a graph in which the Xtick should have the months like Jan, Feb, Mar upto Dec. I have to extract month from the dataframe df['MM_DD_str'] and make them as tick labels for the graph.

This is the final code i have written for plotting graph:

```<code>md_str = df['MM_DD_str']
get_month =md_str.apply(lambda d: pd.to_datetime(d, format='%m-%d').month)
#print(get_month)
plt.xticks(get_month,('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'))
plt.show()enter code here
</code>```

I am not getting neither output nor error

答:
If I understand correctly, you currently have a date string, like "06-23" for example, and you later want to extract the month from it as a datetime object:

```<code>md_col = df['MM_DD_str']
get_month = lambda d: pd.to_datetime(d, format='%m-%d').month
md_col.apply(get_month)
</code>```

get_month is a lambda function that takes a string, converts it to a datetime object, and then extracts the month.

.apply() takes a dataframe column and applies a function to all the rows in the column

Note that if your column contains NaNs or strings that cannot be converted to dates, you could include the errors argument in the .to_datetime function:

```<code>get_month = lambda d: pd.to_datetime(d, errors='ignore', format='%m-%d').month
</code>```

Title: String to Date Conversion in Python

Body:
In the following piece of code:

df['Year']=pd.DatetimeIndex(df['Date']).year
df['Month']=pd.DatetimeIndex(df['Date']).month
df['Day']=pd.DatetimeIndex(df['Date']).day
df['MM_DD_str']=df['Month'].astype(str).str.zfill(2)+'-'+df['Day'].astype(str).str.zfill(2)

Since I want only MM-DD i did this way and it is a string now. But later on the program I want them in the date format. Especially I need month in order to plot a graph. Can i extract a date by extracting month from it.

Edited:

I want to plot a graph in which the Xtick should have the months like Jan, Feb, Mar upto Dec. I have to extract month from the dataframe df['MM_DD_str'] and make them as tick labels for the graph.

This is the final code i have written for plotting graph:

md_str = df['MM_DD_str']
get_month =md_str.apply(lambda d: pd.to_datetime(d, format='%m-%d').month)
#print(get_month)
plt.xticks(get_month,('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'))
plt.show()enter code here

I am not getting neither output nor error

Body:
If I understand correctly, you currently have a date string, like "06-23" for example, and you later want to extract the month from it as a datetime object:

md_col = df['MM_DD_str']
get_month = lambda d: pd.to_datetime(d, format='%m-%d').month
md_col.apply(get_month)

get_month is a lambda function that takes a string, converts it to a datetime object, and then extracts the month.

.apply() takes a dataframe column and applies a function to all the rows in the column

Note that if your column contains NaNs or strings that cannot be converted to dates, you could include the errors argument in the .to_datetime function:

get_month = lambda d: pd.to_datetime(d, errors='ignore', format='%m-%d').month


问:
How to get array of dates between two dates in laravel?
I want to get dates between two dates in an array. The scenario is the following: I want to get daily sales cash collection and there is one filter of $fromdate and $todate. So even if I don't get any sales for an specific date I have to show that in the table.

答:
You can use CarbonPeriod for this.

I found something helpful at https://stackoverflow.com/a/50854594/13642447.


问:
set image wallpaper to fit screen "
I want to set the image to fit all screen when the user makes it as background for his device, I tried many codes but it does not work.
Here is my code</p>

```<code>item_home_image = findViewById(R.id.item_home_image);
item_home_image.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        if (checkPermission()) {
            final Intent intent = getIntent();
            String url = intent.getStringExtra("imageUrl");
            Picasso.with(PicassoDisplayImageAdapter.this).load(url).into(new Target() {
                @RequiresApi(api = Build.VERSION_CODES.N)
                @Override
                public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
                    WallpaperManager wallpaperManager = WallpaperManager.getInstance(PicassoDisplayImageAdapter.this);
                    try {
                        wallpaperManager.setBitmap(bitmap);
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
                    Toasty.normal(PicassoDisplayImageAdapter.this, "تم تغيير الخلفية بنجاح", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onBitmapFailed(final Drawable errorDrawable) {
                    Toasty.error(PicassoDisplayImageAdapter.this, "فشل تحميل الصورة", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onPrepareLoad(final Drawable placeHolderDrawable) {
                    Toasty.normal(PicassoDisplayImageAdapter.this, "جاري التحميل", Toast.LENGTH_SHORT).show();
                }
            });
        }
    }
});
</code>```

答:
Try this:</p>

```<code>DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int height = metrics.heightPixels;
int width = metrics.widthPixels;
Bitmap newBitmap = Bitmap.createScaledBitmap(bitmap, width, height, true);

try {
  wallpaperManager.setBitmap(newBitmap);
  } catch (IOException e) {
  e.printStackTrace();
}
</code>```

Title: set image wallpaper to fit screen "

Body:
I want to set the image to fit all screen when the user makes it as background for his device, I tried many codes but it does not work.
Here is my code

item_home_image = findViewById(R.id.item_home_image);
item_home_image.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        if (checkPermission()) {
            final Intent intent = getIntent();
            String url = intent.getStringExtra("imageUrl");
            Picasso.with(PicassoDisplayImageAdapter.this).load(url).into(new Target() {
                @RequiresApi(api = Build.VERSION_CODES.N)
                @Override
                public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
                    WallpaperManager wallpaperManager = WallpaperManager.getInstance(PicassoDisplayImageAdapter.this);
                    try {
                        wallpaperManager.setBitmap(bitmap);
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
                    Toasty.normal(PicassoDisplayImageAdapter.this, "تم تغيير الخلفية بنجاح", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onBitmapFailed(final Drawable errorDrawable) {
                    Toasty.error(PicassoDisplayImageAdapter.this, "فشل تحميل الصورة", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onPrepareLoad(final Drawable placeHolderDrawable) {
                    Toasty.normal(PicassoDisplayImageAdapter.this, "جاري التحميل", Toast.LENGTH_SHORT).show();
                }
            });
        }
    }
});

Body:
Try this:

DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int height = metrics.heightPixels;
int width = metrics.widthPixels;
Bitmap newBitmap = Bitmap.createScaledBitmap(bitmap, width, height, true);

try {
  wallpaperManager.setBitmap(newBitmap);
  } catch (IOException e) {
  e.printStackTrace();
}


问:
While loop based on component state value
I am working on a calculator app with React. I want to set the innerText of the AC button C while there is a value in the component's state. For example,

```<code>while (this.state.number) {
    document.getElementById("AC").innerText = "C";
}
</code>```

I know this is invalid JSX. So I want to know what is another way to achieve that?

Thank you!

答:
If you are rendering AC Button as react element you can do something like this.

```<code>...

<button>
{
 this.state.number ? "C" : "AC"
}
</button>
...

</code>```

Body:
I am working on a calculator app with React. I want to set the innerText of the AC button C while there is a value in the component's state. For example,

while (this.state.number) {
    document.getElementById("AC").innerText = "C";
}

I know this is invalid JSX. So I want to know what is another way to achieve that?

Thank you!

Body:
If you are rendering AC Button as react element you can do something like this.

...

<button>
{
 this.state.number ? "C" : "AC"
}
</button>
...


问:
Anyone know how to add extra comma and string to array?
i have a problem when i want to assign output into array string i already use str repace, etc but still not working..

i have output like this (in time)

$grapDate output = 09:00:0001:00:0012:00:0011:00:0010:00:0001:00:0000:00:0023:00:0022:00:00

```<code>date('H:i', strtotime($graph['Date'])
</code>```

and the output become = 09:0001:0012:0011:0010:0001:0000:0023:0022:00

but i want to assign that become e.g $date = ['09:00','01:00', '12:00', etc]

because i want to use graph chart like this in my body

```<code>script type="text/javascript">
    var ctx = document.getElementById('myChart2').getContext('2d');
    var myChart2 = new Chart(ctx, {
        type: 'line',
        data: {
            labels: ['$label'], //Jamnya
            datasets: [{
                backgroundColor: 'rgba(232,72,163,0.2)',
                borderColor: '#e848a3',
                label: '29 May 2020',
                data: [807,657,600,578,565,576,611,855,625,573,571,584,607,647,771,943,920,647,622,608,722,832,902,1062],
                fill: true,
                pointRadius: 5,
                pointHoverRadius: 10,
                showLine: true
            }]
        }, options: {
            responsive: true,
            maintainAspectRatio: false,
            title: {
                display: true,
                text: 'Total Online Yesterday',
                position: 'top',
                fontSize: 15,
                fontStyle: 'bold'
            },
            legend: {
                display: false
            },
            elements: {
                point: {
                    pointStyle: 'circle'
                }
            },
            scales: {
                xAxes: [{
                    display: true,
                    scaleLabel: {
                        display: true,
                        labelString: 'TIME'
                    },
                    ticks: {
                        major: {
                            fontStyle: 'bold',
                            fontColor: '#FF0000'
                        }
                    }
                }],
                yAxes: [{
                    display: true,
                    scaleLabel: {
                        display: true,
                        labelString: 'TOTAL ONLINE'
                    }
                }]
            },
            tooltips:{
                callbacks: {
                    title: function(tooltipItem, data) {
                      return '29 May 2020 '+data['labels'][tooltipItem[0]['index']];
                    },
                    label: function(tooltipItem, data) {
                      return 'TOTAL : '+data['datasets'][0]['data'][tooltipItem['index']]+'';
                    },
                },
                titleFontSize: 15,
                bodyFontSize: 15,
                displayColors: false
            }
        }
    });
</script>
</code>```

i still thinking how to assign parameter labels in class Chart become ['value', 'value', 'value']

Body:
i have a problem when i want to assign output into array string i already use str repace, etc but still not working..

i have output like this (in time)

$grapDate output = 09:00:0001:00:0012:00:0011:00:0010:00:0001:00:0000:00:0023:00:0022:00:00

date('H:i', strtotime($graph['Date'])

and the output become = 09:0001:0012:0011:0010:0001:0000:0023:0022:00

but i want to assign that become e.g $date = ['09:00','01:00', '12:00', etc]

because i want to use graph chart like this in my body

script type="text/javascript">
    var ctx = document.getElementById('myChart2').getContext('2d');
    var myChart2 = new Chart(ctx, {
        type: 'line',
        data: {
            labels: ['$label'], //Jamnya
            datasets: [{
                backgroundColor: 'rgba(232,72,163,0.2)',
                borderColor: '#e848a3',
                label: '29 May 2020',
                data: [807,657,600,578,565,576,611,855,625,573,571,584,607,647,771,943,920,647,622,608,722,832,902,1062],
                fill: true,
                pointRadius: 5,
                pointHoverRadius: 10,
                showLine: true
            }]
        }, options: {
            responsive: true,
            maintainAspectRatio: false,
            title: {
                display: true,
                text: 'Total Online Yesterday',
                position: 'top',
                fontSize: 15,
                fontStyle: 'bold'
            },
            legend: {
                display: false
            },
            elements: {
                point: {
                    pointStyle: 'circle'
                }
            },
            scales: {
                xAxes: [{
                    display: true,
                    scaleLabel: {
                        display: true,
                        labelString: 'TIME'
                    },
                    ticks: {
                        major: {
                            fontStyle: 'bold',
                            fontColor: '#FF0000'
                        }
                    }
                }],
                yAxes: [{
                    display: true,
                    scaleLabel: {
                        display: true,
                        labelString: 'TOTAL ONLINE'
                    }
                }]
            },
            tooltips:{
                callbacks: {
                    title: function(tooltipItem, data) {
                      return '29 May 2020 '+data['labels'][tooltipItem[0]['index']];
                    },
                    label: function(tooltipItem, data) {
                      return 'TOTAL : '+data['datasets'][0]['data'][tooltipItem['index']]+'';
                    },
                },
                titleFontSize: 15,
                bodyFontSize: 15,
                displayColors: false
            }
        }
    });
</script>

i still thinking how to assign parameter labels in class Chart become ['value', 'value', 'value']

Body:
First make each separate & print in JSON format.

$str = "09:0001:0012:0011:0010:0001:0000:0023:0022:00";
$date = json_encode(str_split($str, 5));


问:
Using a limit on a left join in mysql
The following query selects all posts and each post's owner, all of the comments that belong to each post, and the owner of each comment.

I need to only retrieve 5 comments per post. I rewrote the query, but I get an error of "each derived table must have it's own alias".

```<code>SELECT posts.id AS postId, posts.body, users.id AS userId, users.displayname, comments.id AS commentId, comments.text, commenters.id, commenters.displayname
FROM posts
JOIN users ON posts.owneruserid = users.id
LEFT JOIN comments ON posts.id = comments.postid
    JOIN users AS commenters ON comments.userId = commenters.id
ORDER BY posts.createdAt
</code>```

New Query:

```<code>SELECT posts.id AS postId, posts.body, users.id AS userId, users.displayname
FROM posts
JOIN users ON posts.owneruserid = users.id
LEFT JOIN (
    SELECT comments.id AS commentId, comments.text AS commentText, commenters.id AS commenterId, commenters.displayname AS commenterDisplayName
    FROM comments
    JOIN users AS commenters ON comments.userid = commenters.id
    LIMIT 0,5
        ) AS comments ON comments.postid = posts.id
ORDER BY posts.createdAt
</code>```

UPDATE The query now works, but it does not produce the desired output. I want to output 10 posts, with 5 comments for each post. This limit clause will only apply for the comments of the first post encountered.

答:
You need to give your derived table an alias: </p>

```<code>SELECT posts.id AS postId, posts.body, users.id AS userId, users.displayname
FROM posts
JOIN users ON posts.owneruserid = users.id
LEFT JOIN (
        SELECT comments.id AS commentId, comments.text AS commentText, commenters.id AS commenterId, commenters.displayname AS commenterDisplayName
        FROM comments
        JOIN users AS commenters ON comments.userid = commenters.id
        LIMIT 0,5
    ) AS derived_table_alias
ORDER BY posts.createdAt
</code>```

Title: Using a limit on a left join in mysql

Body:
The following query selects all posts and each post's owner, all of the comments that belong to each post, and the owner of each comment.

I need to only retrieve 5 comments per post. I rewrote the query, but I get an error of "each derived table must have it's own alias".

SELECT posts.id AS postId, posts.body, users.id AS userId, users.displayname, comments.id AS commentId, comments.text, commenters.id, commenters.displayname
FROM posts
JOIN users ON posts.owneruserid = users.id
LEFT JOIN comments ON posts.id = comments.postid
    JOIN users AS commenters ON comments.userId = commenters.id
ORDER BY posts.createdAt

New Query:

SELECT posts.id AS postId, posts.body, users.id AS userId, users.displayname
FROM posts
JOIN users ON posts.owneruserid = users.id
LEFT JOIN (
    SELECT comments.id AS commentId, comments.text AS commentText, commenters.id AS commenterId, commenters.displayname AS commenterDisplayName
    FROM comments
    JOIN users AS commenters ON comments.userid = commenters.id
    LIMIT 0,5
        ) AS comments ON comments.postid = posts.id
ORDER BY posts.createdAt

UPDATE The query now works, but it does not produce the desired output. I want to output 10 posts, with 5 comments for each post. This limit clause will only apply for the comments of the first post encountered.

Body:
You need to give your derived table an alias:

SELECT posts.id AS postId, posts.body, users.id AS userId, users.displayname
FROM posts
JOIN users ON posts.owneruserid = users.id
LEFT JOIN (
        SELECT comments.id AS commentId, comments.text AS commentText, commenters.id AS commenterId, commenters.displayname AS commenterDisplayName
        FROM comments
        JOIN users AS commenters ON comments.userid = commenters.id
        LIMIT 0,5
    ) AS derived_table_alias
ORDER BY posts.createdAt


问:
Google Drive UI Integration, Submit Failed
I am doing an integration with Google Drive user interface. However when I submit the form for doing so I get this message (with no feedback on the error):

This is the form as it was when I send it:

I have tried sending it from an incognito tap, other browsers, other IPs, other accounts.....
Is there anithing I am not seeing?

答: I am having the same problem but it seems to be a permissions error cause when I open the console I get a couple of 500 and 403 errors. Try contacting support.</p>