问:
Navigation Bar Heading Text Positioning
I have a navigation bar that will expand when the mouse is over it. I wish to display heading text once it is expanded (currently shows icons), I have used display: none on the heading tag, which then toggles to display: inline-block when the :hover event is active on the navbar. However, upon expansion of the navbar the text renders in on two lines before positioning itself into one which I want. I want to get rid of this and have the text render in as one line only while the navbar expands. My code:

```<code><!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Navigation Bar</title>
    <link href="css/styles.css" rel="stylesheet" type="text/css" />
    <script
      src="https://kit.fontawesome.com/6cc49d804e.js"
      crossorigin="anonymous"
    ></script>
  </head>

  <body>
    <div id="sidenav">
      <div id="sidenav-brand">
        <div id="sidenav-heading">
          <h2>Expanded Test</h2>
        </div>
        <div id="sidenav-expand">
          <i id="expand-icon" class="fas fa-angle-double-right fa-2x"></i>
        </div>
      </div>

      <div id="sidenav-links">
        <ul id="links">
          <li>
            <i class="fas fa-fw fa-id-card fa-2x"></i>
          </li>
          <li>
            <i class="fas fa-fw fa-graduation-cap fa-2x"></i>
          </li>
          <li>
            <i class="fas fa-fw fa-briefcase fa-2x"></i>
          </li>
          <li>
            <i class="fas fa-fw fa-smile-beam fa-2x"></i>
          </li>
        </ul>
      </div>
    </div>
  </body>
</html>

</code>```

```<code>body {
}

/* Make the width full-size then use javascript to minimise so content fits */
#sidenav {
  height: 100%;
  width: 75px;
  position: fixed;
  z-index: 1;
  top: 0;
  left: 0;
  background-color: #1e1e2d;
  overflow-x: hidden;
  color: grey;
  transition: width 0.5s;
}

#sidenav-brand {
  padding: 25px 20px;
  background-color: #1a1a27;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
}

#sidenav-heading {
  display: none;
}

#sidenav-heading h2 {
  margin: 0;
  color: white;
}

#sidenav-expand {
  text-align: center;
  margin-left: 3px;
}

#expand-icon {
  transition: transform 0.5s;
}

#sidenav:hover {
  width: 280px;
}

#sidenav:hover #expand-icon {
  transform: rotate(180deg);
}

#sidenav:hover #sidenav-heading {
  display: inline-block;
}

#sidenav-links {
  margin: 15px 0;
}

#links {
  list-style-type: none;
  padding: 0;
  text-align: left;
}

#links li {
  padding: 18px;
  display: block;
}

#links li:hover {
  color: white;
  background-color: hotpink;
}

.fas {
  vertical-align: middle;
}

</code>```

Please check this fiddle for what I mean when the navbar expands:
https://jsfiddle.net/4pk25oLh/

P.S. The effect I want is the same as when you get rid of the space in the heading text (however, I will need the space). Any help would be greatly appreciated.

答:
Please update below CSS selectors in your style file or CSS:

             body {
                  }

            /* Make the width full-size then use javascript to minimise so content fits */
            #sidenav {
              height: 100%;
              width: 75px;
              position: fixed;
              z-index: 1;
              top: 0;
              left: 0;
              background-color: #1e1e2d;
              overflow-x: hidden;
              color: grey;
              transition: width 0.5s;
            }

            #sidenav-brand {
              padding: 25px 20px;
              background-color: #1a1a27;
              display: flex;
              flex-direction: row;
              justify-content: flex-end;
              align-items: center;
            }

            #sidenav-heading {
              display: inline-block;
              position: absolute;
              width: 240px;
              left: 20px;
              transition: opacity 0.3s;
              -webkit-transition: opacity 0.3s;
              opacity: 0;
            }

            #sidenav-heading h2 {
              margin: 0;
              color: white;
            }

            #sidenav-expand {
              text-align: center;
              margin-left: 3px;
            }

            #expand-icon {
              transition: transform 0.5s;
            }

            #sidenav:hover {
              width: 280px;
            }

            #sidenav:hover #expand-icon {
              transform: rotate(180deg);
            }

            #sidenav:hover #sidenav-heading {
              opacity: 1;
            }

            #sidenav-links {
              margin: 15px 0;
            }

            #links {
              list-style-type: none;
              padding: 0;
              text-align: left;
            }

            #links li {
              padding: 18px;
              display: block;
            }

            #links li:hover {
              color: white;
              background-color: hotpink;
            }

            .fas {
              vertical-align: middle;
            }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="css/styles.css" rel="stylesheet" type="text/css" />
    <script
      src="https://kit.fontawesome.com/6cc49d804e.js"
      crossorigin="anonymous"
    ></script>
<div id="sidenav">
      <div id="sidenav-brand">
        <div id="sidenav-heading">
          <h2>Expanded Test</h2>
        </div>
        <div id="sidenav-expand">
          <i id="expand-icon" class="fas fa-angle-double-right fa-2x"></i>
        </div>
      </div>

      <div id="sidenav-links">
        <ul id="links">
          <li>
            <i class="fas fa-fw fa-id-card fa-2x"></i>
          </li>
          <li>
            <i class="fas fa-fw fa-graduation-cap fa-2x"></i>
          </li>
          <li>
            <i class="fas fa-fw fa-briefcase fa-2x"></i>
          </li>
          <li>
            <i class="fas fa-fw fa-smile-beam fa-2x"></i>
          </li>
        </ul>
      </div>
    </div></code>```

Title: Navigation Bar Heading Text Positioning

Body:
I have a navigation bar that will expand when the mouse is over it. I wish to display heading text once it is expanded (currently shows icons), I have used display: none on the heading tag, which then toggles to display: inline-block when the :hover event is active on the navbar. However, upon expansion of the navbar the text renders in on two lines before positioning itself into one which I want. I want to get rid of this and have the text render in as one line only while the navbar expands. My code:

<!DOCTYPE html>

    <meta charset="UTF-8" />
    <title>Navigation Bar</title>
    <link href="css/styles.css" rel="stylesheet" type="text/css" />

Expanded Test

body {
}

/* Make the width full-size then use javascript to minimise so content fits */
#sidenav {
  height: 100%;
  width: 75px;
  position: fixed;
  z-index: 1;
  top: 0;
  left: 0;
  background-color: #1e1e2d;
  overflow-x: hidden;
  color: grey;
  transition: width 0.5s;
}

#sidenav-brand {
  padding: 25px 20px;
  background-color: #1a1a27;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
}

#sidenav-heading {
  display: none;
}

#sidenav-heading h2 {
  margin: 0;
  color: white;
}

#sidenav-expand {
  text-align: center;
  margin-left: 3px;
}

#expand-icon {
  transition: transform 0.5s;
}

#sidenav:hover {
  width: 280px;
}

#sidenav:hover #expand-icon {
  transform: rotate(180deg);
}

#sidenav:hover #sidenav-heading {
  display: inline-block;
}

#sidenav-links {
  margin: 15px 0;
}

#links {
  list-style-type: none;
  padding: 0;
  text-align: left;
}

#links li {
  padding: 18px;
  display: block;
}

#links li:hover {
  color: white;
  background-color: hotpink;
}

.fas {
  vertical-align: middle;
}

Please check this fiddle for what I mean when the navbar expands:
https://jsfiddle.net/4pk25oLh/

P.S. The effect I want is the same as when you get rid of the space in the heading text (however, I will need the space). Any help would be greatly appreciated.

Body:
Please update below CSS selectors in your style file or CSS:

             body {
                  }

            /* Make the width full-size then use javascript to minimise so content fits */
            #sidenav {
              height: 100%;
              width: 75px;
              position: fixed;
              z-index: 1;
              top: 0;
              left: 0;
              background-color: #1e1e2d;
              overflow-x: hidden;
              color: grey;
              transition: width 0.5s;
            }

            #sidenav-brand {
              padding: 25px 20px;
              background-color: #1a1a27;
              display: flex;
              flex-direction: row;
              justify-content: flex-end;
              align-items: center;
            }

            #sidenav-heading {
              display: inline-block;
              position: absolute;
              width: 240px;
              left: 20px;
              transition: opacity 0.3s;
              -webkit-transition: opacity 0.3s;
              opacity: 0;
            }

            #sidenav-heading h2 {
              margin: 0;
              color: white;
            }

            #sidenav-expand {
              text-align: center;
              margin-left: 3px;
            }

            #expand-icon {
              transition: transform 0.5s;
            }

            #sidenav:hover {
              width: 280px;
            }

            #sidenav:hover #expand-icon {
              transform: rotate(180deg);
            }

            #sidenav:hover #sidenav-heading {
              opacity: 1;
            }

            #sidenav-links {
              margin: 15px 0;
            }

            #links {
              list-style-type: none;
              padding: 0;
              text-align: left;
            }

            #links li {
              padding: 18px;
              display: block;
            }

            #links li:hover {
              color: white;
              background-color: hotpink;
            }

            .fas {
              vertical-align: middle;
            }

<link href="css/styles.css" rel="stylesheet" type="text/css" />
    <script
      src="https://kit.fontawesome.com/6cc49d804e.js"
      crossorigin="anonymous"
    ></script>
<div id="sidenav">
      <div id="sidenav-brand">
        <div id="sidenav-heading">
          <h2>Expanded Test</h2>
        </div>
        <div id="sidenav-expand">
          <i id="expand-icon" class="fas fa-angle-double-right fa-2x"></i>
        </div>
      </div>

      <div id="sidenav-links">
        <ul id="links">
          <li>
            <i class="fas fa-fw fa-id-card fa-2x"></i>
          </li>
          <li>
            <i class="fas fa-fw fa-graduation-cap fa-2x"></i>
          </li>
          <li>
            <i class="fas fa-fw fa-briefcase fa-2x"></i>
          </li>
          <li>
            <i class="fas fa-fw fa-smile-beam fa-2x"></i>
          </li>
        </ul>
      </div>
    </div>


来源: stackexchange

问:
Excel: Replace text in next row on base of selection criteria on previous
I have big excel sheet data like below

```<code>10.11.0.5,PCS
10.11.0.6,Reserve
10.11.0.7,Reserve
10.11.0.8,Reserve
10.11.0.9,PCS
10.11.0.10,Reserve
10.11.0.11,Reserve
10.11.0.12,Reserve
</code>```

Now i want to replace Reserve to PLC which is next to PCS

Expected output should be like

```<code>10.11.0.5,PCS
10.11.0.6,PLC
10.11.0.7,Reserve
10.11.0.8,Reserve
10.11.0.9,PCS
10.11.0.10,PLC
10.11.0.11,Reserve
10.11.0.12,Reserve
</code>```

答: If you can, Add formula to next cell

ContentLicense: CC BY-SA 4.0

Body:
I have big excel sheet data like below

10.11.0.5,PCS
10.11.0.6,Reserve
10.11.0.7,Reserve
10.11.0.8,Reserve
10.11.0.9,PCS
10.11.0.10,Reserve
10.11.0.11,Reserve
10.11.0.12,Reserve

Now i want to replace Reserve to PLC which is next to PCS

Expected output should be like

10.11.0.5,PCS
10.11.0.6,PLC
10.11.0.7,Reserve
10.11.0.8,Reserve
10.11.0.9,PCS
10.11.0.10,PLC
10.11.0.11,Reserve
10.11.0.12,Reserve

Body: If you can, Add formula to next cell


问:
R: unite every distinct value in one column into another
I have a data that looks something like this (but actually much larger, around 100000 lines).

```<code>  ID CODE
1  A   F1
2  A   F2
3  B   F3
4  B   F1
5  C   F1
6  C   F1
7  C   F2
</code>```

I need to write all different CODEs for each ID into one column. I have gotten half the way by doing:

```<code>Data %>% arrange(ID) %>% group_by(ID) %>% distinct(CODE)
  CODE  ID
  <fct> <fct>
1 F1    A
2 F2    A
3 F3    B
4 F1    B
5 F1    C
6 F2    C
</code>```

But what I need should look something like this (where column all_CODEs holds all codes for each ID written into string):

```<code>  ID all_CODEs
1  A     F1 F2
2  B     F3 F1
3  C     F1 F2
</code>```

Can anyone help?

答:
After the distinct step, we can summarise by pasteing the 'CODE' into a single string

```<code>library(dplyr)
library(stringr)
Data %>%
  arrange(ID) %>%
  distinct() %>%
  group_by(ID) %>%
  summarise(all_CODEs = str_c(CODE, collapse=' '))
# A tibble: 3 x 2
#  ID    all_CODEs
#  <chr> <chr>
#1 A     F1 F2
#2 B     F3 F1
#3 C     F1 F2
</code>```

NOTE: distinct on a single column with return only that column with the distinct rows because by default .keep_all = FALSE.  Here, it seems that distinct should be applied on the two columns

data

```<code>Data <- structure(list(ID = c("A", "A", "B", "B", "C", "C", "C"), CODE = c("F1",
"F2", "F3", "F1", "F1", "F1", "F2")), class = "data.frame", row.names = c("1",
"2", "3", "4", "5", "6", "7"))
</code>```

Body:
I have a data that looks something like this (but actually much larger, around 100000 lines).

  ID CODE
1  A   F1
2  A   F2
3  B   F3
4  B   F1
5  C   F1
6  C   F1
7  C   F2

I need to write all different CODEs for each ID into one column. I have gotten half the way by doing:

Data %>% arrange(ID) %>% group_by(ID) %>% distinct(CODE)
  CODE  ID
  <fct> <fct>
1 F1    A
2 F2    A
3 F3    B
4 F1    B
5 F1    C
6 F2    C

But what I need should look something like this (where column all_CODEs holds all codes for each ID written into string):

  ID all_CODEs
1  A     F1 F2
2  B     F3 F1
3  C     F1 F2

Can anyone help?

Body:
After the distinct step, we can summarise by pasteing the 'CODE' into a single string

library(dplyr)
library(stringr)
Data %>%
  arrange(ID) %>%
  distinct() %>%
  group_by(ID) %>%
  summarise(all_CODEs = str_c(CODE, collapse=' '))
# A tibble: 3 x 2
#  ID    all_CODEs
#  <chr> <chr>
#1 A     F1 F2
#2 B     F3 F1
#3 C     F1 F2

NOTE: distinct on a single column with return only that column with the distinct rows because by default .keep_all = FALSE.  Here, it seems that distinct should be applied on the two columns

data

Data <- structure(list(ID = c("A", "A", "B", "B", "C", "C", "C"), CODE = c("F1",
"F2", "F3", "F1", "F1", "F1", "F2")), class = "data.frame", row.names = c("1",
"2", "3", "4", "5", "6", "7"))


问:
PHP version on phpinfo() older than the one on terminal
So I have a versioning problem with my php on my macOSX. The version showed on my terminal is correct and shows PHP 7.4.2. However, when I open up phpinfo() on my project I get PHP 7.1.23

All the posts I keep finding on this subject is how the terminal is behind what is shown on phpinfo(), while I get the opposite. I installed php using homebrew since I needed to work with 7.4. However, I feel like php 7.1 was there prior to me installing 7.4, maybe it's the built-n php version on my mac?

Things I tried that did not work:

Putting "export PATH="/usr/local/opt/php@7.4/sbin:$PATH"" in my .bash_profile

Removing and reinstalling php using homebrew

Restarting Apache server thousands of times using "apachectl restart"

Removed XCode and it's developer folder

Cried in a corner in a fetal position

Anyone has other suggestions?

答: The answer posted by @vadim is technically right, but since a2enmod doesn't work on my mac, I needed to manually change it in the httpd.conf file. The php7_module was pointing to the 7.1 libphp7.so file. What I did was simply found the libphp7.so file installed by homebrew and change the location in the httpd.conf to point to that one.</p>


问:
DStream filtering and offset management in Spark Streaming Kafka
I am currently writing a Spark streaming application that reads data from Kafka and tries to decode it before applying some transformations.

The current code structure looks like this:

```<code>val stream = KafkaUtils.createDirectStream[String, String](...)
 .map(record => decode(record.value())
 .filter(...)
 .foreachRDD { rdd =>
   val offsetRanges = rdd.asInstanceOf[HasOffsetRanges].offsetRanges
   ...
   stream.asInstanceOf[CanCommitOffsets].commitAsync(offsetRanges)
 }
</code>```

The decoding and filtering of failures happens on the DStream, and the offset management is done inside the foreachRDD, which means that I will only commit successful records.

To commit the failed records, I could move everything inside the foreachRDD loop:

```<code>val stream = KafkaUtils.createDirectStream[String, String](...)
 .foreachRDD { rdd =>
   val offsetRanges = rdd.asInstanceOf[HasOffsetRanges].offsetRanges
   ...
   // Decoding and filtering here
   ...
   stream.asInstanceOf[CanCommitOffsets].commitAsync(offsetRanges)
 }
</code>```

However, I am wondering whether there is another way to commit the failed records. Maybe it would be acceptable to not commit the failed records?

答:
I am assuming you are using the spark-streaming-kafka library.

Reading the documentation of offset Ranges it stores the range of offsets from the topic partitions. It does not filter out or mark individual offsets within that range based on the clients filtering ".filter(…)" actions. So if you commit that offsetRanges it will commit the highest offset number per partition, regardless of your filter actions.

That makes sense, as your Consumer is telling the Kafka Broker, or more precisely, the Group Coordinator that it consumed these messages. The coordinator is not interested in what you are actually doing with the data, it just wants to know if that particular Consumer Group was reading a message/offset or not.

Coming back to your questions...

I am wondering whether there is another way to commit the failed records.

Although it doesn't look like you need it, but yes, there is another way of committing "failed" records. You can enable auto commit. Together with the Consumer configuration auto.commit.interval.ms, you can periodically commit the offsets your consumer polled from the topic.

Maybe it would be acceptable to not commit the failed records?

I don't have the knowledge of your particular use case, but it is acceptable to not commit the failed records. As mentioned above, the Group Coordinater is interested in the highest offset per partition that your consumer has consumed. If you consume a topic with 10 messages, you start reading from beginning and you only commit the 9th offset (offset counting starts at 0), then the next time you start your consumer it will ignore the first ten messages.

You could check out the Kafka internal topic __consumer_offsets to see what is stored for each Consumer Group: Topic, Partition, Offset (… among others).

ContentLicense: CC BY-SA 3.0

Body:
I am currently writing a Spark streaming application that reads data from Kafka and tries to decode it before applying some transformations.

The current code structure looks like this:

val stream = KafkaUtils.createDirectStream[String, String](...)
 .map(record => decode(record.value())
 .filter(...)
 .foreachRDD { rdd =>
   val offsetRanges = rdd.asInstanceOf[HasOffsetRanges].offsetRanges
   ...
   stream.asInstanceOf[CanCommitOffsets].commitAsync(offsetRanges)
 }

The decoding and filtering of failures happens on the DStream, and the offset management is done inside the foreachRDD, which means that I will only commit successful records.

To commit the failed records, I could move everything inside the foreachRDD loop:

val stream = KafkaUtils.createDirectStream[String, String](...)
 .foreachRDD { rdd =>
   val offsetRanges = rdd.asInstanceOf[HasOffsetRanges].offsetRanges
   ...
   // Decoding and filtering here
   ...
   stream.asInstanceOf[CanCommitOffsets].commitAsync(offsetRanges)
 }

However, I am wondering whether there is another way to commit the failed records. Maybe it would be acceptable to not commit the failed records?


问:
Where does microsoft graph look for photos?
I have an application that successfully gets the users photo using a Microsoft graph API call.

https://graph.microsoft.com/v1.0/users/<upn>/photos/48x48/$value

For some users, that API call will return a 'not found' error. However when looking up their profile in Azure AD, a photo is available there. Their photos are also available in other apps like Outlook, Skype, etc.

Where does Microsoft graph look for user profile photos?

答:
The photo is retrieved from Exchange Online profile photo store. This is used by the majority of services now across Office 365. This photo is updated by going to Delve, Teams and a few other places.

In some cases, depending on your configuration (on-premises hybrid scenarios) this gets a little more complicated. In those scenarios, you need to ensure that Azure AD on-premises is syncing photos that are uploaded to other stores.

There are some solutions out there, including one by Hyperfish as an example https://blog.hyperfish.com/importing-and-exporting-photos


问:
Trouble uploading an image and save it on the server
Below is my code for upload image.
Image is uploaded but the size of the uploaded image on server is 0 KB.

```<code>    NSData *imageData = [NSData dataWithContentsOfFile:filePath];

    NSString *str_url = [NSString stringWithFormat:@"http://someUrl.aspx?TaskId=%@",ID];

    NSURL *url=[NSURL URLWithString:str_url];

    NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
    [request setURL:url];
    [request setHTTPMethod:@"POST"];
    NSString *boundary = [NSString stringWithString:@"---------------------------14737809831466499882746641449"];
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@,",boundary];
    [request addValue:contentType forHTTPHeaderField: @"Content-Type"];

    NSMutableData *body = [NSMutableData data];
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithString:[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"UploadedFilePhysical\"; filename=\"%@\"\r\n",Phusicalstr1]] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[NSData dataWithData:imageData]];
    //[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
</code>```

Any idea what happened in the upload?

答:
```<code> NSMutableData *body = [NSMutableData data];
</code>```

What is this line does?

How are you initializing this?

Replace it with something like this.

```<code>NSMutableData *body = [[NSMutableData alloc] init];
</code>```

Body:
Below is my code for upload image.
Image is uploaded but the size of the uploaded image on server is 0 KB.

    NSData *imageData = [NSData dataWithContentsOfFile:filePath];

    NSString *str_url = [NSString stringWithFormat:@"http://someUrl.aspx?TaskId=%@",ID];

    NSURL *url=[NSURL URLWithString:str_url];

    NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
    [request setURL:url];
    [request setHTTPMethod:@"POST"];
    NSString *boundary = [NSString stringWithString:@"---------------------------14737809831466499882746641449"];
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@,",boundary];
    [request addValue:contentType forHTTPHeaderField: @"Content-Type"];

    NSMutableData *body = [NSMutableData data];
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithString:[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"UploadedFilePhysical\"; filename=\"%@\"\r\n",Phusicalstr1]] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[NSData dataWithData:imageData]];
    //[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];

Any idea what happened in the upload?

Body:
 NSMutableData *body = [NSMutableData data];

What is this line does?

How are you initializing this?

Replace it with something like this.

NSMutableData *body = [[NSMutableData alloc] init];


问:
How can I use cypress to make a JSON call?
Day one with Cypress.

Trying to make a JSON call and examine result but all attempts giving me undefined.

```<code>describe('Test Number 000001 !!!', function() {
  it('starts off OK', function() {
    expect(true).to.equal(true)
  })
  it('can call the example api', function() {
    cy.request('https://jsonplaceholder.typicode.com/todos/1')
  })
  it('can call the example api and store the result', function() {
    result = cy.request('http://jsonplaceholder.typicode.com/todos/1')
    .then(response => response.json()) // I tried with and without then
    expect(result).to.equal(1) // will fail but once i get real response I will adjust
  })
})
</code>```

Update: the below passes... but doesn't actually check anything (any values used will pass)

```<code>    cy.request('http://jsonplaceholder.typicode.com/todos/1').
    then((response) => {
      response = JSON.stringify(response)
      var jsonData = JSON.parse(response)
      for (var i = 0; i < jsonData.length; i++) {
        expect(jsonData[i]['xuserId']).to.equal(1)
      }
    })
</code>```

答:
You need to convert response object to a json string using stringify function inside the promise.

```<code>.then((response) => {
    response = JSON.stringify(response)
    var jsonData = JSON.parse(response)
    for (var i = 0; i < jsonData.length; i++) {
     expect(jsonData[i]['userId']).eq(1)
       }
</code>```

edit

```<code>expect(jsonData[i]['userId']).to.equal(1)
</code>```

Body:
Day one with Cypress.

Trying to make a JSON call and examine result but all attempts giving me undefined.

describe('Test Number 000001 !!!', function() {
  it('starts off OK', function() {
    expect(true).to.equal(true)
  })
  it('can call the example api', function() {
    cy.request('https://jsonplaceholder.typicode.com/todos/1')
  })
  it('can call the example api and store the result', function() {
    result = cy.request('http://jsonplaceholder.typicode.com/todos/1')
    .then(response => response.json()) // I tried with and without then
    expect(result).to.equal(1) // will fail but once i get real response I will adjust
  })
})

Update: the below passes... but doesn't actually check anything (any values used will pass)

    cy.request('http://jsonplaceholder.typicode.com/todos/1').
    then((response) => {
      response = JSON.stringify(response)
      var jsonData = JSON.parse(response)
      for (var i = 0; i < jsonData.length; i++) {
        expect(jsonData[i]['xuserId']).to.equal(1)
      }
    })

Body:
You need to convert response object to a json string using stringify function inside the promise.

.then((response) => {
    response = JSON.stringify(response)
    var jsonData = JSON.parse(response)
    for (var i = 0; i < jsonData.length; i++) {
     expect(jsonData[i]['userId']).eq(1)
       }

edit

expect(jsonData[i]['userId']).to.equal(1)


问:
How can I ask Eclipse to always prefer the newest version of a library that is included by other libraries?
My project uses junit-4.8.2.jar and mockito-all-1.8.5.jar; both includes Hamcrest 1.1. This is working just fine until I added hamcrest-all-1.2.jar; now I get various NoSuchMethodError, because apparently my code compiles to Hamcrest 1.2, but is being run with Hamcrest 1.1.

It looks like there are various ways to solve this problem (e.g. use junit-dep-4.8.2 instead, etc), but is there a way to tell Eclipse to prefer Hamcrest 1.2. at run-time as well as compile-time?

答: It was already mentioned in the comments, but i think it's also a valid answer: Use Maven to handle the dependency management. If you don't want to use Maven (because you already use Ant or anything like that), use Ivy, Gradle, Buildr or any other build tool with dependency management.</p>


问:
How to decrypt the encrypted UID using firestore security rules?

I get the uid, when users login to firebase for the first time
using phone number.

Then I have encrypted the uid.

Then I have created a Collection as users with Document Id uid in the firestore like: users/uid.

Now the users want to write into users/userId, if the
condition is true like below:

```<code>  match /users/{userId} {
     allow write: if request.auth.uid == userId;
  }
</code>```

Here as I mentioned in number 2 the userId is encrypted, but the request.auth.uid is not encrypted.

So how we can decrypt it here the (userId) ?

If I use hashing sha256, so how can I decode the sha256 in client side ?

I am using crypto-js

答:
According to the documentation, you can use hashed values in security rules.  If you are not using one of the hashing algorithms described, then it will not work.  You can read about how it works in the release notes:

New hashing and hashing-adjacent methods are:

```<code>hashing.crc32()
hashing.crc32c()
hashing.sha256()
hashing.md5()
<ByteValue>.toBase64()
<ByteValue>.toHexString()
<String>.toUtf8()
</code>```

For example, previously, if the version of an email in Firestore was
  hashed with SHA-256, you wouldn't be able to compare that email to the
  plaintext email sent with the auth object. Now you can:

```<code>hashing.sha256(request.auth.email.utf8()) == resource.data.ownerEmailHash
</code>```

Alternatively, if you have a field in a document for users to store
  their novellas, you may want to have a shorter identifier for that
  very long string:

```<code>match /novellas/{hash} {
 allow write: if hash == hashing.sha256(request.resource.data.
           novella.utf8()) && resource == null
}
</code>```

Strings are treated as UTF-8-encoded bytes, and the return value is a
  Bytes type:

```<code>hashing.md5("Tag".utf8()) => b"wQEFjn6iG7vypayJMIjpCw=="
</code>```

Body:
I get the uid, when users login to firebase for the first time
using phone number.

Then I have encrypted the uid.

Then I have created a Collection as users with Document Id uid in the firestore like: users/uid.

Now the users want to write into users/userId, if the
condition is true like below:

  match /users/{userId} {
     allow write: if request.auth.uid == userId;
  }

Here as I mentioned in number 2 the userId is encrypted, but the request.auth.uid is not encrypted.

So how we can decrypt it here the (userId) ?

If I use hashing sha256, so how can I decode the sha256 in client side ?

I am using crypto-js

Body:
According to the documentation, you can use hashed values in security rules.  If you are not using one of the hashing algorithms described, then it will not work.  You can read about how it works in the release notes:

New hashing and hashing-adjacent methods are:

hashing.crc32()
hashing.crc32c()
hashing.sha256()
hashing.md5()
<ByteValue>.toBase64()
<ByteValue>.toHexString()
<String>.toUtf8()

For example, previously, if the version of an email in Firestore was
  hashed with SHA-256, you wouldn't be able to compare that email to the
  plaintext email sent with the auth object. Now you can:

hashing.sha256(request.auth.email.utf8()) == resource.data.ownerEmailHash

Alternatively, if you have a field in a document for users to store
  their novellas, you may want to have a shorter identifier for that
  very long string:

match /novellas/{hash} {
 allow write: if hash == hashing.sha256(request.resource.data.
           novella.utf8()) && resource == null
}

Strings are treated as UTF-8-encoded bytes, and the return value is a
  Bytes type:

hashing.md5("Tag".utf8()) => b"wQEFjn6iG7vypayJMIjpCw=="


问:
How do I add multiple Keys and Values into dictionary at the same time?
I am trying to add a column as the key and the column to the right of it as the value.

Can I do this without a loop?

I tried:

```<code>analystDict.Add Key:=refWS.Range("A2:A21"), Item:=refWS.Range("B2:B21")
</code>```

When I try to Debug.Print I get a Type mismatch error:

```<code>For Each x In analystDict.Keys
    Debug.Print x, analystDict(x)
Next x
</code>```

答:
You can't do this in VBA without writing a helper function.</p>

```<code>Option Explicit

Public Sub AddTest()
    Dim analystDict As Scripting.Dictionary
    Set analystDict = New Scripting.Dictionary

    Dim refWS As Worksheet
    Set refWS = ActiveSheet

    AddToDictionary _
        analystDict, _
        Application.WorksheetFunction.Transpose(refWS.Range("A2:A21").Value), _
        Application.WorksheetFunction.Transpose(refWS.Range("B2:B21").Value)

End Sub

Public Sub AddToDictionary(ByRef ipDict As Scripting.Dictionary, ByVal ipKeys As Variant, ByVal ipValues As Variant)

    If UBound(ipKeys) <> UBound(ipValues) Then

        MsgBox "Arrays are not the same size"
        Exit Function

    End If

    Dim myIndex As Long
    For myIndex = LBound(ipKeys) To UBound(ipKeys)

        ipDict.Add ipKeys(myIndex), ipValues(myIndex)

    Next

End Function
</code>```

Body:
I am trying to add a column as the key and the column to the right of it as the value.

Can I do this without a loop?

I tried:

analystDict.Add Key:=refWS.Range("A2:A21"), Item:=refWS.Range("B2:B21")

When I try to Debug.Print I get a Type mismatch error:

For Each x In analystDict.Keys
    Debug.Print x, analystDict(x)
Next x

Body:
You can't do this in VBA without writing a helper function.

Option Explicit

Public Sub AddTest()
    Dim analystDict As Scripting.Dictionary
    Set analystDict = New Scripting.Dictionary

    Dim refWS As Worksheet
    Set refWS = ActiveSheet

    AddToDictionary _
        analystDict, _
        Application.WorksheetFunction.Transpose(refWS.Range("A2:A21").Value), _
        Application.WorksheetFunction.Transpose(refWS.Range("B2:B21").Value)

End Sub

Public Sub AddToDictionary(ByRef ipDict As Scripting.Dictionary, ByVal ipKeys As Variant, ByVal ipValues As Variant)

    If UBound(ipKeys) <> UBound(ipValues) Then

        MsgBox "Arrays are not the same size"
        Exit Function

    End If

    Dim myIndex As Long
    For myIndex = LBound(ipKeys) To UBound(ipKeys)

        ipDict.Add ipKeys(myIndex), ipValues(myIndex)

    Next

End Function


问:
SOIL_load_image() returns null
ANSWER

After using SOIL_last_result(), as dcook had suggested, I found out two things:

1) It couldn't find the image, as PaulMcKenzie said, so my working directory was indeed incorrect as genpfault mentioned.

2) After I set a full path, it mentioned that my jpeg format(progressive), was not supported. I set the image to the standard jpeg format and it worked.

Thanks for the help!

ORIGINAL QUESTION

I am currently trying to load an image using SOIL to use with OpenGL. However, it seems to fail to properly load the image as the variable it is assigned to ends up being null. I've tried looking at this but it seems the guy just put the wrong layout position when he set the attribute. I have it check for errors(glGetError()) after every line but I omitted that here for readability.

The OpenGL error occurs after glTexImage2D() with a GL_INVALID_VALUE. This is more than likely because imgWidth/imgHeight are bigger than GL_MAX_TEXTURE_SIZE due to the null image.

Output:

```<code>null: 1
Max size: 3379
Width: 4298563
Height: 2686488
Obj: 1
GL_INVALID_VALUE - ../src/polygon.cpp:222
</code>```

Code:

```<code>    // Generate the texture object and binds it.
    glGenTextures(1, &m_texture);
    glBindTexture(GL_TEXTURE_2D, m_texture);

    // Texture image data
    int imgWidth, imgHeight;

    // Load the texture image.
    unsigned char* image = SOIL_load_image("potato.jpg",
                  &imgWidth,
                  &imgHeight,
                  0,
                  SOIL_LOAD_RGB);

    std::cout << "null: " << !image << std::endl;
    std::cout << "Max size: " << GL_MAX_TEXTURE_SIZE << std::endl;
    std::cout << "Width: " <<  imgWidth << std::endl;
    std::cout << "Height: " << imgHeight << std::endl;
    std::cout << "Obj: " << m_texture << std::endl;

    // Generate the texture to the currently bound texture object.
    glTexImage2D(GL_TEXTURE_2D,
         0,
         GL_RGB,
         imgWidth,
         imgHeight,
         0,
         GL_RGB,
         GL_UNSIGNED_BYTE,
         image);

    // Generate the mipmap to the currently bound texture object.
    glGenerateMipmap(GL_TEXTURE_2D);

    // Unbind and free image data.
    SOIL_free_image_data(image);
    glBindTexture(GL_TEXTURE_2D, 0);
</code>```

Let me know if any more data is needed. Thanks!

EDIT 1: Yes, the image is in the correct location:

Also, I tried using a full path, it did not help.

答:
I had the same issue. The solution was to set full path to file, like

```<code>C:/TestProjectsCPP/OpenGLTutorials/OpenGLTutorials/res/images/image1.jpg
</code>```

After this image was loaded and shown.

Title: SOIL_load_image() returns null

Body:
ANSWER

After using SOIL_last_result(), as dcook had suggested, I found out two things:

1) It couldn't find the image, as PaulMcKenzie said, so my working directory was indeed incorrect as genpfault mentioned.

2) After I set a full path, it mentioned that my jpeg format(progressive), was not supported. I set the image to the standard jpeg format and it worked.

Thanks for the help!

ORIGINAL QUESTION

I am currently trying to load an image using SOIL to use with OpenGL. However, it seems to fail to properly load the image as the variable it is assigned to ends up being null. I've tried looking at this but it seems the guy just put the wrong layout position when he set the attribute. I have it check for errors(glGetError()) after every line but I omitted that here for readability.

The OpenGL error occurs after glTexImage2D() with a GL_INVALID_VALUE. This is more than likely because imgWidth/imgHeight are bigger than GL_MAX_TEXTURE_SIZE due to the null image.

Output:

null: 1
Max size: 3379
Width: 4298563
Height: 2686488
Obj: 1
GL_INVALID_VALUE - ../src/polygon.cpp:222

Code:

    // Generate the texture object and binds it.
    glGenTextures(1, &m_texture);
    glBindTexture(GL_TEXTURE_2D, m_texture);

    // Texture image data
    int imgWidth, imgHeight;

    // Load the texture image.
    unsigned char* image = SOIL_load_image("potato.jpg",
                  &imgWidth,
                  &imgHeight,
                  0,
                  SOIL_LOAD_RGB);

    std::cout << "null: " << !image << std::endl;
    std::cout << "Max size: " << GL_MAX_TEXTURE_SIZE << std::endl;
    std::cout << "Width: " <<  imgWidth << std::endl;
    std::cout << "Height: " << imgHeight << std::endl;
    std::cout << "Obj: " << m_texture << std::endl;

    // Generate the texture to the currently bound texture object.
    glTexImage2D(GL_TEXTURE_2D,
         0,
         GL_RGB,
         imgWidth,
         imgHeight,
         0,
         GL_RGB,
         GL_UNSIGNED_BYTE,
         image);

    // Generate the mipmap to the currently bound texture object.
    glGenerateMipmap(GL_TEXTURE_2D);

    // Unbind and free image data.
    SOIL_free_image_data(image);
    glBindTexture(GL_TEXTURE_2D, 0);

Let me know if any more data is needed. Thanks!

EDIT 1: Yes, the image is in the correct location:

Also, I tried using a full path, it did not help.

Body:
I had the same issue. The solution was to set full path to file, like

C:/TestProjectsCPP/OpenGLTutorials/OpenGLTutorials/res/images/image1.jpg

After this image was loaded and shown.


问:
Parse - Updating local DataStore in combination with LiveQuery
I am writing an Android app using the local data store and LiveQueries. I am facing a problem in the combination of both. When I start the app, I fetch all instances of an entity the current user has access to and save them in the local storage. Additionally, I subscribe to changes of this entity with the same query using a LiveQuery. When such an entity that is changed by cloud code, e.g., gets deleted, the event is properly received in the app. However, the entity as part of the local storage is not deleted. As I have not found anything about this in the documentation or by searching the Internet my question is, if this is normal behavior and if I have to deal with the changes in the local storage manually, e.g., by unpinning the entity in this case. The other possibility is, that it should update, but it does not in my case somehow.

If I have to deal with it manually: What is the best way to replace/update the entity in the local storage, if only an update happens?

Thanks!

答: As a solution I simply do the pinning/unpinning now in every event handler. It really seems, that there is no automatic updating of the local datastore.</p>


问:
UITextView: How to really disable editing?
I am trying to disable editing on my UITextView. I have tried [aboutStable setUserInteractionEnabled: NO], but it causes the page to not be accessible.

Here is the current code.

```<code>- (void)loadTextView1 {
    UITextView *textView1 = [[UITextView alloc] init];
    [textView1 setFont:[UIFont fontWithName:@"Helvetica" size:14]];
    [textView1 setText:@"Example of editable UITextView"];
    [textView1 setTextColor:[UIColor blackColor]];
    [textView1 setBackgroundColor:[UIColor clearColor]];
    [textView1 setTextAlignment:UITextAlignmentLeft];
    [textView1 setFrame:CGRectMake(15, 29, 290, 288)];
    [self addSubview:textView1];
    [textView1 release];
}
</code>```

答:
Wow, this one's certainly being done to death! Sorry to add another but I should mention you can remove any user uncertainty with:</p>

```<code>commentTextView.isUserInteractionEnabled = false
</code>```

Body:
I am trying to disable editing on my UITextView. I have tried [aboutStable setUserInteractionEnabled: NO], but it causes the page to not be accessible.

Here is the current code.

- (void)loadTextView1 {
    UITextView *textView1 = [[UITextView alloc] init];
    [textView1 setFont:[UIFont fontWithName:@"Helvetica" size:14]];
    [textView1 setText:@"Example of editable UITextView"];
    [textView1 setTextColor:[UIColor blackColor]];
    [textView1 setBackgroundColor:[UIColor clearColor]];
    [textView1 setTextAlignment:UITextAlignmentLeft];
    [textView1 setFrame:CGRectMake(15, 29, 290, 288)];
    [self addSubview:textView1];
    [textView1 release];
}

Body:
Wow, this one's certainly being done to death! Sorry to add another but I should mention you can remove any user uncertainty with:

commentTextView.isUserInteractionEnabled = false


问:
Python typehint for os.getenv causes downstream incompatible type errors
When using os.getenv to retrieve environment variables, the default behavior returns a type of Optional[str]. This is problematic as any downstream methods/functions that utilize these variables will likely be defined to accept a str type explicitly. Is there an accepted usage to get around this issue or enforce the str return type?

In the stub file definition for getenv in typeshed you can find that getenv can have a return type of Optional[str] or Union[str, T_] depending on the usage of the default kwarg.

The four options I can see as yet are:

Define any downstream operations to accept Optional[str] types as arguments. This doesn't feel particularly right as a function/method may not be structured in a way that the Optional type makes sense. i.e. the operation has no reason for a particular argument to be None.

Use the default kwarg for getenv and provide a str default value. This seems more correct, but requires that one set a default value for every usage of getenv. The only problem I can see with this is that doing so may be confounding for testing or usage in different environments.

Define some kind of variable checking function. This could be a function that accepts the name of an environment variable to load, explicitly returns a string, and raises an error if the environment variable doesn't exist.

Explicitly set the type of the value returned by getenv to be a str. I really don't like this as it expects the environment to always be properly configured which, in my experience, is not a good assumption.

Find below an example that raises a mypy error.

import os

SOME_VAR = os.getenv("SOME_VAR")

def some_func(val: str) -> None:
    print(f"Loaded env var: {val}")

some_func(SOME_VAR)
```

The above raises the mypy error:

error: Argument 1 to "some_func" has incompatible type "Optional[str]"; expected "str"

答:
tl;dr Use os.environ['SOME_VAR'] if you're sure it's always there

os.getenv can and does return None -- mypy is being helpful in showing you have a bug there:

```<code>>>> repr(os.getenv('DOES_NOT_EXIST'))
'None'
>>> repr(os.getenv('USER'))
"'asottile'"
</code>```

Alternatively, you can convince mypy that it is of the type you expect in two different ways:

utilizing assertions:

x = os.getenv('SOME_VAR')
assert x is not None, x
# mypy will believe that it is non-None after this point
```

<ol start="2">
<li><p>utilizing a cast:</p>

<pre class="lang-py prettyprint-override"><code>from typing import cast

x = cast(str, os.getenv('SOME_VAR'))
# mypy will believe that it is a `str` after this point
</code>```

(the cast has some downsides in that it is never checked, whereas the assertion will hopefully lead to a test failure)

I would suggest not ignoring this error / working around it and instead use os.environ['SOME_VAR'] for things you expect to always be there, or write a condition to check for the error case when it is missing

Body:
When using os.getenv to retrieve environment variables, the default behavior returns a type of Optional[str]. This is problematic as any downstream methods/functions that utilize these variables will likely be defined to accept a str type explicitly. Is there an accepted usage to get around this issue or enforce the str return type?

In the stub file definition for getenv in typeshed you can find that getenv can have a return type of Optional[str] or Union[str, T_] depending on the usage of the default kwarg.

The four options I can see as yet are:

Define any downstream operations to accept Optional[str] types as arguments. This doesn't feel particularly right as a function/method may not be structured in a way that the Optional type makes sense. i.e. the operation has no reason for a particular argument to be None.

Use the default kwarg for getenv and provide a str default value. This seems more correct, but requires that one set a default value for every usage of getenv. The only problem I can see with this is that doing so may be confounding for testing or usage in different environments.

Define some kind of variable checking function. This could be a function that accepts the name of an environment variable to load, explicitly returns a string, and raises an error if the environment variable doesn't exist.

Explicitly set the type of the value returned by getenv to be a str. I really don't like this as it expects the environment to always be properly configured which, in my experience, is not a good assumption.

Find below an example that raises a mypy error.

import os

SOME_VAR = os.getenv("SOME_VAR")

def some_func(val: str) -> None:
    print(f"Loaded env var: {val}")

some_func(SOME_VAR)

The above raises the mypy error:

error: Argument 1 to "some_func" has incompatible type "Optional[str]"; expected "str"

Body:
tl;dr Use os.environ['SOME_VAR'] if you're sure it's always there

os.getenv can and does return None -- mypy is being helpful in showing you have a bug there:

>>> repr(os.getenv('DOES_NOT_EXIST'))
'None'
>>> repr(os.getenv('USER'))
"'asottile'"

Alternatively, you can convince mypy that it is of the type you expect in two different ways:

utilizing assertions:

x = os.getenv('SOME_VAR')
assert x is not None, x
# mypy will believe that it is non-None after this point

utilizing a cast:

from typing import cast

x = cast(str, os.getenv('SOME_VAR'))
# mypy will believe that it is a `str` after this point

(the cast has some downsides in that it is never checked, whereas the assertion will hopefully lead to a test failure)

I would suggest not ignoring this error / working around it and instead use os.environ['SOME_VAR'] for things you expect to always be there, or write a condition to check for the error case when it is missing


问:
Apache ActiveMQ Artemis queue name format requirement
I am trying out ActiveMQ Artemis with a queue design. I want to know if there is a specified format for correct queue name validation. Also is there a default maximum length for name of the queue and supported symbols? I tried and searched for an answer but could not find any.</p>

答: ActiveMQ Artemis doesn't perform any queue name validation either for length or special symbols.</p>


问:
Automapper - Mapping the index into a property of collection
I'm mapping a domain model to a DTO and vice versa. I'm trying to configure my API to accept a DTO with a collection, where the order of that collection will map to a int Sequence in my domain object for persistence.

```<code>public class Model {
    public ICollection<Fields> Fields { get; set; }
}
public class Field {
    public int Sequence { get; set; }
}
</code>```

```<code>CreateMap<ModelView, Model>()
    .ForMember(x => x.Fields, opt => opt...)
    // here I want to specify that currentField.Sequence = Model.Fields.IndexOf(currentField)
    //     , or to set it equal to some counter++;
    ;
</code>```

Is such a thing possible in Automapper, or would I have to write my own ConstructUsing() method to do this logic?  I'm hesitant to use ConstructUsing() because I have a mapping specified for the Field DTO and I don't want to duplicate that logic.

I also would like to be able to configure it so that when I'm going back to my DTO (Model -> ModelView) that I can insert the Fields into the collection in the order specified by Sequence.

答:
I think I found the solution I was looking for. Using AfterMap() I'm able to override these values from being mapped directly:

```<code>CreateMap<Model, ModelView>()
    .AfterMap((m, v) =>
    {
        v.Fields = v.Fields?.OrderBy(x => x.Sequence).ToList();
        //ensure that the DTO has the fields in the correct order
    })
    ;

CreateMap<ModelView, Model>()
    .AfterMap((v, m) =>
    {
        //override the sequence values based on the order they were provided in the DTO
        var counter = 0;
        foreach (var field in m.Fields)
        {
            field.Sequence = counter++;
        }
    })
</code>```

Body:
I'm mapping a domain model to a DTO and vice versa. I'm trying to configure my API to accept a DTO with a collection, where the order of that collection will map to a int Sequence in my domain object for persistence.

public class Model {
    public ICollection<Fields> Fields { get; set; }
}
public class Field {
    public int Sequence { get; set; }
}

CreateMap<ModelView, Model>()
    .ForMember(x => x.Fields, opt => opt...)
    // here I want to specify that currentField.Sequence = Model.Fields.IndexOf(currentField)
    //     , or to set it equal to some counter++;
    ;

Is such a thing possible in Automapper, or would I have to write my own ConstructUsing() method to do this logic?  I'm hesitant to use ConstructUsing() because I have a mapping specified for the Field DTO and I don't want to duplicate that logic.

I also would like to be able to configure it so that when I'm going back to my DTO (Model -> ModelView) that I can insert the Fields into the collection in the order specified by Sequence.

Body:
I think I found the solution I was looking for. Using AfterMap() I'm able to override these values from being mapped directly:

CreateMap<Model, ModelView>()
    .AfterMap((m, v) =>
    {
        v.Fields = v.Fields?.OrderBy(x => x.Sequence).ToList();
        //ensure that the DTO has the fields in the correct order
    })
    ;

CreateMap<ModelView, Model>()
    .AfterMap((v, m) =>
    {
        //override the sequence values based on the order they were provided in the DTO
        var counter = 0;
        foreach (var field in m.Fields)
        {
            field.Sequence = counter++;
        }
    })


问:
Any tool to increment the build number and build version automatically for react-native apps (Both iOS and Android)
I need to automate the build number and version for both iOS and Android.

For iOS there is agvtool and fastlane too.

Is there an alternate tool which will work seamlessly across iOS, Android

答:
So, I've been using a script in my build phases to increment the build number, but it only works if the value is specified in the Info.plist file, and not referenced in the Info.plist file. Given this was part of the 0.5x.x -> 0.6x.x change for React Native, it does mean I'm running in an old way.

```<code>buildNumber=$(/usr/libexec/PlistBuddy -c "Print CFBundleVersion" "${PROJECT_DIR}/${INFOPLIST_FILE}" | sed -E 's/^([0-9]+).*/\1/')
buildNumber=$(($buildNumber + 1))
/usr/libexec/PlistBuddy -c "Set :CFBundleVersion $buildNumber" "${PROJECT_DIR}/${INFOPLIST_FILE}"
</code>```

Body:
So, I've been using a script in my build phases to increment the build number, but it only works if the value is specified in the Info.plist file, and not referenced in the Info.plist file. Given this was part of the 0.5x.x -> 0.6x.x change for React Native, it does mean I'm running in an old way.

buildNumber=$(/usr/libexec/PlistBuddy -c "Print CFBundleVersion" "${PROJECT_DIR}/${INFOPLIST_FILE}" | sed -E 's/^([0-9]+).*/\1/')
buildNumber=$(($buildNumber + 1))
/usr/libexec/PlistBuddy -c "Set :CFBundleVersion $buildNumber" "${PROJECT_DIR}/${INFOPLIST_FILE}"


问:
Flask API. Loading status response
I am making a service, that takes analytical data and counts correlation between this data and database data.

Because of the fact that there is a lot of correlations to build (could be up to 10 hours computations), I want to make sure that process has begun and to send a response with something like a loading bar.

So any time the request is sent, the response should contain information on how much is computed.

Could Flask provide this solution?

答:
While normally I'd refrain from answering such a broad question. I was actually curious about this myself. I've collected a couple of resources below which you should find helpful.

Another similar question

An example of how to visually complies this in html + flask

Now, that said. In the future I would suggest you avoid asking broad sweeping questions like "is xyz possible." This is because normally the answer is "yes, but it's hard", or "yes, but don't". There is a great stack overflow page about how to ask effective questions in order to get the most helpful answers. I suggest reading it and understanding the basic principle behind it.

Title: Flask API. Loading status response


问:
How to navigate vehicle icon for current location using google map SDK in swift?
I'm calling direction API to draw the route and trying to move the current location marker icon as user moves the location, But I m facing following problems while implementation.

while moving the icon, It appears like icon got tilt.

It doesn't display the actual user position on the route, Icon appears like it is traveling on the side of route.

My location icon (blue icon) on google map continuously changes its position.

func locationManager(_ manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) {
    let direction = newHeading.trueHeading
        lastDriverAngleFromNorth = direction
        self.sourceMarker?.rotation = (lastDriverAngleFromNorth - mapBearing) - bearingValue

        DispatchQueue.main.async {
            CATransaction.begin()
            CATransaction.setValue(2, forKey: kCATransactionAnimationDuration)
                self.gmsmapView?.animate(toBearing: newHeading.magneticHeading)
                    CATransaction.commit()
    }
}

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    if let lastLocation = locations.last {

        self.currentLocation = lastLocation
            let zoom = self.gmsmapView?.camera.zoom ?? 20.0
            zoomLevel = zoom
            let destination = CLLocation.init(latitude: viewModel.marker.location[0], longitude: viewModel.marker.location[1])
            let bearing = getBearingBetweenTwoPoints(point1: lastLocation.coordinate, point2: destination.coordinate)
            self.cameraMoveToLocation(toLocation: lastLocation, zoom:zoom, bearing: bearing)
    }
}

func mapView(_ mapView: GMSMapView, didChange position: GMSCameraPosition) {
    mapBearing  = position.bearing
    if let coordinate = self.currentLocation?.coordinate{
            self.rerouteCalculation(currentLocation:coordinate)
    }

    self.sourceMarker?.rotation = (lastDriverAngleFromNorth - mapBearing) - bearingValue
}

func cameraMoveToLocation(toLocation: CLLocation, zoom : Float, bearing : Double) {
    self.gmsmapView?.animate(toLocation: toLocation.coordinate)
    self.sourceMarker?.position = toLocation.coordinate
}
```

Can anyone please help me, I'm stuck here.

答:
Make sure that you choose the correct location accuracy for your needs.

CCLocationAccuracy offers the following options:

kCLLocationAccuracyBestForNavigation:  <= You should use this when the device is plugged to a power source

The highest possible accuracy that uses additional sensor data to
facilitate navigation apps.

kCLLocationAccuracyBest: <= You should use this when the device runs on battery

The best level of accuracy available.

kCLLocationAccuracyNearestTenMeters: Accurate
to within ten meters of the desired target.

kCLLocationAccuracyHundredMeters: Accurate to
within one hundred meters.

kCLLocationAccuracyKilometer: Accurate to the
nearest kilometer.

kCLLocationAccuracyThreeKilometers: Accurate
to the nearest three kilometers.

Body:
I'm calling direction API to draw the route and trying to move the current location marker icon as user moves the location, But I m facing following problems while implementation.

while moving the icon, It appears like icon got tilt.

It doesn't display the actual user position on the route, Icon appears like it is traveling on the side of route.

My location icon (blue icon) on google map continuously changes its position.

func locationManager(_ manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) {
    let direction = newHeading.trueHeading
        lastDriverAngleFromNorth = direction
        self.sourceMarker?.rotation = (lastDriverAngleFromNorth - mapBearing) - bearingValue

        DispatchQueue.main.async {
            CATransaction.begin()
            CATransaction.setValue(2, forKey: kCATransactionAnimationDuration)
                self.gmsmapView?.animate(toBearing: newHeading.magneticHeading)
                    CATransaction.commit()
    }
}

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    if let lastLocation = locations.last {

        self.currentLocation = lastLocation
            let zoom = self.gmsmapView?.camera.zoom ?? 20.0
            zoomLevel = zoom
            let destination = CLLocation.init(latitude: viewModel.marker.location[0], longitude: viewModel.marker.location[1])
            let bearing = getBearingBetweenTwoPoints(point1: lastLocation.coordinate, point2: destination.coordinate)
            self.cameraMoveToLocation(toLocation: lastLocation, zoom:zoom, bearing: bearing)
    }
}

func mapView(_ mapView: GMSMapView, didChange position: GMSCameraPosition) {
    mapBearing  = position.bearing
    if let coordinate = self.currentLocation?.coordinate{
            self.rerouteCalculation(currentLocation:coordinate)
    }

    self.sourceMarker?.rotation = (lastDriverAngleFromNorth - mapBearing) - bearingValue
}

func cameraMoveToLocation(toLocation: CLLocation, zoom : Float, bearing : Double) {
    self.gmsmapView?.animate(toLocation: toLocation.coordinate)
    self.sourceMarker?.position = toLocation.coordinate
}

Can anyone please help me, I'm stuck here.


问:
certificate signed by unknown authority when connect to remote kubernetes cluster using kubectl
I am using kubectl to connect remote kubernetes cluster(v1.15.2),I am copy config from remote server to local macOS:

```<code>scp -r root@ip:~/.kube/config ~/.kube
</code>```

and change the url to https://kube-ctl.example.com,I exposed the api server to the internet:

```<code>apiVersion: v1
clusters:
- cluster:
    certificate-authority-data: LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSURvakNDQW9xZ0F3SUJBZ0lVU3FpUlZSU3FEOG1PemRCT1MyRzlJdGE0R2Nrd0RRWUpLb1pJaHZjTkFRRUwKQlFB92FERUxNQWtHQTFVRUJoTUNRMDR4RURBT0JnTlZCQWdUQjBKbGFVcHBibWN4RURBT0JnTlZCQWNUQjBKbAphVXBwYm1jeEREQUtCZ05WQkFvVEEyczRjekVTTUJBR0ExVUVDeE1KTkZCaGNtRmthV2R0TVJNd0VRWURWUVFECkV3cHJkV0psY201bGRHVnpNQ0FYR3RFNU1Ea3hNekUxTkRRd01Gb1lEekl4TVRrd09ESXdNVFUwTkRBd1dqQm8KTVFzd0NRWURWUVFHRXdKRFRqRVFNQTRHQTFVRUNCTUhRbVZwU21sdVp6RVFNQTRHQTFVRUJ4TUhRbVZwU21sdQpaekVNTUFvR0ExVUVDaE1EYXpoek1SSXdFQVlEVlFRTEV3azBVR0Z5WVdScFoyMHhFekFSQmdOVkJBTVRDbXQxClltVnlibVYwWlhNd2dnRWlNQTBHQ1NxR1NJYjNEUUVCQVFVQUE0SUJEd0F3Z2dFS0FvSUJBUUNzOGFFR2R2TUgKb0E1eTduTjVydnAvQkEyTVM1RG1TNWwzQ0p4S3VMOGJ1bkF3alF1c0lTalUxVWlqeVdGOW03VzA3elZJaVJpRwpiYzZGT3JkSEJ2QXgzazBpT2pPRlduTHp1UjdaSFhqQ3lTbDJRam9YN3gzL0l1MERQelNHTXJLSzZETGpTRTk4CkdadEpjUi9OSmpiVFFJc3FXbWFEdUIyc3dmcEc1ZmlZU1A1KzVpcld1TG1pYjVnWnJYeUJJNlJ0dVV4K1NvdW0KN3RDKzJaVG5QdFF0QnFUZHprT3p3THhwZ0Zhd1kvSU1mbHBsaUlMTElOamcwRktxM21NOFpUa0xvNXcvekVmUApHT25GNkNFWlR6bkdrTWc2aUVGenNBcDU5N2lMUDBNTkR4YUNjcTRhdTlMdnMzYkdOZmpqdDd3WkxIVklLa0lGCm44Mk92cExGaElq2kFnTUJBQUdqUWpCQU1BNEdBMVVkRHdFQi93UUVBd0lCQmpBUEJnTlZIUk1CQWY4RUJUQUQKQVFIL01CMEdBMVVkRGdRV0JCUm0yWHpJSHNmVzFjMEFGZU9SLy9Qakc4dWdzREFOQmdrcWhraUc5dzBCQVFzRgpBQU9DQVFFQW1mOUozN3RYTys1dWRmT2RLejdmNFdMZyswbVJUeTBRSEVIblk5VUNLQi9vN2hLUVJHRXI3VjNMCktUeGloVUhvbHY1QzVUdG8zbUZJY2FWZjlvZlp0VVpvcnpxSUFwNE9Od1JpSnQ1Yk94K1d6SW5qN2JHWkhnZjkKSk8rUmNxQnQrUWsrejhTMmJKRG04WFdvMW5WdjJRNU1pUndPdnRIbnRxd3MvTlJ2bHBGV25ISHBEVExjOU9kVwpoMllzWVpEMmV4d0FRVDkxSlExVjRCdklrZGFPeW9USHZ6U2oybThSTzh6b3JBd09kS1NTdG9TZXdpOEhMeGI2ClhmaTRFbjR4TEE3a3pmSHFvcDZiSFF1L3hCa0JzYi9hd29kdDJKc2FnOWFZekxEako3S1RNYlQyRW52MlllWnIKSUhBcjEyTGVCRGRHZVd1eldpZDlNWlZJbXJvVnNRPT0KLS0tLS1FTkQgQ0VSVElGSUNBVEUtLS0tLQo=
    server: https://k8s-ctl.example.com
  name: kubernetes
contexts:
- context:
    cluster: kubernetes
    namespace: kube-system
    user: admin
  name: kubernetes
current-context: kubernetes
kind: Config
preferences: {}
users:
- name: admin
  user:
</code>```

when I get cluster pod info in my local Mac:

```<code>kubectl get pods --all-namespaces
</code>```

give this error:

```<code>Unable to connect to the server: x509: certificate signed by unknown authority
</code>```

when I access https://k8s-ctl.example.com in google chrome,the result is:

```<code>{
kind: "Status",
apiVersion: "v1",
metadata: { },
status: "Failure",
message: "Unauthorized",
reason: "Unauthorized",
code: 401
}
</code>```

what should I do to make access remote k8s cluster sucess using kubectl client?

One way I have tried to using this .kube/config generate by command,but get the same result:

```<code>apiVersion: v1
clusters:
- cluster:
    certificate-authority: ssl/ca.pem
    server: https://k8s-ctl.example.com
  name: default
contexts:
- context:
    cluster: default
    user: admin
  name: default
current-context: default
kind: Config
preferences: {}
users:
- name: admin
  user:
    client-certificate: ssl/admin.pem
    client-key: ssl/admin-key.pem
</code>```

答:
When kubectl interacts with kube API server it will validate the kube API server certificate as well as send the certificate in client-certificate  to the kube API server for mutual TLS authentication. I believe the problem is either of below.

the ca that you have used to generate the  client-certificate is not the ca that has been used to startup the kube API server.

The ca in certificate-authority-data is not the ca used to generate kube API server certificate.

If you make sure that you are using same ca to generate all the certificates consistently across the board then it should work.

Body:
I am using kubectl to connect remote kubernetes cluster(v1.15.2),I am copy config from remote server to local macOS:

scp -r root@ip:~/.kube/config ~/.kube

and change the url to https://kube-ctl.example.com,I exposed the api server to the internet:

apiVersion: v1
clusters:
- cluster:
    certificate-authority-data: LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSURvakNDQW9xZ0F3SUJBZ0lVU3FpUlZSU3FEOG1PemRCT1MyRzlJdGE0R2Nrd0RRWUpLb1pJaHZjTkFRRUwKQlFB92FERUxNQWtHQTFVRUJoTUNRMDR4RURBT0JnTlZCQWdUQjBKbGFVcHBibWN4RURBT0JnTlZCQWNUQjBKbAphVXBwYm1jeEREQUtCZ05WQkFvVEEyczRjekVTTUJBR0ExVUVDeE1KTkZCaGNtRmthV2R0TVJNd0VRWURWUVFECkV3cHJkV0psY201bGRHVnpNQ0FYR3RFNU1Ea3hNekUxTkRRd01Gb1lEekl4TVRrd09ESXdNVFUwTkRBd1dqQm8KTVFzd0NRWURWUVFHRXdKRFRqRVFNQTRHQTFVRUNCTUhRbVZwU21sdVp6RVFNQTRHQTFVRUJ4TUhRbVZwU21sdQpaekVNTUFvR0ExVUVDaE1EYXpoek1SSXdFQVlEVlFRTEV3azBVR0Z5WVdScFoyMHhFekFSQmdOVkJBTVRDbXQxClltVnlibVYwWlhNd2dnRWlNQTBHQ1NxR1NJYjNEUUVCQVFVQUE0SUJEd0F3Z2dFS0FvSUJBUUNzOGFFR2R2TUgKb0E1eTduTjVydnAvQkEyTVM1RG1TNWwzQ0p4S3VMOGJ1bkF3alF1c0lTalUxVWlqeVdGOW03VzA3elZJaVJpRwpiYzZGT3JkSEJ2QXgzazBpT2pPRlduTHp1UjdaSFhqQ3lTbDJRam9YN3gzL0l1MERQelNHTXJLSzZETGpTRTk4CkdadEpjUi9OSmpiVFFJc3FXbWFEdUIyc3dmcEc1ZmlZU1A1KzVpcld1TG1pYjVnWnJYeUJJNlJ0dVV4K1NvdW0KN3RDKzJaVG5QdFF0QnFUZHprT3p3THhwZ0Zhd1kvSU1mbHBsaUlMTElOamcwRktxM21NOFpUa0xvNXcvekVmUApHT25GNkNFWlR6bkdrTWc2aUVGenNBcDU5N2lMUDBNTkR4YUNjcTRhdTlMdnMzYkdOZmpqdDd3WkxIVklLa0lGCm44Mk92cExGaElq2kFnTUJBQUdqUWpCQU1BNEdBMVVkRHdFQi93UUVBd0lCQmpBUEJnTlZIUk1CQWY4RUJUQUQKQVFIL01CMEdBMVVkRGdRV0JCUm0yWHpJSHNmVzFjMEFGZU9SLy9Qakc4dWdzREFOQmdrcWhraUc5dzBCQVFzRgpBQU9DQVFFQW1mOUozN3RYTys1dWRmT2RLejdmNFdMZyswbVJUeTBRSEVIblk5VUNLQi9vN2hLUVJHRXI3VjNMCktUeGloVUhvbHY1QzVUdG8zbUZJY2FWZjlvZlp0VVpvcnpxSUFwNE9Od1JpSnQ1Yk94K1d6SW5qN2JHWkhnZjkKSk8rUmNxQnQrUWsrejhTMmJKRG04WFdvMW5WdjJRNU1pUndPdnRIbnRxd3MvTlJ2bHBGV25ISHBEVExjOU9kVwpoMllzWVpEMmV4d0FRVDkxSlExVjRCdklrZGFPeW9USHZ6U2oybThSTzh6b3JBd09kS1NTdG9TZXdpOEhMeGI2ClhmaTRFbjR4TEE3a3pmSHFvcDZiSFF1L3hCa0JzYi9hd29kdDJKc2FnOWFZekxEako3S1RNYlQyRW52MlllWnIKSUhBcjEyTGVCRGRHZVd1eldpZDlNWlZJbXJvVnNRPT0KLS0tLS1FTkQgQ0VSVElGSUNBVEUtLS0tLQo=
    server: https://k8s-ctl.example.com
  name: kubernetes
contexts:
- context:
    cluster: kubernetes
    namespace: kube-system
    user: admin
  name: kubernetes
current-context: kubernetes
kind: Config
preferences: {}
users:
- name: admin
  user:

when I get cluster pod info in my local Mac:

kubectl get pods --all-namespaces

give this error:

Unable to connect to the server: x509: certificate signed by unknown authority

when I access https://k8s-ctl.example.com in google chrome,the result is:

{
kind: "Status",
apiVersion: "v1",
metadata: { },
status: "Failure",
message: "Unauthorized",
reason: "Unauthorized",
code: 401
}

what should I do to make access remote k8s cluster sucess using kubectl client?

One way I have tried to using this .kube/config generate by command,but get the same result:

apiVersion: v1
clusters:
- cluster:
    certificate-authority: ssl/ca.pem
    server: https://k8s-ctl.example.com
  name: default
contexts:
- context:
    cluster: default
    user: admin
  name: default
current-context: default
kind: Config
preferences: {}
users:
- name: admin
  user:
    client-certificate: ssl/admin.pem
    client-key: ssl/admin-key.pem


问:
Django, connect one field with multiple models
I guess it is a "normal" problem. I want to connect model C with different Models A,B,..

```<code>Model A "buildings"
 - time_built
 - description
 - adress
 - architects[]=Model C
 - places

Model B "photos":
 - time_taken
 - title
 - architects[]=Model C
 - places

Model C "architects"
- title
- time_born
- website
- items[]=Model A+Model B
</code>```

So items should be connected m:n to Model A or B for querying like "find architects by buildings in California". Model A and B can have multiple architects.

Is it possible to realize something like this in Django? I thought to use a Intermediate Model, but as I understood it does not help me too.

答:
Ok seems that there are two solutions:

changing the layout of Models like Horatiu mentioned

or what I found by random now and solved my problem what I was looking for: GenericForeignKeys - good example to explain and another question at stackoverflow

Body:
I guess it is a "normal" problem. I want to connect model C with different Models A,B,..

Model A "buildings"
 - time_built
 - description
 - adress
 - architects[]=Model C
 - places

Model B "photos":
 - time_taken
 - title
 - architects[]=Model C
 - places

Model C "architects"
- title
- time_born
- website
- items[]=Model A+Model B

So items should be connected m:n to Model A or B for querying like "find architects by buildings in California". Model A and B can have multiple architects.

Is it possible to realize something like this in Django? I thought to use a Intermediate Model, but as I understood it does not help me too.


问:
AWS lambda/api gateway does not redirect
I have a very simple spring route that im attempting to run on aws lambda. The route simply returns the text/string "redirect:/upload" instead of redirecting. I have the html file in the /resources/templates folder. </p>

```<code>@RequestMapping(path = "/test", method = RequestMethod.POST)
    public String UploadPage2() {
        return "redirect:/upload";
    }
</code>```

答:
I think the problem is from the return type of method: String.

You can do:

```<code>public RedirectView UploadPage2() {
    return new RedirectView("/upload");
}
</code>```

Second question

To return an view on path /test with GET request, you need another method with same path but different method

```<code>@RequestMapping(path = "/test", method = RequestMethod.GET)
public ModelAndView testGet(){
    return new ModelAndView("uploadview");
}

</code>```

Body:
I have a very simple spring route that im attempting to run on aws lambda. The route simply returns the text/string "redirect:/upload" instead of redirecting. I have the html file in the /resources/templates folder.

@RequestMapping(path = "/test", method = RequestMethod.POST)
    public String UploadPage2() {
        return "redirect:/upload";
    }

Body:
I think the problem is from the return type of method: String.

You can do:

public RedirectView UploadPage2() {
    return new RedirectView("/upload");
}

Second question

To return an view on path /test with GET request, you need another method with same path but different method

@RequestMapping(path = "/test", method = RequestMethod.GET)
public ModelAndView testGet(){
    return new ModelAndView("uploadview");
}


问:
How to respond a HTTPGET calling in ASP?
I’m using a SMS service which forwards the received SMSs to my web page by calling my URL using get method. My webpage should respond with an ‘Ok’ in plain text, however I don’t know how to do that, can you give me any idea?</p>

答:
You should use a generic handler (ashx) to do this, in a generic handler:

```<code>public class Handler1 : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        //your code here
        context.Response.ContentType = "text/plain";
        context.Response.Write("OK");
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}
</code>```

The reason to do it in a generic handler is that you avoid the entire page lifecycle that aspx pages have.

If you've want to get up and running fast in a aspx page, simply do this in something like page_load:

```<code>        Response.Clear();
        Response.Write("OK");
        Response.End();
</code>```

Body:
You should use a generic handler (ashx) to do this, in a generic handler:

public class Handler1 : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        //your code here
        context.Response.ContentType = "text/plain";
        context.Response.Write("OK");
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

The reason to do it in a generic handler is that you avoid the entire page lifecycle that aspx pages have.

If you've want to get up and running fast in a aspx page, simply do this in something like page_load:

        Response.Clear();
        Response.Write("OK");
        Response.End();


问:
Restrict number of subprocess.Popen
Following from run multiple instances of python script simultaneously I can now write a python program to run multiple instances.

```<code>import sys
import subprocess

for i in range(1000):
  subprocess.Popen([sys.executable, 'task.py', '{}in.csv'.format(i), '{}out.csv'.format(i)])
</code>```

This starts 1000 subprocess simultaneously. If the command that each subprocess is runs is computationally resource intensive, this can result in load on the machine (may even crash).

Is there a way where I can restrict the number of subprocess to be run at a time? For example something like this:

```<code>if (#subprocess_currently_running = 10) {
   wait(); // Or sleep
}
</code>```

That is just allow 10 subprocess to run at a time. In case one out of ten finishes start a new one.

答:
Counting Semaphore is an old-good mechanism which can be used to control/manage the maximum number of concurrently running threads/processes.

But as each subprocess.Popen object (implying process) needs to be waited for termination, the official doc tells us about the important downside of subprocess.Popen.wait()(for this case of multiple concurrent sub-processes):

Note: The function is implemented using a busy loop (non-blocking call and short sleeps). Use the asyncio module for an asynchronous
  wait: see asyncio.create_subprocess_exec.

Thus, it's preferable for us to switch to:

asyncio.create_subprocess_exec

asyncio.Semaphore

How it can be implemented:

```<code>import asyncio
import sys

MAX_PROCESSES = 10

async def process_csv(i, sem):
    async with sem:  # controls/allows running 10 concurrent subprocesses at a time
        proc = await asyncio.create_subprocess_exec(sys.executable, 'task.py',
                                                    f'{i}in.csv', f'{i}out.csv')
        await proc.wait()

async def main():
    sem = asyncio.Semaphore(MAX_PROCESSES)
    await asyncio.gather(*[process_csv(i, sem) for i in range(1000)])

asyncio.run(main())
</code>```

Title: Restrict number of subprocess.Popen

Body:
Following from run multiple instances of python script simultaneously I can now write a python program to run multiple instances.

import sys
import subprocess

for i in range(1000):
  subprocess.Popen([sys.executable, 'task.py', '{}in.csv'.format(i), '{}out.csv'.format(i)])

This starts 1000 subprocess simultaneously. If the command that each subprocess is runs is computationally resource intensive, this can result in load on the machine (may even crash).

Is there a way where I can restrict the number of subprocess to be run at a time? For example something like this:

if (#subprocess_currently_running = 10) {
   wait(); // Or sleep
}

That is just allow 10 subprocess to run at a time. In case one out of ten finishes start a new one.

Body:
Counting Semaphore is an old-good mechanism which can be used to control/manage the maximum number of concurrently running threads/processes.

But as each subprocess.Popen object (implying process) needs to be waited for termination, the official doc tells us about the important downside of subprocess.Popen.wait()(for this case of multiple concurrent sub-processes):

Note: The function is implemented using a busy loop (non-blocking call and short sleeps). Use the asyncio module for an asynchronous
  wait: see asyncio.create_subprocess_exec.

Thus, it's preferable for us to switch to:

asyncio.create_subprocess_exec

asyncio.Semaphore

How it can be implemented:

import asyncio
import sys

MAX_PROCESSES = 10

async def process_csv(i, sem):
    async with sem:  # controls/allows running 10 concurrent subprocesses at a time
        proc = await asyncio.create_subprocess_exec(sys.executable, 'task.py',
                                                    f'{i}in.csv', f'{i}out.csv')
        await proc.wait()

async def main():
    sem = asyncio.Semaphore(MAX_PROCESSES)
    await asyncio.gather(*[process_csv(i, sem) for i in range(1000)])

asyncio.run(main())


问:
After updating iOS, all applications using the framework stopped running on the device, but they run on the simulator
error:

 {
    dyld: Library not loaded: @rpath/Realm.framework/Realm
      Referenced from: /private/var/containers/Bundle/Application/43190AF8-F437-4B8F-9827-DDEA599AF618/Favorite Places.app/Favorite Places
      Reason: no suitable image found.  Did find:
        /private/var/containers/Bundle/Application/43190AF8-F437-4B8F-9827-DDEA599AF618/Favorite Places.app/Frameworks/Realm.framework/Realm: code signature invalid for '/private/var/containers/Bundle/Application/43190AF8-F437-4B8F-9827-DDEA599AF618/Favorite Places.app/Frameworks/Realm.framework/Realm'

```<code>    /private/var/containers/Bundle/Application/43190AF8-F437-4B8F-9827-DDEA599AF618/Favorite Places.app/Frameworks/Realm.framework/Realm: stat() failed with errno=25
    /private/var/containers/Bundle/Application/43190AF8-F437-4B8F-9827-DDEA599AF618/Favorite Places.app/Frameworks/Realm.framework/Realm: code signature invalid for '/private/var/containers/Bundle/Application/43190AF8-F437-4B8F-9827-DDEA599AF618/Favorite Places.app/Frameworks/Realm.framework/Realm'

    /private/var/containers/Bundle/Application/43190AF8-F437-4B8F-9827-DDEA599AF618/Favorite Places.app/Frameworks/Realm.framework/Realm: stat() failed with errno=1
    /private/var/containers/Bundle/Application/43190AF8-F437-4B8F-9827-DDEA599AF618/Favorite Places.app/Frameworks/Realm.framework/Realm: code signature invalid for '/private/var/containers/Bundle/Application/43190AF8-F437-4B8F-9827-DDEA599AF618/Favorite Places.app/Frameworks/Realm.framework/Realm'

    /private/var/containers/Bundle/Application/43190AF8-F437-4B8F-9827-DDEA599AF618/Favorite Places.app/Frameworks/Realm.framework/Realm: stat() failed with errno=1
(lldb)
}
</code>```

答:
Removing use_frameworks. It will break your Firebase pods.
For projects that utilize Firebase pods, your solutions consist of the following..

Downgrade your iOS device

Create & pay for an Apple Developer Program

Use the simulator and wait for future iOS updates that will hopefully once again allow free dev accounts to use Frameworks again..

This is very often issue which needs to be eliminated by official sources

Body:
error:

 {
    dyld: Library not loaded: @rpath/Realm.framework/Realm
      Referenced from: /private/var/containers/Bundle/Application/43190AF8-F437-4B8F-9827-DDEA599AF618/Favorite Places.app/Favorite Places
      Reason: no suitable image found.  Did find:
        /private/var/containers/Bundle/Application/43190AF8-F437-4B8F-9827-DDEA599AF618/Favorite Places.app/Frameworks/Realm.framework/Realm: code signature invalid for '/private/var/containers/Bundle/Application/43190AF8-F437-4B8F-9827-DDEA599AF618/Favorite Places.app/Frameworks/Realm.framework/Realm'

    /private/var/containers/Bundle/Application/43190AF8-F437-4B8F-9827-DDEA599AF618/Favorite Places.app/Frameworks/Realm.framework/Realm: stat() failed with errno=25
    /private/var/containers/Bundle/Application/43190AF8-F437-4B8F-9827-DDEA599AF618/Favorite Places.app/Frameworks/Realm.framework/Realm: code signature invalid for '/private/var/containers/Bundle/Application/43190AF8-F437-4B8F-9827-DDEA599AF618/Favorite Places.app/Frameworks/Realm.framework/Realm'

    /private/var/containers/Bundle/Application/43190AF8-F437-4B8F-9827-DDEA599AF618/Favorite Places.app/Frameworks/Realm.framework/Realm: stat() failed with errno=1
    /private/var/containers/Bundle/Application/43190AF8-F437-4B8F-9827-DDEA599AF618/Favorite Places.app/Frameworks/Realm.framework/Realm: code signature invalid for '/private/var/containers/Bundle/Application/43190AF8-F437-4B8F-9827-DDEA599AF618/Favorite Places.app/Frameworks/Realm.framework/Realm'

    /private/var/containers/Bundle/Application/43190AF8-F437-4B8F-9827-DDEA599AF618/Favorite Places.app/Frameworks/Realm.framework/Realm: stat() failed with errno=1
(lldb)
}


问:
How to append some object arrays in C#?

Possible Duplicate:

  How do I concatenate two arrays in C#?

How do I append some object arrays into one big object array?

For example, I have 3 elements of type: object[] and want to make one of it. How to do this?

答:
Or the good, old fashioned way:</p>

```<code>object[] objects = new object[objects1.Length + objects2.Length + objects3.Length];
int i = 0;
for(int j = 0; j<objects1.Length; j++)
  objects[i++] = objects1[j];
for(int j = 0; j<objects2.Length; j++)
  objects[i++] = objects2[j];
for(int j = 0; j<objects3.Length; j++)
  objects[i++] = objects3[j];
</code>```

Title: How to append some object arrays in C#?

Body:
Or the good, old fashioned way:

object[] objects = new object[objects1.Length + objects2.Length + objects3.Length];
int i = 0;
for(int j = 0; j<objects1.Length; j++)
  objects[i++] = objects1[j];
for(int j = 0; j<objects2.Length; j++)
  objects[i++] = objects2[j];
for(int j = 0; j<objects3.Length; j++)
  objects[i++] = objects3[j];


问:
Using javascript/jquery, is there a way to stop the rest of a webpage from loading until the header section is loaded?
I have a header (with a video inside), and the header is constructed using a plugin (I am on WordPress). When viewing the website on mobile, the header section takes some time to load, during which the rest of the content fills the empty space. When the header is finally loaded everything realigns as it should (the whole thing takes like 4 seconds).

However, the client prefers the rest of the page is loaded only after the header is there. Is there some javascript/jquery way of doing this that I am missing? Thank you.

Assume the page is constructed this way:

```<code><html>
<head>...</head>
<body>
<section class="header">...</section>
<section class="section1">...</section>
<section class="section2">...</section>
<section class="section3">...</section>
</body>
</html>
</code>```

答:
As Heretic Monkey suggested, use jQuery's ready() function.

A rudimentary implementation would be to update your section classes to display:none and then in your script for this page:

```<code>$(document).ready(function() {
  $(".section1).show();
  $(".section2).show();
  $(".section3).show();
});
</code>```

I believe the default implementation of show() is to set display:block so if you wanted a different value for that property like inline then you can set the value manually through the selector like:

```<code>$(".section1").attr('style', 'display:inline');
</code>```

Body:
I have a header (with a video inside), and the header is constructed using a plugin (I am on WordPress). When viewing the website on mobile, the header section takes some time to load, during which the rest of the content fills the empty space. When the header is finally loaded everything realigns as it should (the whole thing takes like 4 seconds).

However, the client prefers the rest of the page is loaded only after the header is there. Is there some javascript/jquery way of doing this that I am missing? Thank you.

Assume the page is constructed this way:

...

...

...

...

...

Body:
As Heretic Monkey suggested, use jQuery's ready() function.

A rudimentary implementation would be to update your section classes to display:none and then in your script for this page:

$(document).ready(function() {
  $(".section1).show();
  $(".section2).show();
  $(".section3).show();
});

I believe the default implementation of show() is to set display:block so if you wanted a different value for that property like inline then you can set the value manually through the selector like:

$(".section1").attr('style', 'display:inline');


问:
Multiply two matrices in SML
I want to write a function in SML/NJ which will take 2 matrices as an arguments and it will multiply them.

I can only use:

function dot, which take 2 vectors and calculate scalar product:

```<code>fun dot (xs: int list, ys: int list): int =
    List.foldl (fn (x,y) => x+y)
       0
       (ListPair.map (fn (x,y) => x*y) (xs, ys))
</code>```

function transpose, which take 1 matrix and calculate transpose of this matrix:

```<code>fun transpose (m: 'a list list): 'a list list =
    List.tabulate (List.length (List.nth (m, 0)),
           fn x => List.map (fn y => (List.nth (y, x))) m)
</code>```

anonymous function

structures List, ListPair and Math

The function I want to write should be like this:

```<code>fun multiply (a: int list list, b: int list list): int list list
</code>```

So far I have done this:

```<code>fun multiply (a: int list list, b: int list list): int list list =
case a of
[] => []
  | g::rep => [(List.map (fn y => dot(g, y)) transpose(b))] @ (multiply(rep, b))
</code>```

But I got this error:

```<code>test.sml:66.21-66.62 Error: operator and operand do not agree [tycon mismatch]
  operator domain: int list list
  operand:         'Z list list -> 'Z list list
  in expression:
(List.map (fn y => dot <exp>)) transpose
</code>```

I get no errors, if in the last line of function multiply I write b instead of tranpose(b), but of course, if I do this, I don't the the resoult I want:

```<code>fun multiply (a: int list list, b: int list list): int list list =
case a of
[] => []
  | g::rep => [(List.map (fn y => dot(g, y)) b)] @ (multiply(rep, b))
</code>```

I don't know what else should I do. Can anybody pease help me?

答:
At least I succeeded using your scheme</p>

```<code>exception dim_Error;

fun listPair (l1:int list) (l2:int list): (int * int) List.list =
`if not (List.length l1 = List.length l2) then raise dim_Error
    else List.tabulate (List.length l1, fn i => (List.nth(l1, i),List.nth(l2, i)));`

fun dotprod (l1:int list) (l2:int list): int =
    List.foldl (fn (x,y) => x+y) 0 (map (fn (x,y) => x*y) (listPair l1 l2));

fun transpose (matrix: int list list):int list list =
    List.tabulate (List.length (List.nth (matrix, 0)), fn i => List.map (fn j => List.nth (j, i)) matrix);

fun multiply (matrix1: int list list) (matrix2: int list list): int list list =
case matrix1 of
    [] => []
    |    x::xr => [List.map (fn y => dotprod x y) (transpose matrix2)] @ (multiply xr matrix2);

val A = [[ 21,  ~2,  3, ~1], [  2, 115,  6,  7], [ ~6,  9, 210, 11], [ 13, 14, ~19, 15], [ ~2, 21, ~99,  3], [  5, ~4,  ~1,  9]];
val B = [[2, ~6, 0, 3, 9], [~4, ~1, 2, 1, ~2], [~6, 5, 3, ~5, 1], [10, 9, ~4, 9, ~7]];
val C = [[~4, ~3, 7], [1, ~1, ~2], [~5, 3, 7], [8, ~7, 2], [~8, 3, 6]];

multiply (multiply  A B) C;
</code>```

Title: Multiply two matrices in SML

Body:
I want to write a function in SML/NJ which will take 2 matrices as an arguments and it will multiply them.

I can only use:

function dot, which take 2 vectors and calculate scalar product:

fun dot (xs: int list, ys: int list): int =
    List.foldl (fn (x,y) => x+y)
       0
       (ListPair.map (fn (x,y) => x*y) (xs, ys))

function transpose, which take 1 matrix and calculate transpose of this matrix:

fun transpose (m: 'a list list): 'a list list =
    List.tabulate (List.length (List.nth (m, 0)),
           fn x => List.map (fn y => (List.nth (y, x))) m)

anonymous function

structures List, ListPair and Math

The function I want to write should be like this:

fun multiply (a: int list list, b: int list list): int list list

So far I have done this:

fun multiply (a: int list list, b: int list list): int list list =
case a of
[] => []
  | g::rep => [(List.map (fn y => dot(g, y)) transpose(b))] @ (multiply(rep, b))

But I got this error:

test.sml:66.21-66.62 Error: operator and operand do not agree [tycon mismatch]
  operator domain: int list list
  operand:         'Z list list -> 'Z list list
  in expression:
(List.map (fn y => dot <exp>)) transpose

I get no errors, if in the last line of function multiply I write b instead of tranpose(b), but of course, if I do this, I don't the the resoult I want:

fun multiply (a: int list list, b: int list list): int list list =
case a of
[] => []
  | g::rep => [(List.map (fn y => dot(g, y)) b)] @ (multiply(rep, b))

I don't know what else should I do. Can anybody pease help me?

Body:
At least I succeeded using your scheme

exception dim_Error;

fun listPair (l1:int list) (l2:int list): (int * int) List.list =
`if not (List.length l1 = List.length l2) then raise dim_Error
    else List.tabulate (List.length l1, fn i => (List.nth(l1, i),List.nth(l2, i)));`

fun dotprod (l1:int list) (l2:int list): int =
    List.foldl (fn (x,y) => x+y) 0 (map (fn (x,y) => x*y) (listPair l1 l2));

fun transpose (matrix: int list list):int list list =
    List.tabulate (List.length (List.nth (matrix, 0)), fn i => List.map (fn j => List.nth (j, i)) matrix);

fun multiply (matrix1: int list list) (matrix2: int list list): int list list =
case matrix1 of
    [] => []
    |    x::xr => [List.map (fn y => dotprod x y) (transpose matrix2)] @ (multiply xr matrix2);

val A = [[ 21,  ~2,  3, ~1], [  2, 115,  6,  7], [ ~6,  9, 210, 11], [ 13, 14, ~19, 15], [ ~2, 21, ~99,  3], [  5, ~4,  ~1,  9]];
val B = [[2, ~6, 0, 3, 9], [~4, ~1, 2, 1, ~2], [~6, 5, 3, ~5, 1], [10, 9, ~4, 9, ~7]];
val C = [[~4, ~3, 7], [1, ~1, ~2], [~5, 3, 7], [8, ~7, 2], [~8, 3, 6]];

multiply (multiply  A B) C;


问:
R Paste All Variables With Specific Prefix
I would like to paste the content of a set of variables with a given prefix. For example, given this data:

```<code>data <- data.frame(var_1=c(1,2,3,4,5),
                   var_2=c(1,2,3,4,5),
                   var_3=c(1,2,3,4,5))
</code>```

I want to replicate the following behavior without listing each variable name individually, instead pasting all variables with the prefix "var_":

```<code>my_strings <- paste(toy_data$var_1,
                    toy_data$var_2,
                    toy_data$var_3)

my_strings
[1] "1 1 1" "2 2 2" "3 3 3" "4 4 4" "5 5 5"
</code>```

答:
We can do this with do.call for row wise paste

```<code>do.call(paste, data[startsWith(names(data), 'var')])
#[1] "1 1 1" "2 2 2" "3 3 3" "4 4 4" "5 5 5"
</code>```

Or instead of startsWith, use grep

```<code>do.call(paste, data[grep("^var_\\d+$", names(data))])
</code>```

Or with Reduce

```<code>Reduce(paste, data[startsWith(names(data), 'var')])
#[1] "1 1 1" "2 2 2" "3 3 3" "4 4 4" "5 5 5"
</code>```

Another option is apply, but it would be slow

```<code>apply(data[startsWith(names(data), 'var')], 1, paste, collapse= ' ')
#[1] "1 1 1" "2 2 2" "3 3 3" "4 4 4" "5 5 5"
</code>```

Body:
I would like to paste the content of a set of variables with a given prefix. For example, given this data:

data <- data.frame(var_1=c(1,2,3,4,5),
                   var_2=c(1,2,3,4,5),
                   var_3=c(1,2,3,4,5))

I want to replicate the following behavior without listing each variable name individually, instead pasting all variables with the prefix "var_":

my_strings <- paste(toy_data$var_1,
                    toy_data$var_2,
                    toy_data$var_3)

my_strings
[1] "1 1 1" "2 2 2" "3 3 3" "4 4 4" "5 5 5"

Body:
We can do this with do.call for row wise paste

do.call(paste, data[startsWith(names(data), 'var')])
#[1] "1 1 1" "2 2 2" "3 3 3" "4 4 4" "5 5 5"

Or instead of startsWith, use grep

do.call(paste, data[grep("^var_\\d+$", names(data))])

Or with Reduce

Reduce(paste, data[startsWith(names(data), 'var')])
#[1] "1 1 1" "2 2 2" "3 3 3" "4 4 4" "5 5 5"

Another option is apply, but it would be slow

apply(data[startsWith(names(data), 'var')], 1, paste, collapse= ' ')
#[1] "1 1 1" "2 2 2" "3 3 3" "4 4 4" "5 5 5"


问:
What is the Ideal way to return data from function without leaking memory?
In IPhone Development ObjC , I wonder what is the right approach for functions to return some values in Dictionaries or Arrays. I mean should they return autorelease objects, but wouldn't it be bad if I am using too many functions to return values, like getUserRecordsFromDB() function will return all the user records, so should they return me autorelease objects? also when I am calling them multiple times, suppose with a span of 4 seconds to get the newely updated data. Can somebody let me an ideal scanario of how to get data from a function called frequently in the flow of program, and not leaking the memory.</p>

答:
You should stick to the cocoa programming guidelines.
This is a place to start, but there is a lot more to find on the subject.</p>


问:
ts-jest providing different instances of a mock the test and the module
I'm using an automatic mock of a file that exports a function, actual file looks like

```<code>export const serialize = (type:boolean) => (data) => {....}
</code>```

In the debugger I can see that in the module (controller) I'm testing, that serialize is called and is a mock.

in my test, I have

```<code>import {controller} from '../../src/controller'
import {serialize} from '../../src/serialize'
jest.mock('../../src/serialize');

describe('test', () => {
    it('serialize'), (done) => {
       controller.put();  //<-- calls serialize
       expect(serialize).toHaveBeenCalled();  // <-- this fails, with 0 calls
    }
})
</code>```

答: The issue was that in the Controller, the serialize function was called in a way that caused the mockConfig in jest which is stored in a WeakMap, to be removed from the weak map. Hence I moved the call so the GC did collect the reference.</p>

Body:
I'm using an automatic mock of a file that exports a function, actual file looks like

export const serialize = (type:boolean) => (data) => {....}

In the debugger I can see that in the module (controller) I'm testing, that serialize is called and is a mock.

in my test, I have

import {controller} from '../../src/controller'
import {serialize} from '../../src/serialize'
jest.mock('../../src/serialize');

describe('test', () => {
    it('serialize'), (done) => {
       controller.put();  //<-- calls serialize
       expect(serialize).toHaveBeenCalled();  // <-- this fails, with 0 calls
    }
})


问:
While trying to authenticate users in shopify, getting error: Field 'CustomerAccessTokenCreateInput' doesn't exist on type 'Mutation'
I am using node.js in my application, with shopify-api-node (v3.2.0), to authenticate customer login along with other features if shopify. As per shopify documentation (https://shopify.dev/docs/storefront-api/reference/mutation/customeraccesstokencreate) I am using GraphQL to access shopify API.
My code looks something like this below :-

```<code>const Shopify = require('shopify-api-node');

const shopify = new Shopify({
  shopName: process.env.SHOPIFY_DOMAIN_NAME,
  apiKey: process.env.SHOPIFY_API_KEY,
  password: process.env.SHOPIFY_API_KEY_PASSWORD
});

  const query = `mutation {
    customerAccessTokenCreate (input: {
      email: "user@mail.com",
      password: "password123"
     }
    )
    {
      customerAccessToken {
        accessToken
        expiresAt
      }
      customerUserErrors {
        code
        field
        message
      }
    }
  }`;

  shopify
    .graphql(query)
    .then((output) => {
      console.log(output);
    })
    .catch((err) => {
      console.error(err)
    });
</code>```

After this I am getting below error :-

```<code>Error: Field 'customerAccessTokenCreate' doesn't exist on type 'Mutation'
    at got.then (/Users/admin/Documents/Code/shopify-node-app/node_modules/shopify-api-node/index.js:239:19)
    at process._tickCallback (internal/process/next_tick.js:68:7)
  locations: [ { line: 2, column: 5 } ],
  path: [ 'mutation', 'customerAccessTokenCreate' ],
  extensions:
   { code: 'undefinedField',
     typeName: 'Mutation',
     fieldName: 'customerAccessTokenCreate' }
</code>```

Even I am getting the same thing from postman itself.

Any help would be appreciated.

答:
There are two types of GraphQL:

the storefront GraphQL - https://shopify.dev/docs/storefront-api/reference

the admin GraphQL - https://shopify.dev/docs/admin-api/graphql/reference

While they seems similar the strorefront is much more limited but can be used on the front-end, while the admin one is more rich in method and functionality but can't be used safely on the font-end.

The documentation and the method you are trying to make is referring to the Storefront API, but the package you are using is for the Admin GraphQL API.

You can create a storefront access token via the storefrontAccessToken method if you want to make storefront request but the Admin API GraphQL allows for more customization.

So you need to make sure you are using the proper API.

If you plan to use the storefront API, you shouldn't use NodeJS and just create a private app ( from Admin -> APP -> Private App) which will provide you a Store Front Access Token (if you enable it at the bottom and select the proper scopes) that can be used directly on the front-end.

If you plan to use the Admin API, you will need to create a public app and host it, then you can use NodeJS and pass the information via a Proxy in Shopify.

Summary

You are making a request to the Storefront API, while using a library for the Admin API.

Body:
I am using node.js in my application, with shopify-api-node (v3.2.0), to authenticate customer login along with other features if shopify. As per shopify documentation (https://shopify.dev/docs/storefront-api/reference/mutation/customeraccesstokencreate) I am using GraphQL to access shopify API.
My code looks something like this below :-

const Shopify = require('shopify-api-node');

const shopify = new Shopify({
  shopName: process.env.SHOPIFY_DOMAIN_NAME,
  apiKey: process.env.SHOPIFY_API_KEY,
  password: process.env.SHOPIFY_API_KEY_PASSWORD
});

  const query = `mutation {
    customerAccessTokenCreate (input: {
      email: "user@mail.com",
      password: "password123"
     }
    )
    {
      customerAccessToken {
        accessToken
        expiresAt
      }
      customerUserErrors {
        code
        field
        message
      }
    }
  }`;

  shopify
    .graphql(query)
    .then((output) => {
      console.log(output);
    })
    .catch((err) => {
      console.error(err)
    });

After this I am getting below error :-

Error: Field 'customerAccessTokenCreate' doesn't exist on type 'Mutation'
    at got.then (/Users/admin/Documents/Code/shopify-node-app/node_modules/shopify-api-node/index.js:239:19)
    at process._tickCallback (internal/process/next_tick.js:68:7)
  locations: [ { line: 2, column: 5 } ],
  path: [ 'mutation', 'customerAccessTokenCreate' ],
  extensions:
   { code: 'undefinedField',
     typeName: 'Mutation',
     fieldName: 'customerAccessTokenCreate' }

Even I am getting the same thing from postman itself.

Any help would be appreciated.